简体   繁体   中英

I want to copy 2 Excel Worksheets at the same time to a new workbook

To explain, I currently have like 90 different files that I need to, after processing, separate the first two tabs of the file and copy paste to a new workbook and save that workbook, with the name of the person who the report will go to (name is in each of the files) and email them out.

I need help for 2 things. I'm unable to save the file using the cell as a reference for the name and copy two (2) sheets at the same time (sheet1 is dependent on sheet2, copy/pasting separately breaks the connection).

Can anyone help with this?

UPDATE: I've been able to make the save as work :), but still need help in being able to copy two worksheets at the same time.

Here is my UPDATED code:

$Files = GCI '\\networkfolder\workingfolder' | ?{$_.Extension -Match "xlsx?"} | select -ExpandProperty FullName

#Launch Excel, and make it do as its told (supress confirmations)
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $True
$Excel.DisplayAlerts = $False

#Loop through files and perform tasks
ForEach($File in $Files[0..4]){
$Source = $Excel.Workbooks.Open($File,$true,$true) #Open's source
$NewWorkBook = $Excel.Workbooks.Add() # open target (New Workbook)

$sh1_wb1 = $NewWorkBook.sheets.item(1) # first sheet in destination workbook

$sheetToCopy2 = $Source.sheets.item(2) # Alias for 2nd Sheet
$sheetToCopy = $Source.sheets.item(1) # Alias for 1st Sheet
$SheetsToCopy = ($sheetToCopy, $sheetToCopy2) # Selects sheets 1 and 2
#I think the fix to copy both sheets at the same time would be in this step

$SheetsToCopy.copy($sh1_wb1) # copy source sheet 1 & 2 to destination workbook

$ws1 = $NewWorkBook.worksheets | where {$_.name -eq "Charts Data Tab"} #Selects Sheet2
$ws2 = $NewWorkBook.worksheets | where {$_.name -eq "Dashboard"} #Selects Sheet1

$range = $ws1.Rows.Item("1:5000")
[void]$range.select()
$range.Copy();
$range.PasteSpecial(-4163)
$Source.close($false) # close source workbook w/o saving

$Name = $ws1.Cells.Item.Invoke(2,4).Value2  #Registers contents of D2 of Sheet2

$FName = "\\networkfolder\Testing\$Name.xlsx"

$NewWorkBook.SaveAs($FName)
Start-Sleep 50000
}
$xl.quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)

You should have a look at the PSExcel library. It provides a lot of functions for working with Excel.

http://ramblingcookiemonster.github.io/PSExcel-Intro/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM