Execute any file using VBA (Visual Basic for Applications) code example

Execute any file using VBA (Visual Basic for Applications) code example

VBA offers various methods by which you can execute desired file. In this article we will discuss some of them with code example. Below code example will execute “test.py” file which is a python file.

File System Object:

Public Sub OpenFile()
	Dim fso As Object
	Dim oFile As String
	Set fso = CreateObject("shell.application")
	oFile = "C:\Users\Download\test.py"
	fso.Open oFile
End Sub

Shell

Sub OpenFile()
    Dim RetVal
    Dim oFilename As String
    oFilename = "C:\Users\\Downloads\Testing.txt"
    RetVal = Shell("C:\Program Files (x86)\Notepad++\notepad++.exe " & strfilename, vbNormalFocus)
End Sub

Above code will launch Notepad++ and open Testing.txt file

BATCH File this is off topic approach but still can help you:

Create a batch file as shown below where you need to specify two paths:

  1. Python exe path where python exe is located
  2. Script full path with file extension in which script is written as shown below
  3. Save the file with .bat extension I have used “test.bat
echo "Python is ready to launch myscript.py"
"C:\python27\python.exe" "D:\Mycode\hw01\myscript.py"
pause

This batch file can be clubbed to Windows scheduler or Shell command to achieve final goal.

Leave a Reply

Your email address will not be published. Required fields are marked *