vba 使用 Powershell 将 Excel 工作表从一个工作簿复制到另一个工作簿

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3226096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 11:52:15  来源:igfitidea点击:

Copy Excel Worksheet from one Workbook to another with Powershell

excelcompowershellexcel-vbaoffice-automationvba

提问by idazuwaika

I'd like to copy (or move) a worksheet from one workbook to another workbook with Powershell.

我想使用 Powershell 将工作表从一个工作簿复制(或移动)到另一个工作簿。

I had done this before and cant remember how. I think I used CopyTo() function.

我以前做过这个,不记得是怎么做的。我想我使用了 CopyTo() 函数。

Just to get started.

只是为了开始。

$missing = [System.Type]::missing
$excel = New-Object -Com Excel.Application

$wb1 = $excel.Workbooks.Add($missing)
$wb2 = $excel.Workbooks.Add($missing)

# Now, to copy worksheet "Sheet3" from $wb2 into $wb1 as second worksheet.
# How?

回答by dugas

See postfrom Kiron

参见Kiron 的帖子

Changed index to copy to second sheet:

将索引更改为复制到第二张纸:

$file1 = 'C:\Users\eric\Documents\Book1.xlsx' # source's fullpath
$file2 = 'C:\Users\eric\Documents\Book2.xlsx' # destination's fullpath
$xl = new-object -c excel.application
$xl.displayAlerts = $false # don't prompt the user
$wb2 = $xl.workbooks.open($file1, $null, $true) # open source, readonly
$wb1 = $xl.workbooks.open($file2) # open target
$sh1_wb1 = $wb1.sheets.item(2) # second sheet in destination workbook
$sheetToCopy = $wb2.sheets.item('Sheet3') # source sheet to copy
$sheetToCopy.copy($sh1_wb1) # copy source sheet to destination workbook
$wb2.close($false) # close source workbook w/o saving
$wb1.close($true) # close and save destination workbook
$xl.quit()
spps -n excel