下标超出范围IF ISERROR问题

时间:2018-11-08 16:16:41

标签: excel vba

这让我发疯了。我一直在寻找这个问题的答案,但找不到确切的匹配。该行:

If IsError(Sheets(this_year)) Then GoTo Line99

用于确定工作表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

我以为“ If IsError”应该“捕获”错误并执行某些操作,但是我显然在错误地执行“非常明显”的操作!

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

避免循环和错误处理

您可以在一个衬里中使用IsError,但要引用任何现有的单元格(例如A1):

Sub CheckWS()
Dim thisYear$: thisYear = "6th April 2020"
Windows("Retirement Planning - Copy.xlsx").Activate

If Not IsError(Application.Evaluate("'" & thisYear & "'!A1")) Then
    MsgBox ("Congratulations! '" & thisYear & "' Found!")
Else
    MsgBox ("The sheet named '" & thisYear & "' does not exist")
End If
End Sub

答案 2 :(得分:0)

考虑:

Sub ErrorKatcher()
    Dim ws As Worksheet, s As String

    s = "whatever"
    On Error GoTo gotcha
        Set ws = Sheets(s)
    On Error GoTo 0
    MsgBox "NO ERROR"
    Exit Sub
gotcha:
    MsgBox "an error occurred"
End Sub