I have a PowerShell script to open several Excel spreadsheets and write to a cell in each spreadsheet. I'd like to put the code to open each spreadsheet, write to it, and save it in a function. Rather than creating a new instance of the Excel.Application
COM object for every spreadsheet, I'd like to pass an instance to the function, so that the instance can be reused.
Here's my function:
function InsertBlurb
{
param([Object[]]$xl, [string]$filename, [string]$blurb)
$WorkBook = $xl.Workbooks.Open($filename)
$WorkSheet = $WorkBook.Sheets.Item("Print Out")
$WorkSheet.Cells.Item(12, "A") = $blurb
$WorkBook.Save()
$WorkBook.Close()
}
# Call looks like this
InsertBlurb($objExcel, $dsBook, $blurb)
When I try to run the function, I get an error:
You cannot call a method on a null-valued expression.
At T:\rclocher3\Excel-to-PDF2.ps1:32 char:35
+ $WorkBook = $xl.Workbooks.Open <<<< ($filename)
+ CategoryInfo : InvalidOperation: (Open:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
How do I pass an instance of the COM object Excel.Application
to a PowerShell function?