VBA选择数组

时间:2017-07-21 07:30:00

标签: excel vba excel-vba

我已经将这六个工作表命名为两个数组,以独立完成任务。我可以知道为什么这段代码不能正常运行吗?

错误发生在Sheets(i).Select,说选择工作表类的方法失败了。我确实尝试更改为.Activate,但代码似乎没有运行。

MyArray = Array("CPWAEB", "CPWAFB", "CRRTPN", "CRRTQN")
MyArray1 = Array("ACM", "GMRTR")

For Each i In MyArray
    Sheets(i).Select
    Range("G12").GoalSeek Goal:=0, ChangingCell:=Range("G7")
Next i

For Each j In MyArray1
    Sheets(j).Select
    ActiveSheet.Calculate
Next j

3 个答案:

答案 0 :(得分:3)

这就是遵循良好做法的方式。避免使用选择或激活,这是一种不好的做法。

Option Explicit 'Very first line ensures that every variable is declared properly.

Public Sub MySub()
    Dim MyArray() As Variant, MyArray1() As Variant
    Dim i As Long

    MyArray = Array("CPWAEB", "CPWAFB", "CRRTPN", "CRRTQN")
    MyArray1 = Array("ACM", "GMRTR")

    For i = LBound(MyArray) To UBound(MyArray)
        With Worksheets(MyArray(i))
            .Range("G12").GoalSeek Goal:=0, ChangingCell:=.Range("G7")
        End With
    Next i

    For i = LBound(MyArray1) To UBound(MyArray1)
        Worksheets(MyArray1(i)).Calculate
    Next i
End Sub

如果遇到错误,请确保数组中的所有工作表名称确实作为工作表存在。

答案 1 :(得分:2)

您可以像这样迭代工作簿中的工作表:

For Each i In MyArray
    With ThisWorkbook.Worksheets(i)
        .Range("G12").GoalSeek Goal:=0, ChangingCell:=.Range("G7")
    End With
Next i

For Each j In MyArray1
    With ThisWorkbook.Worksheets(j)
        .Calculate
    End With
Next j

确保所有单元格(G12)都包含公式,否则GoalSeek将失败。

答案 2 :(得分:0)

Sub test()
    Dim MyArray, i
    MyArray = Array("CPWAEB", "CPWAFB", "CRRTPN", "CRRTQN")

    For Each i In MyArray
        ' Sheets(i).Select => This won't work when Sheets(i) is not active one
        Sheets(i).Activate ' First activate
        Range("G12").GoalSeek Goal:=0, ChangingCell:=Range("G7") ' Then use the Range on active sheet
    Next i

    ' When not necessary to activate the sheets
    ' you can use Sheets with array as parameter
    Dim sh As Worksheet
    For Each sh In Sheets(MyArray)
        sh.Range("G12").Value = sh.Name
    Next sh
End Sub