2011-09-22 196 views
1

我知道啓動單元格,我需要在列中向下。當下一個單元格爲空時,我需要退出循環。如何在VBA代碼中做到這一點?VBA如何遍歷Excel中的列

感謝回覆

+0

雖然這被標記爲回答一旦範圍被定義,你想要對列做什麼? – brettdj

+0

我正在使用Cognos TM1,並且需要從OLAP獲得對單元格的註釋 – joseph

回答

3

怎麼樣;

'//get a range from anchor cell (a1) to the 1st empty cell in the same column; 
dim r As Range, cell as Range 
set r = Range(Range("A1"), Range("A1").End(xlDown)) 

'//loop it 
for Each cell In r 
    msgbox cell.Value 
next 
+1

1)我不會使用單元格作爲變量名稱。稱它爲myCell。 2)你需要將'DIM myCell'作爲範圍' –

+1

添加一個暗淡的I剩餘單元格,它不是一個保留字,並且不會在xl對象模型中用作類名稱的任何地方(儘管Cells是) –

+0

感謝所有的答覆。 – joseph

0

在VBA中,基於細胞都可以用範圍來完成,使用偏移來回報你正在尋找的價值:

Dim Anchor as Range 

Set Anchor = Range("A1") 

i = 0 
Do 
    ' Cell in column is Anchor.Offset(0, i) 
    ' i.e., Anchor.Offset(0, 0) = A1 
    '  Anchor.Offset(0, 1) = B1 
    '  Anchor.Offset(0, ") = C1 
    '  etc. 

    ' Do whatever you like with this, here! 

    i = i + 1 
Loop Until Anchor.Offset(0, i) = "" 
1

我調整AlexK的回答是:

dim c As Range 

'//loop it 
for Each c In Range(Range("A1"), Range("A1").End(xlDown)) 
    msgbox c.Value 
next