2013-02-15 38 views
2

如果我有一個循環,開始:識別VBA中For Each循環的迭代?

For each c in Range("A1:C8") 

是否有標識的時間迄今循環已經迭代次數的佔位符c (c.count, c.value, c.something,...)的財產?我寧願使用這樣的東西,而不是包含另一個變量。

+5

沒有。你必須自己數數。 – RBarryYoung 2013-02-15 00:49:21

回答

0

你需要自己算吧這樣

Dim i as integer 
i = 0  
For each c in Range("A1:C8") 
    i = i + 1 

或者

Dim i as integer 
Dim c as Range 
For i = 0 to Range("A1:C8").Count - 1 
    Set c = Range("A1:C8").Cells(i) 
+0

如果您以不同的方式構建循環,則不需要添加額外的變量來執行計數。你可以引用像Range這樣的單元格範圍(「A1:C8」)。單元格(c)'只要'c'被標註爲長/整數。 – 2013-02-15 04:14:10

4

而不是使用 「有效範圍內的每個C」,你可以做這樣的事情:

Dim c as Long 'presumably you did this as a Range, just change it to Long. 
Dim myRange as Range 'Use a range variable which will be easier to call on later 
Set myRange = Range("A1:C8") 

For c = 1 to myRange.Cells.Count 
    'Do something to the cell, identify it as myRange.Cells(c), for example: 
    myRange.Cells(c).Font.Bold = True '<--- replace with your code that affects the cell 
Next 

這使您可以執行完全相同的For/Next循環,而不包含不必要的計數器變量。在這種情況下,c是一個計數器,但也用於識別受代碼影響的單元。

+0

如果你使用'For Each c In Range'語法,你可以在循環中使用'c.Font.Bold = True',所以不需要'Long'變量... – 2013-02-15 04:54:24

+1

這個技術的問題是它需要索引訪問才能進入單元格區域,這通常是迭代的起點。 – 2013-02-15 05:44:19

+0

@OlleSjögren**如果OP希望能夠在不使用額外的計數器變量的情況下對迭代進行計數,那麼**需要「Long」變量。 – 2013-02-15 13:11:35

0

(修訂版)

使用列或行屬性,如適合於你迭代的方向,就可以計算在飛行的序數。因此,

For Each c1 in myRange 
    myOrdinal = c1.row - myRange.row + 1  ' down contiguous cells in one column 
    myOrdinal = c1.Column - myRange.Column + 1 ' contiguous columns, L2R 
Next 
+0

我喜歡你的想法,但不應該是_myOrdinal =(c1.Row - 1)* myRange.Columns.Count + c1.Column_?作爲一名老C/C++程序員,我假定每個循環先遍歷一行,再遍歷一行,但你知道他們對假設的看法。如果它先倒列,那麼它會是myOrdinal = _(c1.Column - 1)* myRange.Rows.Count + c1.Row_ ..順便說一下,是否可以指定每個循環遍歷範圍的方式,類似到.find函數(byRows或byColumns)? – riderBill 2015-12-15 00:01:47