我的 VBA 代码中有一个函数,它从我这样调用的 FTP 下载文件
success = fnDownloadFile(hostName, UserName, Password, _
remoteFileStr, _
desktopPath & "downloaded.csv")
有时由于连接问题等,此功能挂起并且没有响应。如果此函数需要超过 5 秒才能设置成功 = True 并取消整个子程序的执行,我想显示一条错误消息。
在 ftp 函数调用之前,我尝试过使用以下内容,但我无法让它工作:
Application.OnTime Now + TimeValue("00:00:05"), "checkIfSuccessIsFalseAndStop"
函数代码如下:
Function fnDownloadFile(ByVal strHostName As String, _
ByVal strUserName As String, _
ByVal strPassWord As String, _
ByVal strRemoteFileName As String, _
ByVal strLocalFileName As String) As Boolean
'// Set a reference to: Microsoft Internet Transfer Control
'// This is the Msinet.ocx
Debug.Print "Value for file passed as:" & strRemoteFileName
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
fnDownloadFile = True
Debug.Print "Download completed"
Errh:
'fnDownloadFile = "Error:-" & Err.Description
fnDownloadFile = False
Resume Xit
End Function
最佳答案
只需设置 .RequestTimeout
property :
With FTP
.URL = strHostName
.Protocol = 2
.UserName = strUserName
.Password = strPassWord
.RequestTimeout 5 '<------
.Execute , "Get " + strRemoteFileName + " " + strLocalFileName
关于vba - 当 VBA 函数的计算时间长于计算时间时如何引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39410427/