2014-02-24 43 views
0

如何在不發送實際工作表模板的情況下在Excel工作表之間傳輸數據?在不發送實際工作表模板的情況下在Excel工作表之間傳輸數據

來源是.xls;目標是.xlsm

我有一個PowerShell腳本,從源到目的地傳送一個工作和做一些重命名使其出現給最終用戶,彷彿只有數據被轉移,但在現實中,它是將工作表複製到目標文件中,然後重命名原始工作表,然後將複製的工作表重命名以代替原始工作表,然後刪除現在重命名但原始的工作表。

這是一個問題,因爲工作簿中的某些單元格會引用原始工作表(它會被重命名並刪除),因此引用會中斷並變成#REF!

有沒有辦法簡單地將源工作表的內容轉移到空目標工作表中,而無需實際複製/重命名工作表?

如果不是,我該如何保留我的腳本,但要確保Excel中的引用不會被破壞?

如果你是好奇,想看看我的劇本,因爲它目前的工作,那就是:

$file1 = $args[0] 

$file2 = $args[1] 

    <# 
     $file1 = 'c:\source.xls' # source's fullpath 
     $file2 = 'c:\destination.xlsm' # destination's fullpath 
    #> 

    $xl = new-object -c excel.application 
    $xl.displayAlerts = $false # don't prompt the user 

    $wb1 = $xl.workbooks.open($file1, $null, $true) # open source, readonly 
    $wb2 = $xl.workbooks.open($file2) # open target 
    $sh2_wb2 = $wb2.sheets.item('SheetOfInterest') # sheet in destination workbook 
    $sheetToCopy = $wb1.sheets.item('SheetOfInterest') # source sheet to copy 

    $sh2_wb2.Name = "OldSheetOfInterest" #Rename original sheet in template 
    $sheetToCopy.copy($sh2_wb2) # copy source sheet to destination workbook 

    $sh2_wb2 = $wb2.sheets | where {$_.name -eq "OldSheetOfInterest"} 
    $sh2_wb2.delete() #Delete original sheet in template 

    $wb1.close($false) # close source workbook w/o saving 
    $wb2.close($true) # close and save destination workbook 
    $xl.quit() 
    spps -n excel 

回答

1

嘗試......

$file1 = $args[0] 

$file2 = $args[1] 

    <# 
     $file1 = 'c:\source.xls' # source's fullpath 
     $file2 = 'c:\destination.xlsm' # destination's fullpath 
    #> 

$xl = new-object -c excel.application 
$xl.displayAlerts = $false # don't prompt the user 

$wb1 = $xl.workbooks.open($file1, $null, $true) # open source, readonly 
$wb2 = $xl.workbooks.open($file2) # open target 
$destination = $wb2.sheets.item('SheetOfInterest') # sheet in destination workbook 
$source = $wb1.sheets.item('SheetOfInterest') # source sheet to copy 

[void]$destination.UsedRange.Clear() # Clear cells that have data in the destination 
[void]$source.UsedRange.Copy() # Copy range of cells with data in them on source sheet 
[void]$destination.Range("A1","A1").Select() # Set first cell of destination as active cell 
[void]$destination.paste() # Paste data into destination sheet starting at active cell (A1) 
[void]$destination.Range("A1","A1").Select() # Set first cell of destination as active cell, otherwise is has everything selected 

$wb1.close($false) # close source workbook w/o saving 
$wb2.close($true) # close and save destination workbook 
$xl.quit() 
spps -n excel 
+0

謝謝!我明天會試試這個。 –

相關問題