Запуск макросов Excel (.xlsm) из скрипта Windows PowerShell
Привет, команда. Я планирую запустить ниже макрос Excel из сценария оболочки Windows Power. Мой макрос
Public Sub LogInformation()
Dim strFile_Path As String
strFile_Path = Application.ThisWorkbook.FullName & ".txt"
Open strFile_Path For Append As #1
Write #1, "message As String" & " : Logged at " & Now
Close #1
End Sub
Моя сила оболочки
#Call the application
$excel = new-object -comobject excel.application
#Now we select the file and path
$excelFile = Get-ChildItem -Path "..\McroWPSS.xlsm"
#The next variable speeds the script up by not calling the comobject as often
$app = $excel.Application
#Now we open the Excel file and activate the macro enabled content
$workbook = $app.workbooks.open($excelfile)
#The next command makes Excel visible
$app.Visible = $false
$workbook.Activate()
#Now we run all the Macros that need to be run.
$app.Run("LogInformation")
#Now we save the workbook in the standard daily format and the close Excel
$workbook.save()
$workbook.close()
$excel.quit()
Когда я запускаю свой скрипт powershell, я получаю ошибку ниже
Исключение, вызывающее "Выполнить" с аргументом (ами) "1": "Невозможно запустить макрос" Workbook_Open ". Макрос может быть недоступен в этой книге или все макросы могут быть отключены". В D:\Powershell\practice\MacroRun.ps1:16 char:2 + $app.Run("Workbook_Open") + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo: NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId: COMException
Исключение, вызывающее "Сохранить" с аргументом (ами) "0": "McroWPSS.xlsm только для чтения. Чтобы сохранить копию, нажмите" ОК ", а затем присвойте книге новое имя в диалоговом окне" Сохранить как "". В D:\Powershell\practice\MacroRun.ps1:19 char:2 + $workbook.save() + ~~~~~~~~~~~~~~~~ + CategoryInfo: NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId: ComMethodTargetInvocation
1 ответ
Вы можете управлять включенным / отключенным макросом через реестр. Вот как я заставил мою бежать.
включить
New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$($excel.Version)\excel\Security" -Name AccessVBOM -PropertyType DWORD -Value 1 -Force | Out-Null
New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$($excel.Version)\excel\Security" -Name VBAWarnings -PropertyType DWORD -Value 1 -Force | Out-Null
Отключить (после запуска макроса)
New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$($excel.Version)\excel\Security" -Name AccessVBOM -PropertyType DWORD -Value 0 -Force | Out-Null
New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$($excel.Version)\excel\Security" -Name VBAWarnings -PropertyType DWORD -Value 0 -Force | Out-Null