【问题标题】:VBA code to ignore error if sheet from array not exist如果数组中的工作表不存在,则 VBA 代码忽略错误
【发布时间】:2013-01-09 01:47:13
【问题描述】:

我正在尝试将特定工作表合并到工作簿中的一张工作表中。这里的挑战是阵列中的工作表可能并非一直可用。所以宏应该忽略那些并移动到下一张表来复制数据。我已经编写了代码,但是当工作表不存在时,宏会出现错误。

Sub test()
Dim MyArr, j As Long
Dim ws As Worksheet
Dim sary, i As Long

Worksheets.Add Before:=Worksheets("Equity")
ActiveSheet.Name = "Consolidated"
MyArr = Array("Sample Sheet_Equity", "Sample Sheet_Funds", "Sample Sheet_Warrants",    "Eq", "Fu", "Wa")

For j = 0 To UBound(MyArr)

Set ws = Worksheets(MyArr(j))

If Not ws Is Nothing Then

    ws.Select
    Rows("2:2").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
    Sheets("Consolidated").Select
    Range("A2").End(xlDown).Offset(1, 0).Select

    ActiveSheet.Paste
End If
Next
End Sub

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    你可以这样做:

    For j = 0 To UBound(MyArr)
        On Error Resume Next
        Set ws = Worksheets(MyArr(j))
        If Err.Number = 0 Then
            On Error GoTo 0    
            If Not ws Is Nothing Then
                'Your copying code goes here
            End If
        Else
            Err.Clear
        End If
    Next
    

    更新:感谢 Doug Glancy 的评论,这里是更精简的版本

    For j = 0 To UBound(MyArr)
        Set ws = Nothing
    
        On Error Resume Next
        Set ws = Worksheets(MyArr(j))
        On Error GoTo 0    
    
        If Not ws Is Nothing Then
            'Your copying code goes here
        End If
    Next
    

    【讨论】:

    • 我使用了这个,但每次工作表不存在时,它都会从活动表中复制数据。我希望它跳过复制并移至下一张。
    • 当工作表不存在时ws 将被评估为Nothing,因此您的整个If Not ws Is Nothing Then ... End If 块不应执行
    • 谢谢彼得,未评估 ws 的方法是什么,然后转到下一个 ws
    • 这只会跳过一次。例如,数组中有 6 张工作表,但在工作簿中只有 3 张存在。使用此代码将仅跳过第一张工作表,并为下一张不存在的工作表引发错误。
    • 我知道你找到了一些可行的方法,但我认为这个答案过于复杂,而且你的第一个版本更接近理想。要意识到的是,尝试将ws 设置为不存在的工作表会将其设置为之前设置的任何值。它没有将其设置为Nothing。但是,如果在尝试将其设置为数组成员之前将其设置为 Nothing,则可以轻松测试它是否仍然为 Nothing 并跳过处理。我总是对我的 On Error 对处于不同缩进级别的代码持怀疑态度:)。
    猜你喜欢
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 2017-02-15
    相关资源
    最近更新 更多