2013-06-03 124 views
0

我想在Excel VBA中設置一個簡單的for循環,在指定的行開始,迭代直到文檔結束?我似乎不知道如何通過谷歌做到這一點。任何幫助將不勝感激。Excel,for循環問題

+1

參考該鏈接http://stackoverflow.com/questions/6301665/row-number-of-last-cell-with-data – Santosh

+1

又【此鏈接](http://support.microsoft.com/kb/299036)。 – chuff

+2

或者這一個:[在VBA中創建一個循環](http://stackoverflow.com/a/16745181/138938) –

回答

1

這將遍歷行直到找到空白單元格。

Dim iRow As Integer 
    iRow = 0 
    Do 
    iRow = iRow + 1 
    'do something 
    Debug.Print ActiveSheet.Range("A" & iRow).Value 

    Loop Until ActiveSheet.Range("A" & iRow).Formula = "" 
+0

請注意,如果您正在循環的範圍中有空白行,這將不起作用。 –

+0

是的,這就是爲什麼它會「查看行直到找到一個BLANK單元格」。 – nemmy

+1

許多數據集都有空白行撒在整個。如果你一旦空白就停下來,你將不會處理所有的數據。對此的標準方法是找到最後一行,並在它們打到時停止,而不是空白。 –

-2
Dim CurrentRow 
Dim LastRow 
Dim i 

CurrentRow = ActiveCell.Row 
CurrentColumn = ActiveCell.Column 
LastRow = ActiveSheet.Rows.Count 

For i = CurrentRow to LastRow 
    Cells(i, CurrentColumn).Value = "X" 
Next i 
1

如果您希望用戶指定要啓動的細胞中,這將正常工作。

Sub myLoop() 
Dim userInput As String 
Dim count As Integer 
Dim first As Integer 

userInput = InputBox("Which cell would you like to start in?", "Enter Range like 'A1'") 
first = ActiveSheet.Range(userInput).Row 
count = ActiveSheet.UsedRange.Rows.count 

For i = first To count 
    MsgBox "Row: " & i 
    'Replace the above msgbox function with the code you would like to run 
Next i 
End Sub