簡體   English   中英

為每個循環添加計數器

[英]Add counter to for each loop

我一直無法弄清楚如何for each循環在下面添加一個計數器,因此當整個公式列完成后,循環將移至下一列。 所有計算均正確進行,但所有計算均在同一列中。 感謝您的任何建議。

Sub Test()
Dim SrchRng1 As Range, cell1 As Range
Dim SrchRng2 As Range, cell2 As Range

Dim lr As Long
lr = Sheets("sheet1").Cells(Rows.count, 2).End(xlUp).Row
Set SrchRng1 = Sheets("sheet1").Range("B3:B95")

Dim lc As Long
lc = Sheets("sheet2").Cells(3, Columns.count).End(xlToLeft).Column
Set SrchRng2 = Sheets("sheet2").Range("A3:AC3")

Dim lrr As Long
lrr = Sheets("sheet2").Cells(Rows.count, 2).End(xlUp).Row

Dim c As Long
c = 0

For Each cell1 In SrchRng1
    For Each cell2 In SrchRng2

        If cell1.Value = cell2.Value Then
            c = 31
            For r = 4 To 100
                  Cells(r, c).FormulaR1C1 = "=sheet1!" & cell1.Offset(, 1).Address(ReferenceStyle:=xlR1C1) & "*" & cell2.Offset(1, 0).Address(ReferenceStyle:=xlR1C1) & ""
            Next r
            c = c + 1
        End If
    Next cell2
Next cell1
Application.DisplayAlerts = True
End Sub

每次您總是將c重置為31。 將c = 31從內循環中移到第一個for語句的正下方。 像這樣:

For Each cell1 In SrchRng1
    c = 31
    For Each cell2 In SrchRng2

        If cell1.Value = cell2.Value Then

             For r = 4 To 100
                  Cells(r, c).FormulaR1C1 = "=sheet1!" & cell1.Offset(, 1).Address(ReferenceStyle:=xlR1C1) & "*" & cell2.Offset(1, 0).Address(ReferenceStyle:=xlR1C1) & ""
            Next r
            c = c + 1
        End If
   Next cell2
Next cell1

暫無
暫無

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

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