简体   繁体   English

Excel VBA:连接中的消息框错误

[英]Excel VBA: message box error in connection

There is a website, that can create thousands of .csv files that contain tables. 有一个网站,可以创建包含表的数千个.csv文件。 The CSV files are based on the information the user asks. CSV文件基于用户要求的信息。

I created an excel file with VBA script. 我用VBA脚本创建了一个excel文件。 The user enters the data to the excel file, then the VBA script generates the correct URL, and tries to get the required data from the .csv in that URL. 用户将数据输入excel文件,然后VBA脚本生成正确的URL,并尝试从该URL中的.csv获取所需的数据。

In my excel file, the user can ask for hundreds of .csv tables, and I want the user to be able to enter the hundreds of information kinds he wants, then run the VBA script and leave the computer to work on it. 在我的excel文件中,用户可以要求数百个.csv表,而我希望用户能够输入他想要的数百种信息类型,然后运行VBA脚本并让计算机进行处理。

I first do URL check, and if it is ok, I try to get the data in the .csv file in that URL. 我首先进行URL检查,如果可以,我尝试在该URL的.csv文件中获取数据。

most of the times, it works completely fine. 在大多数情况下,它完全可以正常工作。 Works fine for a case when HttpExists returns TRUE, and also works fine for a case that HttpExists returns FALSE (it just skips the current active cell and goes to the next one). 适用于HttpExists返回TRUE的情况,也适用于HttpExists返回FALSE的情况(它仅跳过当前活动单元并转到下一个单元)。

But there are a few times, that the URL check answers that the URL is fine (HttpExists returns TRUE), but when it tried to get the data, it opens a message box that says "sorry, we couldn't open 'url address' ". 但是有几次,URL检查会回答URL正常(HttpExists返回TRUE),但是当尝试获取数据时,它会打开一个消息框,显示“抱歉,我们无法打开'URL地址”。 (message box for Run Time Error 1004) and then the VBA scripts terminates. (运行时错误1004的消息框),然后VBA脚本终止。

I would like to know how can I fix it. 我想知道如何解决它。 How can I just skip the current URL in case of error, instead of showing a message box that terminates the script run? 如果出现错误,如何跳过当前URL,而不是显示一个终止脚本运行的消息框?

Sub my_method()

On Error GoTo handleCancel

Dim errorFlag As Boolean



 .......

Do Until ActiveCell.Value = ""
    errorFlag = True

    URLstring= ....

    ........

        If Not HttpExists(URLstring) Then
            symbolStatus = "Data unavailable"
            logAddress = updateLog("invalid URL " & ActiveCell.Value, logAddress, debugString)
            Application.DisplayAlerts = False
            Sheets(currentSymbol).Delete
            Application.DisplayAlerts = True
        Else
            With Sheets(currentSymbol).QueryTables.Add(Connection:= _
                "TEXT;" & URLstring _
                , Destination:=Sheets(currentSymbol).Range(dataAddress))
                .Name = ""
                .FieldNames = True
                .RowNumbers = False
                .FillAdjacentFormulas = False
                .PreserveFormatting = True
                .RefreshOnFileOpen = False
                .RefreshStyle = xlOverwriteCells
                .SavePassword = False
                .SaveData = True
                .AdjustColumnWidth = True
                .RefreshPeriod = 0
                .TextFilePromptOnRefresh = False
                .TextFilePlatform = 850
                .TextFileStartRow = 2
                .TextFileParseType = xlDelimited
                .TextFileTextQualifier = xlTextQualifierDoubleQuote
                .TextFileConsecutiveDelimiter = False
                .TextFileTabDelimiter = False
                .TextFileSemicolonDelimiter = False
                .TextFileCommaDelimiter = True
                .TextFileSpaceDelimiter = False
                .TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 2, 9)
                .TextFileTrailingMinusNumbers = True
                .Refresh BackgroundQuery:=False
            End With

  .......

    errorFlag = False
 handleCancel:
    ActiveCell.Offset(1, 0).Select

    If errorFlag = True Then
            symbolStatus = "Data unavailable"
            logAddress = updateLog("invalid URL " & ActiveCell.Value,      
                         logAddress, debugString)
            Application.DisplayAlerts = False
            Sheets(currentSymbol).Delete
            Application.DisplayAlerts = True
    End If

Loop
 End Sub




