Sunday, September 05, 2010
Latest Content

VBA Check if Executable is Found by Cmd Shell

I have found that quite often I write a piece of VBA code and will end up calling third-party software from within VBA.  Naturally this poses a problem if the VBA code is taken to a different machine and the software being called is not installed or can't be found by Windows.  As kind of a sanity check I show below a small VBA function that tries to look for the tools "ls", "grep", and "awk" on a Windows machine (obviously these are Windows-ported GNU tools!), determines if they are callable from the command-line, and will exit the VBA code execution if any executable cannot be called.

The function checkExeTools takes a string with the executables to be found seperated by semi-colons, omitting the .exe extension.  The code is fairly explanatory and can be easily modified to suit individual needs.

    ' Check to see if required windows-ported linux tools are installed on system
    ' and are directly callable from cmd.exe (as part of the windows environment)
    checkExeTools ("ls;grep;awk")


Private Sub checkExeTools(toolsSemicolonDelimited As String)
    
    ' Enable Miscrosoft Scripting Runtime via Tools -> References
    ' to use FileSystemObject
    Dim FS As New FileSystemObject
    
    Dim execCheck As String
    execCheck = toolsSemicolonDelimited
    
    Dim execFiles() As String
    execFiles = Split(execCheck, ";")
    
    Dim enviroPath As String
    enviroPath = Environ("Path")
    
    Dim execPaths() As String
    execPaths = Split(enviroPath, ";")
       
    Dim i As Integer
    Dim j As Integer
    Dim e As Boolean
    
    ' Must ensure all PATH enviro paths end in trailing "\"
    ' (Windows allows users to enter it with or without one)
    For i = 0 To UBound(execPaths)
        If Right(execPaths(i), 1) <> "\" Then
            execPaths(i) = execPaths(i) + "\"
        End If
    Next
    
    For j = 0 To UBound(execFiles)
        e = False
        For i = 0 To UBound(execPaths)
            If FS.FileExists(execPaths(i) + execFiles(j) + ".exe") Then
                e = True
            End If
        Next i
        If e = False Then
            MsgBox execFiles(j) + ".exe" + " is not installed.", vbExclamation, "Required Executable Missing"
            End
        End If
    Next j

    Set FS = Nothing

End Sub

Great Items