我正在使用Excel将一些文件上传到具有WinSCP的服务器上。此示例有效:
Sub FTP_upload()
Dim logfile, ftp_login, file_to_upload, upload_to_folder As String
logfile = "D:\temp\ftp.log"
ftp_login = "ftp://ftp_mydomain:[email protected]/"
file_to_upload = "D:\tmep\myfile.txt"
upload_to_folder = "/myfolder/"
'upload the file
Call Shell("C:\Program Files (x86)\WinSCP\WinSCP.com /log=" & logfile & " /command " & """open """ & ftp_login & " " & """put " & file_to_upload & " " & upload_to_folder & """ " & """exit""")
End Sub
我现在希望Excel等待外壳关闭。
使用Wait for shell command to complete中的信息,将以下代码放在一起:
Sub FTP_upload_with_wait()
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errorCode As Integer
Dim logfile, ftp_login, file_to_upload, upload_to_folder As String
logfile = "D:\temp\ftp.log"
ftp_login = "ftp://ftp_mydomain:[email protected]/"
file_to_upload = "D:\tmep\myfile.txt"
upload_to_folder = "/myfolder/"
execute_string = "C:\Program Files (x86)\WinSCP\WinSCP.com /log=" & logfile & " /command " & """open """ & ftp_login & " " & """put " & file_to_upload & " " & upload_to_folder & """ " & """exit"""
errorCode = wsh.Run(execute_string, windowStyle, waitOnReturn)
End Sub
不幸的是,这不起作用。 Excel报告:
运行时错误'-2147024894(80070002)'自动化错误系统找不到指定的文件
当我以此方式替换字符串时,它起作用:
execute_string = "notepad.exe"
似乎wsh.Run
不喜欢引号。我该如何进行这项工作?
WinSCP的路径包含空格,因此您需要将其包装为双引号(需要将其双引号以使其在VBA字符串中转义):
execute_string = """C:\Program Files (x86)\WinSCP\WinSCP.com"" ..."
但是那只是您的命令中第一组引号是错误的。
正确的命令将是:
execute_string = """C:\Program Files (x86)\WinSCP\WinSCP.com"" " & _
"/log=" & logfile & " /command " & _
"""open " & ftp_login & """ " & _
"""put " & file_to_upload & " " & upload_to_folder & """ " & _
"""exit"""
假设logfile
,ftp_login
,file_to_upload
和upload_to_folder
都不包含空格,在这种情况下将需要更多的双引号。
阅读有关WinSCP command-line syntax的矿石
Call Shell
必须具有一些启发式,以在C:\Program Files (x86)\WinSCP\WinSCP.com
周围添加引号。尽管命令行的其余部分正常工作只是运气,但是引号在那也是错误的。因此,即使您的第一个代码也是错误的。它运行以下命令:
"C:\Program Files (x86)\WinSCP\WinSCP.com" /log=D:\temp\ftp.log /command "open "ftp://ftp_mydomain:[email protected]/ "put D:\tmep\myfile.txt /myfolder/" "exit"
((请注意open
周围的引号放错了位置]