Search code examples
excelpowershellcopy-paste

Change from single target to last used cell in column


I am sure this is a common question. I am trying to just paste instead of to the target cell in the paste range, to go to the last used cell in the column + 1, so it just appends the target spread sheet. What do I need to change here?

I have tried some of the suggestions on here but keep getting errors, probably because I am using $lastRow = $ExcelWorkSheet.UsedRange.rows.count + 1 in the wrong place (haven't been using powershell that long).

If anyone can show easiest way to do this would be great. Thanks!

$Excel = New-Object -ComObject "Excel.Application"
$Excel.Visible=$true 

$Workbook = $Excel.Workbooks.Open($pathxlsx)
$TempWorkbook = $Excel.Workbooks.Opentext($pathcsv)

$temp = $excel.Workbooks.Item(2)  
$temp = $temp.Worksheets.Item(1)
$CopyRange = $temp.Range("C15") 
$CopyRange.Copy()  

$workbooksheet = $Workbook.Worksheets.Item(1)
$Workbooksheet.activate()
$PasteRange = $workbooksheet.Range("C10")
$workbooksheet.Paste($PasteRange)

EDIT - Ok, got it to do something different, but still not what I want.

$Excel = New-Object -ComObject "Excel.Application"
$Excel.Visible=$true 

$Workbook = $Excel.Workbooks.Open($pathxlsx) 
$TempWorkbook = $Excel.Workbooks.Opentext($pathcsv) 

$temp = $excel.Workbooks.Item(2)  
$temp = $temp.Worksheets.Item(1) 
$CopyRange = $temp.Range("C15") 
$CopyRange.Copy()  

$workbooksheet = $Workbook.Worksheets.Item(1) 
$ExcelWorkSheet.UsedRange.rows.count
$lastRow = $workbooksheet.UsedRange.rows.count + 1
$Workbooksheet.activate()
$PasteRange = $workbooksheet.Range("C" + $lastrow) 
$workbooksheet.Paste($PasteRange)

Solution

  • I ended up just creating an excel template with a power query for this issue. This plus a formula to transpose the data allowed for a clean copy and paste with the data I needed in the form i needed it.