VBA: How to run another application from MS Access

后端 未结 4 1399
南方客
南方客 2021-01-11 13:46

I\'ve been trying to get this issue figured out, and it seems that I cannot find the solution to the problem anywhere. Here was the first part: VBA Shell command always retu

4条回答
  •  轮回少年
    2021-01-11 14:23

    I always use ShellExecute from the Windows API when I need to execute something in VBA.
    As far as I know, it works on machines without full privileges as well.

    Example:

    Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, _
        ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, _
        ByVal lpDirectory As String, ByVal lpnShowCmd As Long) As Long
    
    
    Public Sub ShellEx(ByVal Path As String, Optional ByVal Parameters As String, Optional ByVal HideWindow As Boolean)
    
        If Dir(Path) > "" Then
            ShellExecute 0, "open", Path, Parameters, "", IIf(HideWindow, 0, 1)
        End If
    
    End Sub
    

    Now you can call ShellEx to run pretty much anything:

    'run executable
    ShellEx "c:\mytool.exe"
    
    'open file with default app
    ShellEx "c:\someimage.jpg"
    
    'open explorer window
    ShellEx "c:\"
    

    Note that ShellEx has two optional parameters as well.
    I didn't show this in the above examples, but you can:

    • pass parameters to executables
    • hide the window of the called executable

提交回复
热议问题