Home » excel » excel vba – Capture Output of WScript Shell Object

excel vba – Capture Output of WScript Shell Object

Posted by: admin May 14, 2020 Leave a comment


This code upload a file to a FTP Server using Putty

Dim wsh As Object
Dim waitOnReturn As Boolean
Dim windowStyle As Integer
Dim cstrSftp As String
Dim strCommand As String
Dim pUser As String
Dim pPass As String
Dim pHost As String
Dim pFile As String
Dim pRemotePath As String
Dim site As String
Dim resp As String

Set wsh = VBA.CreateObject("WScript.Shell")

'Wait the execution to finish
waitOnReturn = True

'Show the window
windowStyle = 1

cstrSftp = """" & Application.ActiveWorkbook.Path & "\pscp.exe" & """"
site = "http://mysite/"
pUser = "user"
pPass = "password  "
pHost = "ftp.mysite"
pRemotePath = "/home/"
pFile = """" & Application.ActiveWorkbook.Path & "file.png" & """"

'Command string
strCommand = "cmd /c echo n | " & cstrSftp & " -sftp -l " & pUser & " -pw " & pPass & " " & pFile & " " & pHost & ":" & pRemotePath

'Run the command
wsh.Run strCommand, windowStyle, waitOnReturn

Since the storage server is not reliable I need to capture the output to know if the upload worked. And, if it doesn’t I need to know what was the message.

I thought of using the command ” > C:\output.txt” to capture the output. Like this

strCommand = strCommand & " > " & """" "C:\output.txt" & """"

When the upload works my output file works too. But, when the upload doesn’t work, nothing is written in the output file.

For example, when I get the message Fatal: Server unexpectedly closed network connection nothing is written in the output file. But I need to know what is the exactly messaged given.

How to&Answers:

Example for using exec to retrieve output, maybe this is useful in your case

Sub TestExec()

Dim wsh As New WshShell
Dim s As String

    s = wsh.Exec("cmd /c Dir C:\ ").StdOut.ReadAll
    Debug.Print s

End Sub