将Excel工作表行数据值复制到另一个Excel工作簿

时间:2018-11-23 16:10:28

标签: excel powershell

我是使用Powershell的初学者,并且遇到了一个问题,即使在研究并结合了其他问题的解决方案后也无法解决。我试图将值从一个Excel工作簿中的一行数据复制并粘贴到另一个。我的脚本正在运行,但是要复制的信息未出现在目标工作簿中。

我的代码如下:

Param( 
    $sourcefile = "C:\Desktop\GL_Detail_Test_1\Source_File.xlsx",
    $destfile = "C:\Desktop\GL_Detail_Test_Output\Dest_File.xlsx",
    $Worksheet1 = "Named_Worksheet",
    $rowNbr = 0,
    $SourceCol1 = "A"
    ) #end param

$Excel = New-Object -ComObject "Excel.Application"
$Excel.Visible = $false        #Runs Excel in the background.
$Excel.DisplayAlerts = $false        #Supress alert messages.

# Setup the Workbooks
$SourceWorkbook       = $Excel.Workbooks.open($sourcefile)
$TargetWorkbook       = $Excel.workBooks.open($destfile)

# Load the Worksheets
$SourceWorksheet      = $SourceWorkbook.WorkSheets.item($Worksheet1).activate()
$TargetWorksheet      = $TargetWorkbook.WorkSheets.item(1).activate()

# Count Max Rows
$rowMax               = $SourceWorkBook.Worksheets.Item($Worksheet1).UsedRange.Rows.count

# Get the Source Location
$rowNbr               = $rowMax - 5
$SourceRow            = $SourceCol1 + $rowNbr
$SourceRange          = $SourceWorkbook.WorkSheets.item($Worksheet1).range($sourceRow).EntireRow.copy()

#Look value to ensure that it keeps searching for an empty cell
$foundEmptyCell = $false

#The first row to check in the range
$rowNumber = 1

#Declare the variable
$range = ""

#Loop through rows until you find one without a value
while (!$foundEmptyCell)
{
   $range = "A{0}" -f $rowNumber
   $TargetRange1 = $TargetWorkBook.WorkSheets.item(1).range($range).EntireRow;
   if ($TargetRange1.Value2 -eq $null)
   {

      $foundEmptyCell = $true
   }
   else
   {
      #Write-Host $TargetRange1.Value2
      $rowNumber++
   }
 }

#Paste the value in
$TargetRange1.PasteSpecial(-4163)

#Save and close
$TargetWorkbook.Save()
$excel.quit()
while( [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)){}
function release-comobject($ref) 
{
  while ([System.Runtime.InteropServices.Marshal]::ReleaseComObject($ref) -gt 0) { }
  [System.GC]::Collect()
}

我们将不胜感激或提供任何帮助。

0 个答案:

没有答案