vba - 当 VBA 函数的计算时间长于计算时间时如何引发错误

标签 vba excel

我的 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/

相关文章:

正则表达式在字母数字字符串中查找未括在括号中的数字字符串

vba - 处理 docmd.applyfilter 的无结果

sql - Excel VBA,如何进行多个数据库条目

vba - 查找并替换目录中所有 Excel 文件工作簿中的字符串

excel - 检查Word文档是否已经打开+错误处理

PhpSpreadSheet:如何将工作簿工作表保存在单个 CSV 文件中

excel - 如何将最后一列输入到数组中以将文本写入列?

vb.net - Excel VBA 和 VB.NET 一样吗

vba - 在文本字符串中插入空格 准备文件目录

excel - 将数据模型数据用于单元格公式