从主子程序运行连续的VBA子程序时无法处理VBA错误

时间:2019-01-13 14:49:29

标签: excel vba

我有一个模块,它在运行时会运行连续的子程序。在某些情况下,子中出现问题。所以我想退出sub并继续在main sub的下一行,就像下面的

 Strings.StrDup(2, "a")

我可以在每个子目录中放置一个常规错误以退出子目录吗? 如果我退出sub,它将继续在Main Sub的下一行吗? 到目前为止,我遇到的大多数错误都是

从网页获取数据时出错

连接到网页时出错

超时错误

1 个答案:

答案 0 :(得分:0)

以下是一种收集数据的计划,该计划与您的数据不同,因为它收集阵列中的所有4个数据并仅在特定时间(例如10秒,可调)之后处理该阵列。如果可以较早获得完整的数据,则可以更早地编写它们,并且在这种情况下,您可以将抓取限制在特定的时间间隔内-当您尝试分别处理每个单个基准时,所有这些事情都很难完成。

Sub RecordData()

    ' create an array with 1 element for each of the 4 data you wish to record
    Dim Arr(1 To 4) As Variant
    Dim TimeOut As Single
    Dim Tmp As String
    Dim Done As Boolean
    Dim i As Integer                            ' loop counter

    TimeOut = Timer + 10                        ' allow 10 seconds to complete scraping
    Do While Not Done
        Done = True
        For i = 1 To 4
            If IsEmpty(Arr(i)) Then
                Tmp = GetMetaData(i)            ' get the scraped string
                Done = Len(Tmp)                 ' sets Done to False if Tmp is ""
            End If
        Next i
        If Timer > TimeOut Then Exit Do         ' end the loop on time-out
    Loop

    ' Now write the contents of Arr to your workbook
    ' It may be complete or not.
End Sub

Private Function GetMetaData(DataID As Integer) As String

    ' DataID should mark the difference between your
    ' procedures GetMwetaDat1 thru 4.
    ' If you don't know how to merge the 4 procedures into one
    ' on that basis, the following setup could be used.
    GetMetaData = Application.Run("GetMetaData" & DataID)

    ' The GetMetaData# procedures must be created as functions
    ' which return nothing if an error occurred.
    ' capture the error with
    On Error Resume Next
    If Err.Number = 0 Then
        ' GetMetaData# = [Scraped value]
    End If
    Err.Clear
    ' The above setup will return an empty string ("")
    ' if an error occurred in the scraping
End Function