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\"
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启动的相对路径
for /f …… 这⼀句主要是遍历查整个启动程序的路径
start  "" 可以省略
exit 是为了退出cmd命令窗⼝
cd /d %~dp0
set
for /f "tokens=*" %%i in ('dir /a/b/s/on "%ProgramFiles%\*%exeName%"') do (set exePath="%%i")
set fileName="bat.xlsm"
set cmdMsg=/batOpen
%exePath% %fileName%  %cmdMsg%
exit
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)
vba 字符串转数组' 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

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。