启动时从VBA打开macros安全性

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

在没有启用的情况下,我需要程序打开macros安全设置,方便用户访问。

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

代码如下:

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 

这个代码完成它的工作,除非macros设置是默认的“禁用所有macros通知”,在这种情况下,我激活macros,然后得到一个运行时错误“-2147467259(80004005)方法'ExecuteMso'的对象'_CommandBars'失败”

这个错误只会在第一次启动时发生,因为我不必激活连续启动时的macros,除非我移动文件位置。

我已经尝试了暂停这个macros两秒钟,但是对我没有做任何事情,也没有试图抓住错误,然后尝试再次执行Application.CommandBars.ExecuteMso ("MacroSecurity")行的error handling程序。 它结束了同样的错误。

debugging器告诉我,这个错误是在Application.CommandBars.ExecuteMso ("MacroSecurity")行中,但是这对于那个错误信息来说可能没有多大意义。

简单的解决scheme,如@CLR在上面的注释中所提出的,但是当我最初testing它(用户错误!)时没有工作。 所有代码都放在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提示用户单击该button,然后更改安全设置。

Module1 ,button的单击事件处理程序:

 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 

在这里的框外思考…
如果在工作表上放一个大消息告诉用户激活macros,然后让自动启动macros删除或隐藏该消息,那该怎么办? 那会把信息传达给那些需要的人,而不是其他人。