下标超出范围IF ISERROR问题

mik*_*ton 1 excel vba

这让我很生气.我已经找到了这个问题的答案,但找不到完全匹配.这条线:

If IsError(Sheets(this_year)) Then GoTo Line99
Run Code Online (Sandbox Code Playgroud)

用于确定表单是否6th April YYYY存在.如果我使用2019(确实存在),以下代码运行正常.但是,如果我使用2020(它不存在)给我

错误代码9,下标超出范围.

    Dim this_year As String
    this_year = "6th April 2020"
    Windows("Retirement Planning - Copy.xlsx").Activate
    If IsError(Sheets(this_year)) Then GoTo Line99
    Windows("Savings Details - Copy.xlsm").Activate
    MsgBox ("Congratulation")
    GoTo Line100
    Line99:
    MsgBox ("This year does not exist")
    Line100:
End Sub
Run Code Online (Sandbox Code Playgroud)

我认为"If IsError"应该"陷阱"错误并做一些事情,但我显然做了一些"令人眼花缭乱"的错误!

Sto*_*ant 5

我就是这样做的.

Dim thisYear As String
Dim currSheet as Worksheet
Dim found as Boolean

thisYear = "6th April 2020"

Windows("Retirement Planning - Copy.xlsx").Activate

For Each currSheet in ActiveWorkbook.Worksheets
    If currSheet.Name = thisYear Then
         found = True
         Exit For
    End If
Next

If found Then
    MsgBox ("Congratulations! " & currSheet.Name & " Found!")
Else
    MsgBox ("The sheet named " & thisYear & " does not exist")
End If
Run Code Online (Sandbox Code Playgroud)