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啟動的相對路徑

for /f …… 這一句主要是遍歷查找EXEL.exe整個啟動程序的路徑
start  "" 可以省略
exit 是為了退出cmd命令窗口
cd /d %~dp0


set exeName=EXCEL.exe 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)
' 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM