VBA执行cmd命令并返回String结果

原创文章,欢迎转载:http://miao.blog/article/vba-execute-cmd-return-string-result

' Execute command and get string result
' Import Microsoft Scripting Runtime, Windows Script Host Object Model
Function ExecuteCmdForString(command As String) As String
    On Error GoTo ErrorHandler
    
    Dim tmp_file As String, oshell As WshShell
    tmp_file = Environ("tmp") & "\cmdResult.txt"
    Set oshell = New WshShell
    
    ' execute command
    oshell.Run "cmd /c " & command & " > " & tmp_file, vbHide, True
    
    ' get result
    Dim fso As FileSystemObject, txtStream As TextStream
    Set fso = New FileSystemObject
    Set txtStream = fso.OpenTextFile(tmp_file)
    
    If Not txtStream.AtEndOfStream Then
        ExecuteCmdForString = txtStream.ReadAll
    End If
    
    Exit Function
ErrorHandler:
    ExecuteCmdForString = ""
End Function
推荐阅读
评论