Powershell Excel条件复制循环运行缓慢

时间:2015-04-15 08:49:54

标签: excel powershell

我有一个powershell脚本,它为A列中的每个唯一项创建一个新工作表,然后将每个唯一项的相关行复制到相应的工作表。它工作正常,它只是非常慢,我想知道是否有一种简单的方法来加快它。这是脚本:

$arrExcelValues = @()
$executingScriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
$path1 = Join-Path $executingScriptDirectory "my_workbook.xls"
$Excel = new-object -comobject excel.application
$Excel.Visible = $False
$Workbook1 = $Excel.Workbooks.open($path1)
$Worksheet1 = $Workbook1.WorkSheets.item(2) 

$rowCount = $worksheet1.UsedRange.Rows.Count
$colCount = $worksheet1.UsedRange.Columns.Count
$i = 2
Do {
    $arrExcelValues += $Worksheet1.Cells.Item($i, 1).Value()
    $i++
}
While ($Worksheet1.Cells.Item($i,1).Value() -ne $null)
foreach ($objItem in $arrExcelValues) {
    write-host $objItem 
}
$arrExcelValues = $arrExcelValues | select -uniq

$x=0
While ($x -ne $arrExcelValues.length) {
$Workbook1.Worksheets.add([System.Reflection.Missing]::Value,$Workbook1.Worksheets.Item($Workbook1.Worksheets.count))
$sheet_new = $Workbook1.worksheets.Item($Workbook1.Worksheets.count)
$sheet_new.name = $arrExcelValues[$x]
$SaveSheet = $Workbook1.WorkSheets.item($arrExcelValues[$x])

# Copy header row...
1..($ColCount) | % {$SaveSheet.Cells.Item(1,$_) = $Worksheet1.Cells.Item(1,$_)}

# Find rows to copy...
$TestName = $arrExcelValues[$x]
$SaveRow = 2
2..($rowCount) | % {
    If (($Worksheet1.Cells.Item($_,1).Text).ToUpper() -match $TestName) {
        $row = $_
        1..($ColCount) | % {$SaveSheet.Cells.Item($SaveRow,$_) = $Worksheet1.Cells.Item($Row,$_).Text}
        $SaveRow ++}
}
$x++
}

$workbook1.Save()
$workbook1.close($true)
$Excel.Quit()
Remove-Variable -Name excel 
Remove-Variable -Name Worksheet1 
Remove-Variable -Name Workbook1 
Remove-Variable -Name path1

1 个答案:

答案 0 :(得分:0)

而不是$Excel.Visible = $Falsefalse尝试使用$Excel.ScreenUpdating = $false

也许这会有所作为?