2016-03-07 402 views
1

嗨团队我打算从Windows Power Shell脚本下运行excel宏。 我的宏从Windows PowerShell脚本运行Excel宏(.xlsm)

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” 的说法(S) :“无法运行宏'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

错误的第一行说明了原因:要么你没有明确的PowerShell通过CMD启用宏或有ISN” t现在我想到的任何宏 – newguy

+0

在这个'$ workbook = $ app.workbooks.open($ excelfile)'之后,你在哪里启用了宏内容? [见此](http://stackoverflow.com/questions/26907650/enable-macros-via-powershell)获取更多信息。 – newguy

+0

您的错误信息与您的脚本不匹配 - 您尝试运行哪个宏,它是如何声明的以及它在哪个模块中? –

回答

0

可以控制宏启用/通过注册表disbaled。我就是这样运行的。

启用

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 
+0

感谢您的答案。但我仍然一样。 – user5384290

+0

您是否可以在注册表中手动打开该节点以检查设置的值? [本页](https://blogs.technet.microsoft.com/diana_tudor/2014/12/02/microsoft-project-how-to-control-macro-settings-using-registry-keys/)讨论宏安全设置。我假设错误消息的第一部分不正确,并且LogInformation宏是您打开的工作簿(而不是Personal.XLSB或其他工作簿)的一部分。编辑:此外,我相信你必须作为管理员运行Powershell来进行注册表更改。 – gms0ulman