Using Powershell to Append a table to the end of an Excel File (The Last Row)

后端 未结 2 532
鱼传尺愫
鱼传尺愫 2020-12-17 07:37

I\'ve written a Powershell script that copies a table from Microsoft Word and pastes them to an excel document. I want to append it after the last used row in column A.

相关标签:
2条回答
  • 2020-12-17 07:54

    The object returned by $ExcelWorkSheet.UsedRange has a property rows (not a method, you can't use a parameter). This means that $ExcelWorkSheet.UsedRange.rows.count will work, but won't give you the desired result (it will give you the row number of the las trow for the longest column).

    To append something after the last used cell in column A, try the following:

    $xldown = -4121 # see: http://msdn.microsoft.com/en-us/library/bb241212(v=office.12).aspx
    $xlup = -4162
    $Excel = New-Object -ComObject Excel.Application
    $Excel.Visible = $True
    $ExcelWordBook = $Excel.Workbooks.Open($ExcelPath)
    $ExcelWorkSheet = $Excel.WorkSheets.item("Sheet1")
    $ExcelWorkSheet.activate()
    
    # Find the last used cell
    $lastRow = $ExcelWorksheet.cells.Range("A1048576").End($xlup).row
    
    $nextRow = $lastRow + 1
    $range = $ExcelWorkSheet.Range("A$nextRow")
    $ExcelWorkSheet.Paste($range)
    
    0 讨论(0)
  • 2020-12-17 08:11

    Thanks I ended up going a different route that's more dynamic instead of using "A9924082480198" as the end of the range.

    $Excel = New-Object -ComObject Excel.Application
    $Excel.Visible = $True
    $ExcelWordBook = $Excel.Workbooks.Open($ExcelPath)
    $ExcelWorkSheet = $Excel.WorkSheets.item("sheet1")
    $ExcelWorkSheet.activate()
    
    $lastRow = $ExcelWorkSheet.UsedRange.rows.count + 1
    $Excel.Range("A" + $lastrow).Activate()
    $ExcelWorksheet.Paste()
    
    0 讨论(0)
提交回复
热议问题