下标超出范围 - 运行时错误9

时间:2017-03-02 11:00:03

标签: vba excel-vba excel

你能告诉我为什么下面的代码没有选择可见的表格,但结果是运行时错误。这真让我抓狂。谢谢你的帮助。

Sub SelectSheets1()

    Dim mySheet As Object
    Dim mysheetarray As String

    For Each mySheet In Sheets
        With mySheet
            If .Visible = True And mysheetarray = "" Then
                mysheetarray = "Array(""" & mySheet.Name
            ElseIf .Visible = True Then
                mysheetarray = mysheetarray & """, """ & mySheet.Name
            Else
            End If
        End With
    Next mySheet        

    mysheetarray = mysheetarray & """)"                
    Sheets(mysheetarray).Select

End Sub

3 个答案:

答案 0 :(得分:3)

长话短说 - 当你期待数组时,你会给出一个字符串(mysheetarray)。 VBA喜欢得到它所期望的。

长篇故事 - 这是选择所有可见工作表的方法:

Option Explicit

Sub SelectAllVisibleSheets()

    Dim varArray()          As Variant
    Dim lngCounter          As Long

    For lngCounter = 1 To Sheets.Count
        If Sheets(lngCounter).Visible Then
            ReDim Preserve varArray(lngCounter - 1)
            varArray(lngCounter - 1) = lngCounter
        End If
    Next lngCounter

    Sheets(varArray).Select

End Sub

答案 1 :(得分:2)

您应该将Dim mySheet As Object定义为Worksheet

此外,您可以使用可见的Sheet.Name数组。

<强>代码

Sub SelectSheets1()

    Dim mySheet As Worksheet
    Dim mysheetarray() As String
    Dim i As Long

    ReDim mysheetarray(Sheets.Count) '< init array to all existing worksheets, will optimize later
    i = 0
    For Each mySheet In Sheets
        If mySheet.Visible = xlSheetVisible Then
            mysheetarray(i) = mySheet.Name
            i = i + 1
        End If
    Next mySheet

    ReDim Preserve mysheetarray(0 To i - 1) '<-- optimize array size    
    Sheets(mysheetarray).Select

End Sub

答案 2 :(得分:1)

我试图解释Sheets一点,HTH。 注意:Sheets属性在WorkbookApplication对象上定义,两者都有效,并返回Sheets-Collection

Option Explicit

Sub SheetsDemo()
    ' All sheets
    Dim allSheets As Sheets
    Set allSheets = ActiveWorkbook.Sheets

    ' Filtered sheets by sheet name
    Dim firstTwoSheets As Sheets
    Set firstTwoSheets = allSheets.Item(Array("Sheet1", "Sheet2"))
    ' or simply: allSheets(Array("Sheet1", "Sheet2"))
    ' Array("Sheet1", "Sheet2") is function which returns Variant with strings

    ' So you simply need an array of sheet names which are visible
    Dim visibleSheetNames As String
    Dim sh As Variant ' Sheet class doesn't exist so we can use Object or Variant
    For Each sh In allSheets
        If sh.Visible Then _
            visibleSheetNames = visibleSheetNames & sh.Name & ","
    Next sh

    If Strings.Len(visibleSheetNames) > 0 Then
        ' We have some visible sheets so filter them out
        visibleSheetNames = Strings.Left(visibleSheetNames, Strings.Len(visibleSheetNames) - 1)
        Dim visibleSheets As Sheets
        Set visibleSheets = allSheets.Item(Strings.Split(visibleSheetNames, ","))

        visibleSheets.Select

    End If
End Sub