2017-08-22 58 views
0

我在创建多个/嵌套循环时遇到问题。我可以编写一段代码,并重复17次,每次都稍作修改,但我试图避免这种情况。Excel中的多个循环VBA

我的代码看起来像下面这样,其他一切都很好,除了最后添加'循环所需的部分。所以基本上循环应该包括“AJ2,AK2,...,AZ2”和“1,2,...,17”。

任何帮助将不胜感激。这几个星期我一直在努力。

Sub Test() 

Worksheets("SheetName").Activate 
Range("A1").CurrentRegion.Copy 
Worksheets("NewSheet").Activate 

Range("A1").PasteSpecial 
Range("A1").PasteSpecial xlPasteColumnWidths 

Dim c As Range 
Dim col1 As Range 
Dim j As Integer 
Dim Source As Worksheet 
Dim Target As Worksheet 
Dim lastrow As Long 

Set Source = ActiveWorkbook.Worksheets("SheetName") 
Set Target = ActiveWorkbook.Worksheets("NewSheet") 
Set col1 = Source.Range("SheetName[Col]") 

j = 2  

For Each c In col1 
    If c >= Range("AJ2") Then 'loop needed with "AJ2" 
     Source.Range("A" & c.Row & ":BN" & c.Row).Copy 
     Target.Range("A" & Range("E65536").End(xlUp).Row + 1).PasteSpecial xlPasteValues 
     Target.Range("BO" & Rows.Count).End(xlUp).Value = DateAdd("m", 1, Range("BO2").Value) 'loop needed with 1 
     j = Range("A65536").End(xlUp).Row + 1 
    End If 
Next c 

For Each c In col1 
    If c >= Range("AK2") Then 'loop needed with "AK2" 
     Source.Range("A" & c.Row & ":BN" & c.Row).Copy 
     Target.Range("A" & Range("E65536").End(xlUp).Row + 1).PasteSpecial xlPasteValues 
     Target.Range("BO" & Rows.Count).End(xlUp).Value = DateAdd("m", 2, Range("BO2").Value) 'loop needed with 2 
     j = Range("A65536").End(xlUp).Row + 1 
    End If 
Next c 

End Sub 
+0

编写一个带'Range(“AJ2”)'&c的*函数*。作为*参数* – Bathsheba

回答

0

尝试使用cells([rownumber], [columnnumber])而不是按名称引用范围。这样,您可以轻松地使用增加的数字来进行循环,而不是文本。