我是一个初学者,也是Excel VBA的新手,但我正在尝试通过连接到Excel并创建一个可能会有所帮助的宏来自动化FTP (WinSCP)中的一些文件共享。在FTP中,我转到会话>生成会话URL/代码>脚本(脚本文件),其中包含以下代码:
open ftp://myUsername:myPassword@theHostname/
# Your command 1
# Your command 2
exit我假设开通线路会把Excel和FTP连接起来。我引用了这个站点的代码,将其放入'# command‘区域:https://www.mrexcel.com/forum/excel-questions/261043-connecting-ftp-excel.html
open ftp://myUsername:myPassword@theHostname/
Option Explicit
Sub FtpTest()
MsgBox fnDownloadFile("ftp://yoursite", "username", "password", _
"The name of your file", _
"C:\The name of your file to save as")
End Sub
Function fnDownloadFile(ByVal strHostName As String, _
ByVal strUserName As String, _
ByVal strPassWord As String, _
ByVal strRemoteFileName As String, _
ByVal strLocalFileName As String) As String
'// Set a reference to: Microsoft Internet Transfer Control
'// This is the Msinet.ocx
Dim FTP As Inet 'As InetCtlsObjects.Inet
Set FTP = New Inet 'InetCtlsObjects.Inet
On Error GoTo Errh
With FTP
.URL = strHostName
.Protocol = 2
.UserName = strUserName
.Password = strPassWord
.Execute , "Get " + strRemoteFileName + " " + strLocalFileName
Do While .StillExecuting
DoEvents
Loop
fnDownloadFile = .ResponseInfo
End With
Xit:
Set FTP = Nothing
Exit Function
Errh:
fnDownloadFile = "Error:-" & Err.Description
Resume Xit
End Function
exit我照这个网站说的做了,去VBA编辑器>工具>参考,并勾选了Microsoft Internet Control。
1)我使用的代码正确吗?我把它放在正确的区域(在'# command‘区域)了吗?现在我将整个代码放在一个命令按钮中,但当我单击它时,它只会给我一个语法错误,突出显示第一行: Private Sub CommandButton1_Click()
2)我是将Msgbox留在第三行等待用户输入,还是填写我的用户名/密码/主机名?(我还不太擅长VBA中的函数)如果我在代码中填写了它,由于我不访问网站,我应该为"yoursite“值填什么?
很抱歉我很困惑:(任何帮助都会很好,提前谢谢你!)
发布于 2017-06-27 22:00:52
我认为你应该看看这里- Excel VBA reference for Inet objects这里展示了如何在vba中添加对INet对象的引用。此外,当您只想测试代码是否正常工作时,如果您使用"Function“,那么当您转到工作表单元格并开始键入=fnDown时,而不是将宏赋给按钮等等。你应该会看到你的宏--你可以把你的函数参数放在那里。但是,首先您必须注意对Inet的引用。
这个链接可能也会有帮助:VBA Excel and FTP with MSINET.OCX and Inet type
https://stackoverflow.com/questions/44781828
复制相似问题