面臨的需求:VBA既可以通過人手動觸發(fā)運行,生成相應的文件;也需要通過命令控制,自動執(zhí)行VBA生成文件,供其他工具使用。 解決方法:1. 手動執(zhí)行VBA只需要在excel中增加綁定宏的按鈕即可 2. 通過命令執(zhí)行是為了供其他系統(tǒng)或者工具使用,解決思路為,其他工具調bat文件,bat文件通過打開excel執(zhí)行vba 步驟如下: (1)在VBA中增加workbook的open事件,此事件會在文件打開時觸發(fā) (2)寫一個bat文件,用于打開excel,同時設置標識,用于標識是bat打開的: (3)VBA檢查是否為cmd命令打開excel,如果是進行后續(xù)處理,如果否則不處理,代碼如下: ' Declare Function GetCommandLine Lib "kernel32" Alias "GetCommandLineW" () As Long ' Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (MyDest As Any, MySource As Any, ByVal MySize As Long) ' Declare Function lstrlenW Lib "kernel32" (ByVal lpString As Long) As Long Private Declare PtrSafe Function GetCommandLine Lib "kernel32" Alias "GetCommandLineW" () As LongPtr Private Declare PtrSafe Function lstrlenW Lib "kernel32" (ByVal lpString As LongPtr) As LongPtr Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (MyDest As Any, MySource As Any, ByVal MySize As LongPtr) Private Sub Workbook_Open() CmdLine = CmdToSTr(CmdRaw) On Error Resume Next ' 這句是必須的,防止非bat打開,下面代碼會報錯 paraPos = WorksheetFunction.Search("/batOpen", CmdLine, 1) '檢查打開方式 ' 被調用的子函數(shù) , 用來將命令行參數(shù)轉換成字符串類型: Function CmdToSTr(Cmd As LongPtr) As String StrLen = lstrlenW(Cmd) * 2 ReDim Buffer(0 To CInt(StrLen - 1)) As Byte CopyMemory Buffer(0), ByVal Cmd, StrLen
此時便可以區(qū)分是bat打開還是人工打開。bat打開彈窗 人工打開彈窗。需求圓滿實現(xiàn)。
|