如何在不发送实际工作表模板的情况下在Excel工作表之间传输DATA?
来源为.xls
; desination是.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
答案 0 :(得分: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