简体   繁体   English

Excel VBA 工作簿_打开在 Excel 已经打开时不起作用

[英]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:我试图自动化 VBA 运行,其文件从命令行打开如下:

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

The VBA scripts and files are as follows: VBA 脚本和文件如下:

Book2.xlsm/Module1 Book2.xlsm/Module1

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

Book2.xlsm/ThisWorkbook 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.现在,上面的 cmd 命令确实有效,当 Excel 未打开时,预计会通过 MsgBox 通知我。 But it does not work when Excel is already being open with other project/file(s).但是当 Excel 已经与其他项目/文件一起打开时,它不起作用。

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.问题是,当您在已经打开的 Excel 实例中启动 Excel 文件时,通过 cmd.exe 传递环境变量或命令行由于某种原因无法正常工作,而不是 VBA 端的问题。

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.如果有人能帮助解决我的疑惑,我将不胜感激。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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