简体   繁体   中英

How do I copy info from a specific cell from one workbook in excel and paste it to a specific cell to another workbook using Powershell?

So basically I wanted to pull information from one cell, using a specific location, copy that info and paste it into a whole other workbook with a specific cell location all while using Powershell.

An example of this would be: copy from cell B2 in wb1 (sheet4) --> paste in A2 in wb2 (sheet3)

Also, I want to be able to do this multiple different times (for different cells of course)

I tried the below code and this just had me extracting the entire workbook to another work. I know there could be a way to pull a specific cell but I'm not sure how to do that just yet. Can someone please help?

$file1 = 'C:\Book1.xlsx' # <-- source file full path
$file2 = 'C:\Book2.xlsx' # <-- destination file full path
$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(1) # 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

PS There is an answered question about this but the code uses C#. Can it be translated to Powershell?

Thanks!

You can get/set a specific cell value with:

# source/target cell
$sourceRange = $wb1.Worksheets.Item('Sheet4').Range('B2','B2')
$targetRange = $wb2.Worksheets.Item('Sheet3').Range('A2','A2')

# copy source value to target
$targetRange.Value = $sourceRange.Value

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