我尝试使用 Powershell 7 版本中的 ForEach-Object -Parallel 选项并行执行 Excel 减法运算的示例程序。
Param(
[Parameter(Position=1)]
[string]$input_filename,
[Parameter(Position=2)]
[string]$output_filename
)
# Instantiate Excel instnace
$excel_test = New-Object -ComObject Excel.Application
# Make the instance visiable to work with it
$excel_test.visible = $False
# Catch alerts
$excel_test.DisplayAlerts = 'False'
# Add in the file source
$workbook = $excel_test.Workbooks.Add($input_filename)
# Choose a sheet in the workbook
$Sheet = $excel_test.Worksheets.Item(1)
$totalNoOfRecords = ($Sheet.UsedRange.Rows).count
# Assign the formula to the target variable
$Sheet.Cells.Item(1,3) = "Substraction"
Measure-Command {
2..$totalNoOfRecords | ForEach-Object -Parallel {
# Assign a formula to the target variable
$i = $_
$strFormula_1 = "=(A$($i)- B$($i))"
Write-Host $strFormula_1
Write-Host $i
$Sheet.Cells.Item($i,3) = "=(A$($i) - B$($i))"
} -ThrottleLimit 3
}
# Exit the XLS
$workbook.SaveAs($output_filename)
$workbook.close($false)
$excel_test.Quit()
但是,它会引发如下错误,
InvalidOperation:
Line |
8 | $Sheet.Cells.Item($i,3) = "=(A$($i) - B$($i))"
| ~~
| You cannot call a method on a null-valued expression.
如何修复这里的错误?