Function HttpExists(sURL As String) As Boolean
    Dim oXHTTP As Object
    Set oXHTTP = CreateObject("MSXML2.ServerXMLHTTP")

    If Not UCase(sURL) Like "HTTP:*" Then
        sURL = "http://" & sURL
    End If

    On Error GoTo haveError
    oXHTTP.Open "HEAD", sURL, False
    oXHTTP.send
    HttpExists = IIf(oXHTTP.status = 200, True, False)
    Exit Function

haveError:
    HttpExists = False
End Function

It sometimes goes out with a messagebox of Run Time Error 1004, and it happens in the line of: 有时会出现“运行时错误1004”消息框,并且发生在以下行中:

        With Sheets(currentSymbol).QueryTables.Add(Connection:= _
            "TEXT;" & URL _

I would like it just to skip the current cell in a case of error, and go on with the next cell, without any messagebox and without crashing. 我希望只是在出现错误的情况下跳过当前单元格,然后继续下一个单元格,而无需任何消息框且不会崩溃。

How can I fix it? 我该如何解决?

Thanks 谢谢

You need to add error handling to your code. 您需要在代码中添加错误处理。 Server timeout notices doesn't reflect an issue with your coding, but an issue with the server (which is out of your control, unless of course, you entered an incorrect URL). 服务器超时通知并不反映您的编码问题,而是服务器问题(除非您输入了错误的URL,否则这是您无法控制的)。

In your code, you need to place On Error GoTo ErrHandler , make sure you have the error number, and since you are wanting to just resume to the next cell you can do something like this: 在您的代码中,您需要将On Error GoTo ErrHandler ,确保您拥有错误号,并且由于您只想恢复到下一个单元格,因此可以执行以下操作:

Sub Test()
    On Error GoTo ErrHandler

    'Your code

    Exit Sub
ErrHandler:
    If Err.Number = 123456 Then
        'Get the code ready for the next cell, if necessary
        Resume Next
    Else
        'Other Errs
    End If
End Sub

See if this error handling structure works better. 查看此错误处理结构是否更好地工作。 I eliminated parts that are unnecessary and adjusted to what should work, but I am not sure what code is in the ..... sections. 我消除了不必要的部分,并调整了应该工作的部分,但是我不确定.....节中的代码是什么。 Anyway, this should at least give you a general understanding. 无论如何,这至少应该使您有一个大致的了解。 I commented a few things to explain more clearly in code. 我评论了几件事,以便在代码中更清楚地解释。

Option Explicit

Sub my_method()

    Do Until ActiveCell.Value = ""

        'URLstring= ....

        If Not HttpExists(URLstring) Then

            LogError 'create sub since you do same thing twice

        Else

            On Error GoTo handleBadURL 'now is only time you need to move to actual error handling

            With Sheets(currentSymbol).QueryTables.Add(Connection:= _
                "TEXT;" & URLstring _
                , Destination:=Sheets(currentSymbol).Range(dataAddress))
                .Name = ""
                .FieldNames = True
                .RowNumbers = False
                .FillAdjacentFormulas = False
                .PreserveFormatting = True
                .RefreshOnFileOpen = False
                .RefreshStyle = xlOverwriteCells
                .SavePassword = False
                .SaveData = True
                .AdjustColumnWidth = True
                .RefreshPeriod = 0
                .TextFilePromptOnRefresh = False
                .TextFilePlatform = 850
                .TextFileStartRow = 2
                .TextFileParseType = xlDelimited
                .TextFileTextQualifier = xlTextQualifierDoubleQuote
                .TextFileConsecutiveDelimiter = False
                .TextFileTabDelimiter = False
                .TextFileSemicolonDelimiter = False
                .TextFileCommaDelimiter = True
                .TextFileSpaceDelimiter = False
                .TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 2, 9)
                .TextFileTrailingMinusNumbers = True
                .Refresh BackgroundQuery:=False
            End With

            On Error Go To 0 'reset error handling (doesn't matter so much here, but good practice to always reset when not needed

        End If

        ActiveCell.Offset(1, 0).Select

    Loop

Exit Sub 'leave sub when all is done (so it doesn't move to error handling code below

handleBadURL:

        LogError 'created sub since you do same thing twice
        Resume Next 'this statement will allow code to continue from point of error onward (the loop will keep going

 End Sub


Sub LogError()

    symbolStatus = "Data unavailable"
    logAddress = updateLog("invalid URL " & ActiveCell.Value, logAddress, debugString)
    Application.DisplayAlerts = False
    Sheets(currentSymbol).Delete
    Application.DisplayAlerts = True

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM