在Excel VBA中嵌套For循环

时间:2017-03-14 17:54:31

标签: excel-vba vba excel

以下代码仅适用于c = 2,但我希望它也适用于其他值。下面是我要运行它的Excel表。

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

1 个答案:

答案 0 :(得分: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