Sunday, August 23, 2015

Can I execute batch file by excel VBA ?

Creating and executing batch file is very useful way for project automation. It is very comprehensive to create complex automation. you can use batch file with excel VBA combination for several operations.


Given below are few such examples:


  • File Download from Servers,
  • Schedule Macro execution automatically,
  • Run application at particular time period and so on.

Here is the code which will do same kind of operation,

Public Sub Create_Run_Batch_File()
' Author: Dreams24
' Written for VBA Tricks and tips blog
' https://vbatricksntips.com

    Dim fNum As Integer
    Dim rVal As Variant
    Dim appPath, appfile As String
     
        file_Name = "C:\Users\Dreams\Desktop\Test.bat"
        
        'Variable to store Application path which is to be run
        appPath = "C:\Program Files (x86)\Google\Chrome\Application"
        
        'Variable to Store Application .exe file name
        appfile = "chrome.exe"
         
        fNum = FreeFile
         
         'Create batch file
        Open file_Name For Output As #fNum
        
        Print #fNum, "@echo off"
      
       'Here chr(34) used for double quotes character as output of the string
      
        Print #fNum, "cd " & Chr(34) & appPath & Chr(34) 
        Print #fNum, "start " & appfile
        Print #fNum, "exit"
        Close #fNum
         
         'Run batch file
        rVal = Shell(file_Name, vbNormalFocus)
         
         ' NOTE THE BATCH FILE WILL RUN, BUT THE CODE WILL CONTINUE TO RUN.
        If rVal = 0 Then
            MsgBox "An Error Occured"
            Close #fNum
            End
        End If
     
End Sub

Watch this video for step by step details:




No comments: