如果来自数组的表不存在,VBA代码将忽略错误

我正在尝试将特定图纸合并到工作簿中的一张图纸上。 这里的挑战是数组中的表可能并不是所有的时间都可用。 所以macros应该忽略这些,并移动到下一张表来复制数据。 我已经写了代码,但是当表单不存在的时候macros观错误就出错了。

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 

你可以这样做:

 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