Excel VBA - 表格(Arrary(" Sheet2"," Sheet3"))使用工作表名称的变量

时间:2012-02-01 02:06:28

标签: excel-vba arraylist vba excel

我想编写以下代码

表格(Arrary(“Sheet2”,“Sheet3”))。选择,通过为工作表名称创建一个变量来替换“Sheet2”,“Sheet3”。

Sub SelectMultipleSheets()

  Dim sSheets as String
  Dim intSheet As Integer

    sSheets = ""

    For intSheet = 1 To Sheets.count

        If Sheets(intSheet).Name <> "Sheet1" And intSheet <= Sheets.count Then

            Sheets(intSheet).Cells.Hyperlinks.Delete 'deleting hyperlinks

            sSheets = sSheets & Chr(34) & Sheets(intSheet).Name & Chr(34) & ","

        End If

    Next

    sSheets = Left(sSheets, Len(sSheets) - 1)
    Sheets(Array(sSheets)).Select

End Sub

我收到错误消息“下标不在范围内。我该如何解决?谢谢

2 个答案:

答案 0 :(得分:2)

在此行中构建数组列表参数

sSheets = sSheets & Chr(34) & Sheets(intSheet).Name & Chr(34) & "," 

你实际上是在创建一个逗号分隔的字符串变量,Excel无法知道你实际上是指逗号分隔字符串的列表。

你可以通过直接创建数组来解决这个问题。

Option Explicit

Sub SelectMultipleSheets()
    Dim intSheet As Integer
    Dim arSheets() As String
    Dim intArrayIndex As Integer

    intArrayIndex = 0

    For intSheet = 1 To Sheets.Count

        If Sheets(intSheet).Name <> "Sheet1" Then

            Sheets(intSheet).Cells.Hyperlinks.Delete 'deleting hyperlinks

            ReDim Preserve arSheets(intArrayIndex)
            arSheets(intArrayIndex) = Sheets(intSheet).Name
            intArrayIndex = intArrayIndex + 1
        End If
    Next

    Sheets(arSheets).Select

End Sub

答案 1 :(得分:0)

不能这样做,即使它看起来应该有效。相反,下面的代码利用Select's Replace参数添加到循环中的选择。 boolNoSelectionYet变量确保它不会添加到循环开始之前存在的选择中,例如,如果在例程启动时选择了Sheet1,则不希望它保持选中状态。

Sub SelectMultipleSheets()
Dim intSheet As Integer
Dim boolNoSelectionYet As Boolean

boolNoSelectionYet = True
For intSheet = 1 To Sheets.Count
    If Sheets(intSheet).Name <> "Sheet1" Then
        Sheets(intSheet).Cells.Hyperlinks.Delete
        Sheets(intSheet).Select (boolNoSelectionYet)
        boolNoSelectionYet = False
    End If
Next
End Sub

请注意,我删除了If语句的第二部分,因为For Next循环确保intSheet永远不会超过工作表数。