2011-09-26 249 views
0

我有下面的宏,讓腳本超出範圍的錯誤在If arr(0) <> opt Then arr(0) = VAL_DIFFExcel宏標超出範圍的錯誤

,如果我看到一個數組的長度它顯示2.我不明白爲什麼我不能夠訪問arr(0),據我所知數組總是以0開始。我能夠打印arr(1),arr(2)值。

下面的宏能夠找到相似的記錄並複製到sheet2.Here我也想用sheet1中的顏色來突出顯示。請幫幫我。

Option Base 1 
Sub Tester() 

    Const COL_ID As Integer = 1 
    Const COL_SYSID As Integer = 2 
    Const COL_STATUS As Integer = 4 
    Const COL_OPTION As Integer = 3 
    Const VAL_DIFF As String = "XXdifferentXX" 

    Dim d As Object, sKey As String, id As String 
    Dim rw As Range, opt As String, rngData As Range 
    Dim rngCopy As Range, goodId As Boolean 
    Dim FirstPass As Boolean, arr 

     With Sheet1.Range("A1") 
      Set rngData = .CurrentRegion.Offset(1).Resize(_ 
          .CurrentRegion.Rows.Count - 1) 
     End With 
     Set rngCopy = Sheet1.Range("F2") 

     Set d = CreateObject("scripting.dictionary") 
     FirstPass = True 

    redo: 
     For Each rw In rngData.Rows 

      sKey = rw.Cells(COL_SYSID).Value & "<>" & _ 
        rw.Cells(COL_STATUS).Value 

      If FirstPass Then 
       'Figure out which combinations have different option values 
       ' and at least one record with id=US or CHN 
       id = rw.Cells(COL_ID).Value 
       goodId = (id = "US" Or id = "CHN") 
       opt = rw.Cells(COL_OPTION).Value 

       If d.exists(sKey) Then 
        arr = d(sKey) 'can't modify the array in situ... 
        If arr(1) <> opt Then arr(1) = VAL_DIFF 
        If goodId Then arr(2) = True 
        d(sKey) = arr 'return [modified] array 
       Else 
        d.Add sKey, Array(opt, goodId) 
       End If 

      Else 
       'Second pass - copy only rows with varying options 
       ' and id=US or CHN 
       If d(sKey)(2) = VAL_DIFF And d(sKey)(1) = True Then 
        rw.Copy rngCopy 
        Set rngCopy = rngCopy.Offset(1, 0) 
       End If 
      End If 

     Next rw 
     If FirstPass Then 
      FirstPass = False 
      GoTo redo 
     End If 

    End Sub 
+0

您是否嘗試過在數組中調用Lbound和Ubound並在引用它們之前查看真正的邊界是否正確? – Brad

回答

2

停止在模塊頂部使用選項庫1。它似乎可以讓事情變得更容易,但最終只會導致混亂。我已經給你提供了着色範圍的答案 - 請嘗試在發佈之前先查看並試用它們。

+0

感謝您的建議,當我刪除或更改爲選項基地0.在這兩種情況下,我存在的代碼無法正常工作。 – Raj

+0

然後只需調整您發佈的代碼中的索引即可。 0 - > 1和1 - > 2 –

+0

您好,現在我在這裏得到錯誤d(sKey)(0)= VAL_DIFF和d(sKey)(1)= True.if我chnaged o-> 1和1 - > 2.輸出不如預期。 – Raj

0

要檢查數組的下限位置,請使用Lbound(arr)

此外,您沒有將arr初始化爲數組。像這樣初始化它: Dim arr() As Variant

您還可以指定數組的較低維度和較高維度。 Dim arr(3 To 10) As Variant。這將創建一個從零開始的7個元素的數組。我建議通過Google搜索學習更多關於VBA中的數組的知識。

+0

:即使在數組初始化後,我也會得到相同的錯誤。 – Raj

+0

我不認爲這個問題與任何索引問題有關,Raju。它看起來像代碼只需要重寫。你有一個數組的字典對象。你可能想製作一個2D數組。 Dim arr(0 To 1000,0 To 2)As Variant:arr(0)= d(sKey)(0):arr(1)= d(sKey)(1)[...]你想做什麼? – Bobort