详细的QueryTables错误处理

时间:2014-03-10 16:58:39

标签: sql excel vba error-handling

下午好,

我正在寻找一种处理QueryTable错误的方法。我已经查看了google和stackoverflow上的其他问题,但是他们似乎没有回答我想问的具体问题。

基本上,有没有办法确定处理QueryTables错误时的具体错误是什么?

代码:

On Error Goto queryError

With Activesheet.QueryTables...

....
End With


queryError:
    Msgbox("There was an error with the QueryTables. The reason for the error was: " & myError)

有没有办法设置myError以提供特定于问题的更多详细信息,即使这意味着选择某种状态代码?例如

QueryTables.StatusCode...

还是什么?

提前致谢。

1 个答案:

答案 0 :(得分:0)

如何处理错误
Excel VBA不支持Try Catch Finally。相反,它使用On Error GoTo

要完全控制Excel中的错误处理,您必须使用标签(始终以冒号结尾)。

在此示例中,两个标签是:

  • TRYAGAIN:
  • queryError:


假设正在创建的查询表来自一个类似于:

的文本文件

Text File

首次运行例程时,系统会提示用户输入三个输入:

  • 文件路径
  • 新表名称
  • 要粘贴到
  • 的单元格(即范围)

Input Box


如果这些输入中的任何一个发生错误,代码将立即转到标签 queryError:

因此,假设用户没有输入有效的文件路径,它看起来像这样:

Error Message

如果用户点击“是”(再次尝试),则Resume tryAgain会将代码恢复到该标签并完成整个过程。


最后注意Select Case。这是您可以控制如何处理特定错误的方法。


以下是要粘贴到模块中的代码:

Option Explicit

Sub CreateQueryTable()

    'Assign values to these variables by prompting user with Input Boxes
    Dim filepath As String
    Dim qryTableName As String
    Dim startCellForTable As Range

    'These variables are used in the error handling prompts
    Dim Msg As String
    Dim Ans As Integer

    'If an error occurs, code will go to the label `queryError:`
    On Error GoTo queryError


tryAgain:

    'Prompt user for the filename of the .txt file to use as QueryTable Source
    filepath = InputBox("Please enter filepath of text file to use as the source")

    'Prompt user to name the new Query Table
    qryTableName = InputBox("Please enter name of Query Table")

    'Prompt user for the cell to put table at
    Set startCellForTable = Application.InputBox(Prompt:="Please select a cell where you would like to paste the table to", Type:=8)


    'If user hits OK, check to see that they at least put something as a value
    If filepath <> "" And qryTableName <> "" And startCellForTable <> "" Then

        'format filepath variable so can pass it as argument to QueryTables.Add
        'Trim any leading or trailing spaces from qryTableName
        filepath = "TEXT;" & filepath
        qryTableName = Trim(qryTableName)

    End If

    'Create QueryTable at Range("A1")
    With ActiveSheet.QueryTables.Add(Connection:=filepath, Destination:=Range(startCellForTable.Address))
        .Name = qryTableName
        .Refresh BackgroundQuery:=False
    End With

    'If there are no errors, exit the procedure (so the `queryError:` code won't execute)
    Exit Sub


queryError:

    Msg = ""

    'Say that an error occured
    Msg = Msg & "An error occurred with the Query Table. " & vbNewLine & vbNewLine

    'Use Excel's built-in Error object (named `Err`) to show error number and description of error
    Msg = Msg & Err.Number & ": " & Error(Err.Number) & vbNewLine & vbNewLine

    Select Case Err.Number

        'Type mismatch
        Case 13


        'Object required
        Case 424

            Msg = Msg & vbNewLine & "Please check that a valid range was selected" & vbNewLine

        'Application defined or Object defined error
        Case 1004

            Msg = Msg & vbNewLine & "Please check that this filepath is correct: " & vbNewLine & vbNewLine & filepath & vbNewLine

        Case Else


    End Select


    'Prompt user to Try Again
    Msg = Msg & vbNewLine & vbNewLine & "Try again?"

    Ans = MsgBox(Msg, vbYesNo + vbCritical)

    'If user says Yes, clear the error, and resume execution of code at label `TryAgain:`
    If Ans = vbYes Then Resume tryAgain


End Sub