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
推荐阅读
vba要实现md5必须引用外部库,导致vba程序交付安装不是很方便。很多时候我们并不是想要取真正的md5,只是取一个加密字符串,比如保存密码的时候。本文中的代码直接利用windows系统内置命令certutil -hashfile实现了一种变相的md5函数。代码要读写本地文件两次,因此效率不高,不过在登陆验证一下密码等场景并没有影响。
VBA发送GET、POST请求的方法
评论