簡體   English   中英

在Excel VBA中嵌套循環

[英]Nested For Loop in Excel VBA

以下代碼僅在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

您的主要問題是,一旦定義了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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM