简体   繁体   中英

Excel VBA Workbook_Open does not work when Excel is already open

I was trying to automate VBA run with its file opening from command line as below:

cmd.exe /C set MacroName=MyMacro \& EXCEL.EXE C:\\_documents\\Book2.xlsm

The VBA scripts and files are as follows:

Book2.xlsm/Module1

Sub MyMacro()
    MsgBox "MyMacro is running..."
End Sub

Book2.xlsm/ThisWorkbook

Private Sub Workbook_Open()
    Dim strMacroName As String
    strMacroName = CreateObject("WScript.Shell").Environment("process").Item("MacroName")
    If strMacroName <> "" Then Run strMacroName
End Sub

Now, the above cmd command does work, expectedly notifies me with the MsgBox, when Excel is not open. But it does not work when Excel is already being open with other project/file(s).

How can I make this work?

The problem was that when you launch an Excel file in the already open Excel instance passing environment variables through cmd.exe or command line does not work correctly for some reason, rather than as a VBA-side problem.

I'm still not sure this is a bug or I'm doing wrong something. I appreciate that if someone would help to solve my wondering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM