2017-03-14 165 views
0

以下代碼僅適用於c = 2,但我希望它也適用於其他值。下面是我想要運行它的Excel表格。在Excel VBA中嵌套for循環

Date PickupCost StorageCost DeliveryCost 
1/1/2017 140  35   0 
1/8/2017 80  20   0 
1/10/2017 0   0   149 
1/30/2017 35   8   0 

我要填寫每個日期失蹤,但只在第3欄(StorageCost)值的數據需要在其他失蹤日期值前一天的StorageCost值相同。

Dim j, p, w, c As Long 
Dim date1, date2 As Date 
j = Cells(Rows.Count, 1).End(xlUp).Row 
w = 2 
For c = w To j 
    date1 = Range("A" & w).Value 
    date2 = Range("A" & (w + 1)).Value 
    p = DateDiff("d", date1, date2) 
    For w = 2 To p 
     Range("A" & (c + 1)).EntireRow.Insert 
     ActiveSheet.Cells(c + 1, 1).Value = (ActiveSheet.Cells(c, 1).Value) + 1 
     ActiveSheet.Cells(c + 1, 2).Value = 0 
     ActiveSheet.Cells(c + 1, 3).Value = ActiveSheet.Cells(c, 3).Value 
     ActiveSheet.Cells(c + 1, 4).Value = 0 
     c = c + 1 
    Next w 
    w = w + 1 
    ActiveSheet.Range("A1").Select 
    j = Cells(Rows.Count, 1).End(xlUp).Row 
Next c 
+0

什麼是C應該是和你在哪裏初始化呢? –

+0

c是基於哪個循環需要運行的次數的計數器,以便需要計算在前一行的行和日期的每個日期組合之間的間隙。它是根據w的值初始化的。 –

+0

請解釋你想要做得更好 - 我不明白。 「數據缺失」是否爲0值?你能舉一個你想要結果的例子嗎? – user1274820

回答

1

你的主要問題是,一旦你確定你的For c = w To j環路,則它將只運行,直到它到達當你定義的for循環j值了。 如果你想要一個端點,能夠適應在運行時更改的行數的循環,你應該使用Do Until循環,就像這樣:

Dim p As Long 
Dim c, w As Integer 
Dim date1, date2 As Date 

c = 2 
Do Until c = Cells(Rows.Count, 1).End(xlUp).Row 
    date1 = Range("A" & c).Value 
    date2 = Range("A" & (c + 1)).Value 
    p = DateDiff("d", date1, date2) 
    For w = c To c + p - 2 
     Range("A" & (w + 1)).EntireRow.Insert 
     ActiveSheet.Cells(w + 1, 1).Value = (ActiveSheet.Cells(c, 1).Value) + 1 
     ActiveSheet.Cells(w + 1, 2).Value = 0 
     ActiveSheet.Cells(w + 1, 3).Value = ActiveSheet.Cells(c, 3).Value 
     ActiveSheet.Cells(w + 1, 4).Value = 0 
     c = c + 1 
    Next w 
    c = c + 1 
Loop 
+0

非常感謝。它完全按照我的要求工作。 –