bat打开excel并自动运行VBA程序

1、bat中打开excle文件

1)绝对路径、一行语句

"C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE" "D:\Users\bat.xlsm" \batOpen

2) 绝对路径、变量路径

set exePath="C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE" 
set fileName="D:\Users\bat.xlsm"
set cmdMsg=/batOpen

start  "" %exePath%  %fileName% %cmdMsg%

其他应用程序(比如qq影音)

set exePath="C:\Program Files (x86)\Tencent\QQPlayer\QQPlayer.exe"
set fileName="D:\视频教程\VBA数组教学.mp4"
start  "" %exePath%  %fileName% 

3)文件相对路径

cd /d %~dp0 这一句就把路径修改为bat文件所在路径了

cd /d %~dp0

set exePath="C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE" 
set fileName="bat.xlsm"
set cmdMsg=/batOpen

start  "" %exePath%  %fileName% %cmdMsg%

4)excel启动的相对路径

2、把excel打开整个行为指定一个vba一个sub

' 32 位系统为
' Private Declare Function GetCommandLine Lib "kernel32" Alias "GetCommandLineW" () As Long
' Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (MyDest As Any, MySource As Any, ByVal MySize As Long)
' Private 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 CmdMsg  As String
    CmdMsg = "/batOpen" '命令行传递来的参数标识,与bat文件中的参数一致
    
    Dim CmdRaw  As LongPtr
    CmdRaw = GetCommandLine()
    Dim CmdLine As String
    CmdLine = CmdToSTr(CmdRaw)
    On Error Resume Next '这句是必须的,防止非bat打开,下面代码会报错
    Dim paraPos As Integer
    paraPos = WorksheetFunction.Search(CmdMsg, CmdLine, 1) '检查打开方式
    If paraPos > 0 Then
      MsgBox "bat自动打开,并运行VBA程序"
        
    Else
        MsgBox "手动打开,不运行VBA程序"
    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

 

上一篇:VBA中Dir函数的使用


下一篇:VBA掌握循环结构,包你效率提高500倍