0

When running a Powershell script using a task scheduler (VisualCron), I am getting the error "Unable to get the Open property of the Workbooks class at System.Management.Automation.ComInterop.ComRuntimeHelpers.CheckThrowException(Int32 hresult, ExcepInfo& excepInfo, ComMethodDesc method, Object[] args, UInt32 argErr). Below is the script I am running in Powershell.

# Define Excel
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false

# Get the path to source Excel workbook
$sourceWorkbookPath = "\\{USERVAR(FPS-Prod)}\Operations\Performance\Recurring Tasks\Monthly\Factset Batcher\ICS Monthly Output\NAT0S014_CLPSE.xlsx"

# Get the path to target Excel workbook
$targetWorkbookPath = "\\{USERVAR(FPS-Prod)}\Operations\Performance\Recurring Tasks\Monthly\Factset Batcher\ICS Monthly Output\NAT0S014_EXP.xlsx"

# Open the source/target Excel workbooks
$source = $excel.Workbooks.Open($sourceWorkbookPath, $null, $true)  # open source, readonly
$target = $excel.Workbooks.Open($targetWorkbookPath)                # open target

# Define n-th position in target to insert sheet
$nth_target = $target.sheets.item(1) # n-th sheet in target workbook
$nth1_target = $target.sheets.item(1) # n-th sheet in target workbook
$nth2_target = $target.sheets.item(1) # n-th sheet in target workbook
$nth3_target = $target.sheets.item(1) # n-th sheet in target workbook
$nth4_target = $target.sheets.item(1) # n-th sheet in target workbook
$nth5_target = $target.sheets.item(1) # n-th sheet in target workbook

# Define source sheet and copy to target workbook
$sheetToCopy = $source.sheets.item('ATTRIBUTION_1M')
$sheetToCopy.copy($nth_target)
$sheetToCopy = $source.sheets.item('ATTRIBUTION_Q_QTD')
$sheetToCopy.copy($nth1_target)
$sheetToCopy = $source.sheets.item('SECTOR_CONTRI_1M')
$sheetToCopy.copy($nth2_target)
$sheetToCopy = $source.sheets.item('SECTOR_CONTRI_1M_1')
$sheetToCopy.copy($nth3_target)
$sheetToCopy = $source.sheets.item('SECTOR_WEIGHT_MthEnd')
$sheetToCopy.copy($nth4_target)
$sheetToCopy = $source.sheets.item('SECTOR_WEIGHT_MthEnd_1')
$sheetToCopy.copy($nth5_target)

$target.Worksheets.Item(1). Activate()

# Close the source/target Excel workbooks
$source.Close($false)   # close source workbook w/o saving
$target.Close($true)    # close and save target workbook
$excel.Quit()
spps -n Excel

This script is for merging all worksheets from two Excel files (source and target) into one Excel file (target). Any ideas on what is causing the error?

  • What user account is the scheduled task running under, and has the user account ever been used to log on to the machine and launch Excel manually (for first-time user configuration)? – Mathias R. Jessen Jun 29 '23 at 14:46

0 Answers0