在启动时从VBA打开宏安全性

时间:2017-06-22 13:31:06

标签: excel vba excel-vba

我目前有一个代码,在启动时检查选项" Trust访问VBA项目对象模型"是否启用。

如果未启用,我需要程序打开宏安全设置,以方便用户访问。

在大多数情况下,我已经制作了一些代码,但是我遇到了一个我不知道如何解决的问题。

代码如下:

Private Sub Workbook_Open
If Not VBATrusted() Then
    MsgBox "Trust access to the VBA project object model is not enabled" & vbNewLine & vbNewLine & _
    "Please allow access by ticking the checkbox in the window that appears after clicking Ok"
    Application.CommandBars.ExecuteMso ("MacroSecurity")
End If
End Sub

Function VBATrusted() As Boolean
    On Error Resume Next
    VBATrusted = (Application.VBE.VBProjects.Count) > 0
End Function

此代码完成其工作,除非宏设置为默认值"禁用所有带通知"的宏,在这种情况下我激活宏然后得到运行时错误" -2147467259( 80004005)方法' ExecuteMso'对象' _CommandBars'失败"

此错误仅在第一次启动时发生,因为我不必在连续启动时激活宏,除非我移动文件位置。

我已经尝试暂停宏两秒钟,但这对我没有任何作用,也没有一个错误处理程序尝试获取错误然后再次尝试执行Application.CommandBars.ExecuteMso ("MacroSecurity")行。最终出现了同样的错误。

调试器告诉我错误位于Application.CommandBars.ExecuteMso ("MacroSecurity")行,但对于该错误消息可能并不奇怪。

2 个答案:

答案 0 :(得分:2)

在这里开箱思考......
如果您在工作表上放置一条大消息,告诉用户激活宏,然后使用自动启动宏删除或隐藏该消息,该怎么办?这会把信息带给那些需要它的人,而不是其他人。

答案 1 :(得分:1)

@CLR在上面的评论中提出的

简单解决方案,但在我最初测试它时没有用(用户错误!)。所有代码都在ThisWorkbook模块中:

Option Explicit

Private Sub Workbook_Open()
If Not VBATrusted() Then
    MsgBox "Trust access to the VBA project object model is not enabled. " & vbNewLine & _
    "Please allow access by ticking the checkbox in the window that appears"
    Application.OnTime Now + TimeValue("00:00:01"), "ThisWorkbook.SetSecurity"
End If
End Sub

Function VBATrusted() As Boolean
    On Error Resume Next
    VBATrusted = (Application.VBE.VBProjects.Count) > 0
End Function

Sub SetSecurity(Optional foo)
    Application.CommandBars.ExecuteMso "MacroSecurity"
End Sub

稍微复杂一点:在工作表中添加MSForms.CommandButton,用户点击后会打开安全设置窗格。让MsgBox提示用户单击按钮,然后更改安全设置。

Module1中,按钮的点击事件处理程序:

Option Explicit
Sub Button1_Click()
    Call ThisWorkbook.SetSecurity
End Sub

ThisWorkbook模块中:

Option Explicit

Private Sub Workbook_Open()
If Not VBATrusted() Then
    MsgBox "Trust access to the VBA project object model is not enabled. " & vbNewLine & _
    "Please allow access by:" & vbNewLine & vbNewLine & _
    "1. Clicking the button on this sheet" & vbNewLine & _
    "2. Ticking the checkbox in the window that appears"
End If
End Sub

Function VBATrusted() As Boolean
    On Error Resume Next
    VBATrusted = (Application.VBE.VBProjects.Count) > 0
End Function

Sub SetSecurity(Optional foo)
    Application.CommandBars.ExecuteMso "MacroSecurity"
End Sub