2017-08-04 402 views
0

我試圖建立一個代碼,允許我從多個日期範圍中生成日期列表,並將日期與相鄰單元格相匹配。VBA - 如何跳過循環中的空單元格?

由於我試圖自動化這個過程,我遇到的問題是原始數據在日期範圍之間有空行。所以問題是,我如何讓代碼跳過循環中的空行?

這是我到目前爲止有:

Sub Dates() 

Dim dStart As Date 
Dim dEnd As Date 
Dim dDate As Date 
Dim iCol As Integer 
Dim iColDate As Integer 

iCol = 6 
iColDate = 6 

Do While Cells(iCol, 3).Value <> "" 
    dStart = Format(Cells(iCol, 3).Value, "dd/mm/yyyy") 
    dEnd = Format(Cells(iCol, 4).Value, "dd/mm/yyyy") 
    For dDate = dStart To dEnd 
     Cells(iColDate, 7).Value = dDate 
     Cells(iColDate, 6).Value = Cells(iCol, 2).Value 
     iColDate = iColDate + 1 
    Next 
    iCol = iCol + 1 
Loop 


End Sub 

希望得到任何幫助都沒有。謝謝一堆!

+0

,我認爲,如果你加上'或者Worksheetfunction.Counta(行(ICOL))= 0'您'待辦事項得到控制而e'循環將檢查單元格是否爲空,或者該行是否爲空。 (爲什麼你把'iCol'作爲行變量?只是好奇) – BruceWayne

回答

0

嘗試使用Rows.CountFOR loop代替,這樣你在運行循環之前檢查的最後一排,並避免被踢出如果在C行單元格是空的循環:

Sub Dates() 

Dim dStart As Date 
Dim dEnd As Date 
Dim dDate As Date 
Dim iColDate As Integer 
Dim lastrow As Long 
Dim loop1 As Long 

lastrow = Cells(Rows.Count, "C").End(xlUp).Row 

iColDate = 6 

For loop1 = 6 To lastrow 
    dStart = Format(Cells(iCol, 3).Value, "dd/mm/yyyy") 
    dEnd = Format(Cells(iCol, 4).Value, "dd/mm/yyyy") 
    For dDate = dStart To dEnd 
     Cells(iColDate, 7).Value = dDate 
     Cells(iColDate, 6).Value = Cells(iCol, 2).Value 
     iColDate = iColDate + 1 
    Next 
Next loop1 

End Sub 
0

而不是循環到第一個空行,計算最後一行是第一個。

Dim lLastRow As Long 
    lLastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Row 

然後使用索引For..Next循環,而不是一個Do..While循環

Dim lIndex as long 
For lIndex = 1 to lLastRow 

' do stuff here 

Next 
相關問題