面临的需求:
VBA既可以通过人手动触发运行,生成相应的文件;也需要通过命令控制,自动执行VBA生成文件,供其他工具使用。
解决方法:
1. 手动执行VBA只需要在excel中增加绑定宏的按钮即可
2. 通过命令执行是为了供其他系统或者工具使用,解决思路为,其他工具调bat文件,bat文件通过打开excel执行vba
步骤如下:
(1)在VBA中增加workbook的open事件,此事件会在文件打开时触发
(2)写一个bat文件,用于打开excel,同时设置标识,用于标识是bat打开的:
(3)VBA检查是否为cmd命令打开excel,如果是进行后续处理,如果否则不处理,代码如下:
' 32 位系统为
' 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
' 64 位系统为
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()
Dim CmdRaw As LongPtr
Dim CmdLine As String
Dim Msg As String
CmdRaw = GetCommandLine
CmdLine = CmdToSTr(CmdRaw)
Dim paraPos%
On Error Resume Next ' 这句是必须的,防止非bat打开,下面代码会报错
paraPos = WorksheetFunction.Search("/batOpen", CmdLine, 1) '检查打开方式
If paraPos > 0 Then
MsgBox "bat"
'===============
'===============
Else
MsgBox "man"
End If
End Sub
' 被调用的子函数 , 用来将命令行参数转换成字符串类型:
Function CmdToSTr(Cmd As LongPtr) As String
Dim Buffer() As Byte
Dim StrLen As LongPtr
If Cmd Then
StrLen = lstrlenW(Cmd) * 2
If StrLen Then
ReDim Buffer(0 To CInt(StrLen - 1)) As Byte
CopyMemory Buffer(0), ByVal Cmd, StrLen
CmdToSTr = Buffer
End If
End If
End Function
此时便可以区分是bat打开还是人工打开。bat打开弹窗
人工打开弹窗。需求圆满实现。
参考:https://blog.csdn.net/richardsa/article/details/6609606
参考:https://www.cnblogs.com/duanyuerui/p/6958631.html