Hi Team我打算在Windows power shell脚本下运行excel宏。 我的宏
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
我的powershell
#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
答案 0 :(得分:0)
您可以通过注册表控制启用/解除宏的宏。这就是我如何让我跑。
启用
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