我需要访问Excel VBA宏中的命令行参数,并发现许多变体,但只有一个与Excel-2010一起使用,似乎API随着时间的推移而发生了变化。我尝试了这段代码,我找到了“out there”:
Dim pCmdLine As Long ' Pointer to the Comand-line string
Dim strCmdLine As String ' Command line string
Dim CmdLine As String ' Command line string
' Get the pointer to the command line string
pCmdLine = GetCommandLineA
' Fill the string with zeros
' (300 characters for command line seems to be enough)
strCmdLine = String$(300, vbNullChar)
' Copy from the pointer to VBA-style string
lstrcpynA strCmdLine, pCmdLine, Len(strCmdLine)
' At this point we got the string,
' now skip the rest of it filled with 0 characters.
CmdLine = Left(strCmdLine, InStr(1, strCmdLine, vbNullChar) - 1)
MsgBox "Length of the command line = " & Len(CmdLine) '' Debug
MsgBox "Command Line:: " & CmdLine '' Debug
我将其放入电子表格的Auto_open宏中。如果我试试这个电话:
start excel TestMacro.xlsm /e/abcd/xyz
似乎一般都有效,宏观报道:
Command line = " C:/.../excel.exe TestMacro.xlsm"
所以我得到了调用部分,但参数丢失了。
部分解决方案: 我发现如果我将调用更改为:
start excel /e/abcd/xyz TestMacro.xlsm
它的工作原理,除了必须更改解析代码以忽略不在最后的文件名,并且此表单似乎不允许任何参数中的任何空格,即使引用。系统似乎将它们解释为目标excel文件的文件名并给出错误。例如:
start excel /e/abc/"my sheet"/ TestMacro.xlsm
给出错误:
file 'sheet"/.xlsx' not found
虽然在虚假的启动错误之后,预期的工作表会打开,并且可以使用整个行。