2016-12-28 75 views
0

我想寫一個循環,基於兩個條件添加單元格到一個範圍。程序級變量在循環中丟失值嗎?

1)的細胞或者是向右或已在的範圍內的小區的向下,

2)的單元是相同的顏色作爲先前指定的顏色。

Sub DefineContiguousRegion() 

Dim c As Range 
Dim areNewCells As Boolean 

Do 
    areNewCells = False 
    For Each c In CurrentRange 
     If (Intersect(CurrentRange, c.Offset(1)) Is Nothing) And c.Offset(1).Interior.ColorIndex = CurrentColor Then 
      areNewCells = True 
      CurrentRange = Union(CurrentRange, c.Offset(1)) 
     End If 
     If (Intersect(CurrentRange, c.Offset(, 1)) Is Nothing) And c.Offset(, 1).Interior.ColorIndex = CurrentColor Then 
      areNewCells = True 
      CurrentRange = Union(CurrentRange, c.Offset(, 1)) 
     End If 
    Next 
Loop Until areNewCells = False 

的問題是,可變areNewCells在的末端對於每一個環被重置爲斷章取義。所以即使條件從未被滿足,即使該值從未被設置爲真。

這是怎麼發生的?我該如何解決它?

如果有人能想出一個更簡單的方法來創建這個範圍,那很好,但我真正想要的是更好地理解變量範圍/生命期,因爲這是一個學習項目,而不是時間敏感的工作相關。

+0

您是否通過加強與在本地窗口觀察'areNewCells'的價值? – Porcupine911

+0

是的。我在Loop Until之前的「next」語句中有一個斷點。一旦我到達「下一個」聲明,本地窗口就會清除。 – Rubikkon

+0

CurrentRange的定義在哪裏? –

回答

0

既然你問了更簡單的方法,你可以考慮下面的代碼:

With CurrentRange 
    For Each c In Union(.Offset(, .Columns.count).Resize(.Rows.count + 1, 1), .Offset(.Rows.count).Resize(1)) '<--| loop through wanted cells only 
     If c.Interior.ColorIndex = CurrentColor Then Set CurrentRange = Union(CurrentRange, c) 
    Next c 
End With 
+0

@Rubikon,您是否通過了它? – user3598756