投稿‎ > ‎

VBA Run DOS Command

posted Mar 16, 2016, 11:35 PM by Zhang Wenxu   [ updated Jul 12, 2016, 6:40 PM ]
Public Const TemporaryFolder = 2
Public function runCmd(strCmd as String, Optional waitOnReturn = True) as String
    Dim ret as String
    Dim tmpFile as String
    Dim fso as New FileSystemObject
    Dim wsh As New WshShell
    'Dim waitOnReturn as Boolean
    Dim windowStyle As Integer

    tmpFile = fso.GetSpecialFolder(TemporaryFolder) & "¥" & Replace(fso.GetTempName(), ".tmp", ".txt")
    strCmd = "cmd /c " & strCmd & " > " & tmpFile & " 2>&1"
    'waitOnReturn = True
    windowStyle = 0

    wsh.Run strCmd, windowStyle, waitOnReturn
    
    If waitOnReturn Then
        If Faso.FileExits(tmpFile) Then
            On Error Resume Next
            ret = fso.OpenTextFile(tmpFile, ForReading, False).ReadAll
        Else
            ret = "Error, no output all all."
        End If
    End If
    runCmd = ret
End Function

参照設定:
Windows Script Host Object Model
Microsoft Scripting Runtime

Comments