首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当VBA函数的计算时间超过长度时如何抛出错误

当VBA函数的计算时间超过长度时如何抛出错误
EN

Stack Overflow用户
提问于 2016-09-09 19:20:46
回答 2查看 98关注 0票数 1

我的VBA代码中有一个从FTP下载文件的函数,我这样调用它

代码语言:javascript
复制
success = fnDownloadFile(hostName, UserName, Password, _
        remoteFileStr, _
        desktopPath & "downloaded.csv")

有时由于连接问题等原因,此函数挂起且不响应。如果此函数花费超过5秒的时间没有设置success = True并取消整个sub的执行,我会显示一条错误消息。

我试着在ftp函数调用之前修改以下代码,但是我不能让它工作:

代码语言:javascript
复制
Application.OnTime Now + TimeValue("00:00:05"), "checkIfSuccessIsFalseAndStop"

函数代码如下:

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2016-09-09 20:27:24

只需设置.RequestTimeout property

代码语言:javascript
复制
With FTP
    .URL = strHostName
    .Protocol = 2
    .UserName = strUserName
    .Password = strPassWord
    .RequestTimeout 5       '<------
    .Execute , "Get " + strRemoteFileName + " " + strLocalFileName
票数 2
EN

Stack Overflow用户

发布于 2016-09-09 19:48:47

您应该在.StillExecuting循环中控制这一点

我想这应该行得通。这在很大程度上取决于您的inet类是什么:自定义引用还是MSINET.OCX引用。如果它是自定义的,那么您应该声明cancel方法。

代码语言:javascript
复制
Dim dtStart As Date
dtStart = Now
.Execute , "Get " + strRemoteFileName + " " + strLocalFileName
Do While .StillExecuting

    If DateDiff("s", Now, dtStart) > 5 Then
        ' Cancel after5 seconds
        .Cancel
        .Execute , "CLOSE" ' Close the connection
        MsgBox "Download cancelled after 5 seconds"
    End If

    DoEvents
Loop
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39410427

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档