2017-07-21 73 views
2

我已經以兩個數組的形式命名這六個工作表來獨立完成他們的任務。我可以知道爲什麼這段代碼無法正常運行嗎?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 
+0

您的目標是?你想做什麼?代碼應該做什麼? – Wernerson

+0

'Sheets(MyArray(i))' – FunThomas

+0

@FunThomas它顯示類型不匹配。 –

回答

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將失敗。

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 

如果遇到錯誤,請確保數組中的所有工作表名稱確實存在爲工作表。

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 
相關問題