我创建了Word模板加载项(.dtom)。它使用FTP从服务器下载文件。如果我的防火墙关闭,它工作正常。如果打开防火墙,则不允许下载。在某些情况下,使用防病毒设置防火墙。
这是我的代码,如果防火墙关闭,它可以正常工作。
'Add DLL runtime
Private Declare PtrSafe Function InternetGetConnectedState Lib "wininet.dll" _
(ByRef dwflags As Long, ByVal dwReserved As Long) As Long
Private Declare PtrSafe Function InternetOpenA Lib "wininet.dll" ( _
ByVal sAgent As String, _
ByVal lAccessType As Long, _
ByVal sProxyName As String, _
ByVal sProxyBypass As String, _
ByVal lFlags As Long) As Long
Private Declare PtrSafe Function InternetConnectA Lib "wininet.dll" ( _
ByVal hInternetSession As Long, _
ByVal sServerName As String, _
ByVal nServerPort As Long, _
ByVal sUsername As String, _
ByVal sPassword As String, _
ByVal lService As Long, _
ByVal lFlags As Long, _
ByVal lcontext As Long) As Long
Private Declare PtrSafe Function FtpGetFileA Lib "wininet.dll" ( _
ByVal hConnect As Long, _
ByVal lpszRemoteFile As String, _
ByVal lpszNewFile As String, _
ByVal fFailIfExists As Long, _
ByVal dwFlagsAndAttributes As Long, _
ByVal dwflags As Long, _
ByVal dwContext As Long) As Long
Private Declare PtrSafe Function InternetCloseHandle Lib "wininet" ( _
ByVal hInet As Long) As Long
Private Const INTERNET_FLAG_PASSIVE As Long = &H8000000
Public Sub downloadFile()
If (fileExists = True) Then
Kill folderLocation
End If
strRemoteFile = "/MyFile.xml"
strLocalFile = folderLocation
strHost = "XXX.XXX.XXX.XXX"
lngPort = 21
strUser = "myuser"
strPass = "mypassword"
'usage
'FtpDownload "/TEST/test.html", "c:\test.html", "ftp.server.com", 21, "user", "password"
Dim hOpen As Long
Dim hConn As Long
hOpen = InternetOpenA("FTPGET", 1, vbNullString, vbNullString, 1)
hConn = InternetConnectA(hOpen, strHost, lngPort, strUser, strPass, 1, INTERNET_FLAG_PASSIVE, 2)
If FtpGetFileA(hConn, strRemoteFile, strLocalFile, 1, 0, FTP_TRANSFER_TYPE_UNKNOWN Or INTERNET_FLAG_RELOAD, 0) Then
Debug.Print "done"
Else
Debug.Print "fail"
End If
InternetCloseHandle hConn
InternetCloseHandle hOpen
End Sub
如果打开防火墙,请建议我如何下载。还建议是否有任何其他方式可以解决防火墙问题。 (例如,在Mac VBA中,我们可以使用MacScript中的Curl命令下载文件,该命令可以从VBA执行)
答案 0 :(得分:0)
您必须使用被动FTP模式:
InternetConnectA(hOpen, strHost, lngPort, strUser, strPass, 1, INTERNET_FLAG_PASSIVE, 2)
当涉及防火墙或NAT时,InternetConnect
默认为活动模式,该模式几乎不可用。
请参阅Active and Passive FTP connection modes上的文章,了解您需要使用被动模式的原因。