首先禁用宏运行,根据需要打开工作簿,然后重新启用宏运行。 (这里建议:Getting a .xlsm file to not execute code when being opened with VBA)
Private Sub OpenWorkBookMacroDisabled(wbPath As String)
Application.AutomationSecurity = msoAutomationSecurityForceDisable
Workbooks.Open (wbPath)
Application.AutomationSecurity = msoAutomationSecurityByUI
'or
'Application.AutomationSecurity = msoAutomationSecurityLow
End Sub
但实际上这并不能解决您的问题。要运行宏,必须重新打开工作簿,然后再次自动启动各个宏。
解决方法 1
这里提到了一个可能的解决方案:https://www.ozgrid.com/forum/forum/help-forums/excel-general/47477-enabling-macros-without-re-opening-worksheet:
创建一个启用/禁用验证单元
如果出现问题,唯一的解决方法可能是在您的主页/首页上显示“已启用”的验证单元/“已禁用”。
然后在打开工作簿时始终启用宏,然后在工作簿打开时自动将其设置为禁用。
那么您将让所有宏查看此引用,如果禁用则不运行,您需要启用拨号以允许任何宏运行。
可能不是你想要的,而是一个想法。
解决方法 2
另一种解决方法可能是:
(1) 使用上述代码打开工作簿。
(2) 以编程方式将Sub Workbook_Open 更改为Sub Workbook_Open_OLD
(3) 保存工作簿
(4) 将AutomationSecurity更改为所需级别
(5) 重新打开您的工作簿
相当多的工作!
详情见:http://www.cpearson.com/excel/vbe.aspx
解决方法 3
启用/禁用验证单元的一个变体是使用中心属性
例如应用程序.用户名
**This Macro calls the 'other excel files':**
Sub Main0()
'TEST 1:
'Open workbook and DON'T run macros
'Call "YourCode" manually
Application.UserName = "NoMacroRun"
Debug.Print "Test 1:"
Debug.Print Application.UserName
Workbooks.Open ThisWorkbook.Path & "\macro_010.xlsb"
Debug.Print "Open finished"
Debug.Print "Call YourCode"
Run "macro_010.xlsb!YourCode"
Workbooks("macro_010.xlsb").Close SaveChanges:=False
Debug.Print "Test 1: FINISHED successfully"
Debug.Print ""
'TEST 2:
'Open workbook and run macros
Application.UserName = "SomeThingElse"
Debug.Print "Test 2:"
Debug.Print Application.UserName
Workbooks.Open ThisWorkbook.Path & "\macro_010.xlsb"
Debug.Print "Test 2: FINISHED successfully"
Debug.Print ""
Workbooks("macro_010.xlsb").Close SaveChanges:=False
Debug.Print ""
End Sub
其他文件如下所示:
在“其他文件”中,您将“YourCode”与“Workbook_Open”分开并使其可从外部调用:
'doubleclick "ThisWorkbook" in the IDE and insert this code there
Public Sub Workbook_Open()
If Application.UserName <> "NoMacroRun" Then
Debug.Print "---> " & ThisWorkbook.Name & ": Workbook_Open is part of ThisWorkbook in the IDE"
'your code
Call YourCode
End If
End Sub
您插入到模块中的这段代码:
'doubleclick "module" in the IDE and insert this code there
'OR click in the menu --> Insert --> Module
Sub YourCode()
Debug.Print "---> " & ThisWorkbook.Name & ": ""Sub YourCode"" is part of a module in the IDE!"
End Sub
最后,立即窗口证明它按预期工作:
Test 1:
NoMacroRun
Open finished
Call YourCode
---> macro_010.xlsb: "Sub YourCode" is part of a module in the IDE!
Test 1: finished successfully
Test 2:
SomeThingElse
---> macro_010.xlsb: Workbook_Open is part of ThisWorkbook in the IDE
---> macro_010.xlsb: "Sub YourCode" is part of a module in the IDE!
Test 2: finished successfully
Q.E.D. ;-)