运行时错误:Excel宏2016中的“9”下标超出范围

问题描述 投票:-2回答:1

我要求隐藏或取消隐藏Excel电子表格中的某些选项卡,具体取决于值是否设置为True或封面上是否为空。

在宏中使用下面的代码,它一直工作,直到它到达最后一个选项卡。

例如:选项卡1和2设置为True,选项卡3和4设置为空白。

当宏运行时,它将使选项卡1和2可见并隐藏选项卡3和4,但随后它会因错误而失败

run-time error '9' subscript out of range

我猜这是因为没有什么可以检查所以它失败了。我怎么能告诉宏停止?当我调试代码时,它突出显示Else之后的行(Worksheets(cell.Value).Visible = xlSheetHidden)

If (Worksheets ("Cover").Cells(rValue, cell.Column).Value = True) Then
    Worksheets(cell.Value).Visible = xlSheetVisible
Else 
    Worksheets(cell.Value).Visible = xlSheetHidden 
End If
vba excel-vba
1个回答
0
投票

这实现了您的目标。

Private Sub hideshit()
    Dim arr As Variant
    Dim i As Long

    arr = ThisWorkbook.Sheets("Sheet1").UsedRange
    For i = LBound(arr, 1) To UBound(arr, 1)
        If arr(i, 2) = "n" Then
            Worksheets(i).Visible = False
        Else
            Worksheets(i).Visible = True
        End If
    Next i
End Sub

这是我的测试样本:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.