Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

vba - Passing arguments from command line in excel 2010

I have found several snippet of code out there that allows me to pass arguments into excel from command line.

The code below is placed in a new module called parameters:

Declare Function GetCommandLine Lib "kernel32" Alias "GetCommandLineW" () As Long
Declare Function lstrlenW Lib "kernel32" (ByVal lpString As Long) As Long
Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (MyDest As Any, MySource As Any, ByVal MySize As Long)

Public CmdLineToStr() As String
'
' Returns the command line in the call to Excel
'
Dim Buffer() As Byte
Dim StrLen As Long
Dim CmdPtr As Long

CmdPtr = GetCommandLineW()
If CmdPtr > 0 Then
  StrLen = lstrlenW(CmdPtr) * 2
  If StrLen > 0 Then
    ReDim Buffer(0 To (StrLen - 1)) As Byte
    CopyMemory Buffer(0), ByVal CmdPtr, StrLen
    CmdLineToStr = Buffer
  End If
End If

End Sub

and then in thisworkbook i call this code

Sub workBook_open()
    MsgBox Parameters.CmdLineToStr
End Sub

It fails with the GetCommandLine function, so is the error due to problems with linking the dll library or is this due to the fact that i have some macros stored in personal.xlsb?

I call the excel sheet from the command line with this line: C:UserskimDesktop>start excel Parameters.xlsm /e/nmbnmbmnb

and i get this error :

eroor

Outside procedure

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The corrected, tested procedure: (The version above had two mistakes.)

Option Explicit

Declare Function GetCommandLine Lib "kernel32" Alias "GetCommandLineW" () As Long
Declare Function lstrlenW Lib "kernel32" (ByVal lpString As Long) As Long
Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
    (MyDest As Any, MySource As Any, ByVal MySize As Long)

Public Function CmdLineToStr() As String
'Returns the command line used to open Excel
    Dim Buffer() As Byte, StrLen As Long, CmdPtr As Long
    CmdPtr = GetCommandLine()
    If CmdPtr > 0 Then
      StrLen = lstrlenW(CmdPtr) * 2
      If StrLen > 0 Then
        ReDim Buffer(0 To (StrLen - 1)) As Byte
        CopyMemory Buffer(0), ByVal CmdPtr, StrLen
        CmdLineToStr = Buffer
      End If
    End If
End Function

...place the code in a new, regular module, then call CmdLineToStr to get the command line that was used to open Excel, such as:

excel.exe /x "C:UserssomeoneDesktopmyTest.xlsm"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...