簡體   English   中英

為什么此嵌套循環不起作用?

[英]Why isn't this nested loop working?

我不能讓它循環到下一行。 我可以使用調試器告訴我們,內部的兩個循環工作正常,但從未進行到下一行。 任何幫助,將不勝感激。

Sub PopulateData()
Dim s1 As Worksheet
Dim s2 As Worksheet
Dim locationRow As Integer
Set s1 = ThisWorkbook.Sheets("Order_LVL")
Set s2 = ThisWorkbook.Sheets("sheet1")
Dim Lastrow As Integer
Lastrow = s1.Cells(Rows.Count, 1).End(xlUp).Row
Dim iRow As Integer

For iRow = 1 To Lastrow
Dim cellj As Range
    For Each cellj In s1.Range("B:F")
    locationRow = 1
    Dim celli As Range
        For Each celli In s2.Range("B1:F1")
        Dim currentrow As Long
        currentrow = iRow + 1
            If s1.Cells(currentrow, cellj.Column).Value = 0 Then

            ElseIf s1.Cells(currentrow, cellj.Column).Value <>   s2.Cells(locationRow, celli.Column).Value And s2.Cells(currentrow, celli.Column).Value = 0 Then
            s2.Cells(currentrow, celli.Column).Value = 0
            Else: s2.Cells(currentrow, celli.Column).Value = 1 'indicates that this order features a line from this location
            End If
        Next celli
    Next cellj
Next iRow
End Sub

您可以在一些測試數據上嘗試一下嗎(請注意,我自己並沒有對其進行測試,而是僅通過兩個循環將其重寫)

Sub PopulateData()
Dim s1 As Worksheet: Dim s2 As Worksheet
Dim rng As range: Dim rng2 As range
Dim cell: Dim header

With Application
    .ScreenUpdating = False
End With

With ThisWorkbook
    Set s1 = .Sheets("Order_LVL")
    Set s2 = .Sheets("sheet1")
End With

With s1
    Set rng = range(.Cells(1, 2), .Cells(.Cells(Rows.Count, 6).End(xlUp).Row, 6)) ' Used Range in Order_LVL
End With

Set rng2 = range(s2.Cells(1, 2), s2.Cells(1, 6)) 'Header range in sheet1

For Each cell In rng.Cells
    For Each header In rng2.Cells
        If cell.value = 0 Then

        ElseIf cell.value <> header.value And s2.Cells(cell.Row, header.Column).value = 0 Then
            s2.Cells(cell.Row, header.Column).value = 0 ' Not sure why you're doing this - if it is already 0 why set it back to 0. Left it in for continuity
        Else
            s2.Cells(cell.Row, header.Column).value = 1 ' indicates that this order features a line from this location
        End If
    Next header
Next cell

With Application
    .ScreenUpdating = True
End With
End Sub

如果我理解正確,它應該可以執行您想要的操作。

暫無
暫無

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

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