2015-09-04 60 views
0

我一直無法弄清楚如何將計數器添加到下面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 

回答

0

您總是將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 
+0

謝謝!我把它放在''for each''循環之外,它工作!我一直盯着這個宏觀太久了。 – RTrain3k

+0

@ user3290799很高興我能幫忙。 –