2013-08-28 20 views
1

我正在遍歷VBA中的一個範圍,當前處於for循環中。我有一個if語句,當它們符合某些條件時會從該範圍中刪除值,但是當我這樣做時,範圍中的下一個值將被跳過。在VBA中迭代通過更改範圍

我知道我可以在Java中使用數組和迭代器解決這個問題,VBA是否有類似的東西?

+0

您是使用'For var = ...'還是'For Each'? –

+0

我使用的每個現在使用爲 – Intern87

回答

1

你必須刪除行時迭代向後因此,你必須使用for循環,而不是for each

您設置i在範圍內的最後一排,然後添加step -1有循環遞減的i

樣品for each不會正常工作

dim cell as Range 
for each cell in Range("A1:A100") 
    if isEmpty(cell) then cell.delete shift:=xlUp 
next 

替換For循環,如果它們爲空將刪除行

dim i as long, lastRow as Long, firstRow as Long 
lastRow = 100: firstRow = 1 
dim cell as Range 
for i = lastRow to firstRow step -1 
    Set cell = Range("A" & i) 
    if isEmpty(cell) then cell.Delete shift:=xlUp 
    Set cell = Nothing 
next i 
+1

這是偉大的歡呼聲 – Intern87