我有一个Excel文件,可以使用VBA打开其他Excel文件。这些其他excel文件都在打开状态下运行代码-当前,当主文件打开文件时,它将等待打开的代码在刚打开的文件中运行,然后打开下一个文件。我希望它只是打开文件,然后继续打开下一个文件,而不必等待打开的代码完成-(我计划使用进程ID限制一次打开的文件数量)-有什么提示?
答案 0 :(得分:0)
首先,禁用宏的运行,根据需要打开工作簿,然后重新启用宏的运行。 (如此处建议的: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
启用/禁用验证单元的一种变体是使用中央属性
例如Application.Username
**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。 ;-)