【问题标题】:Add counter to for each loop为每个循环添加计数器
【发布时间】:2015-09-04 20:20:16
【问题描述】:

我一直无法弄清楚如何在下面的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

【问题讨论】:

    标签: excel vba for-loop counter


    【解决方案1】:

    每次您总是将 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
    

    【讨论】:

    • 谢谢!我把它放在两个for each 循环之外,它起作用了!我一直盯着这个宏太久了。
    • @user3290799 很高兴我能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多