同时更改循环VBA的变量

时间:2018-04-25 20:11:50

标签: excel-vba for-loop nested-loops vba excel

试图让BRarr1和BRarr2同时改变。我知道它目前的运行方式会在改变之前改变b。

有没有办法运行这样的东西,以便在继续执行代码之前更改两个工作表?

代表。我需要通过BR01和BR01A然后运行BR5和BR05A等等

Sub BranchAnalysis()
Dim s1 As Worksheet
Dim s2 As Worksheet
Dim a As Integer
Dim b As Integer
Dim BRarr1
Dim BRarr2

BRarr1 = Array("BR1", "BR5", "BR10", "BR11", "BR13", "BR18", "BR20", "BR21", 
                "BR22", "BR23", "BR25", "BR28", "BR29", "BR33", "BR35")
BRarr2 = Array("BR01A", "BR05A", "BR10A", "BR11A", "BR13A", "BR18A", 
              "BR20A", "BR21A", "BR22A", "BR23A", "BR25A", "BR28A", "BR29A", 
               "BR33A", "BR35A")

For a = LBound(BRarr1) To UBound(BRarr1)
    For b = LBound(BRarr2) To UBound(BRarr2)

    Set s1 = Workbooks("Primary to Network vBG2.xlsm").Worksheets("" & BRarr1(a) & "")
    Set s2 = Workbooks("Primary to Network vBG2.xlsm").Worksheets("" & BRarr2(b) & "")

    r1 = Workbooks("Primary to Network vBG2.xlsm").Worksheets("" & BRarr1(a) & "").UsedRange.Rows.count
    r2 = Workbooks("Primary to Network vBG2.xlsm").Worksheets("" & BRarr2(b) & "").UsedRange.Rows.count

    Dim i, j As Long

    'line items count
    Dim count1 As Long
    count1 = 0
    For j = 2 To r2
        For i = 2 To r1
        If s2.Cells(j, 1).Value = s1.Cells(i, 1).Value Then
           count1 = count1 + 1
           s2.Cells(j, 2).Value = count1
        Else
        End If
        Next i
        count1 = 0
    Next j

blah blah more code

    Next b
next a

1 个答案:

答案 0 :(得分:0)

(基于Scott的评论)

BRarr1 BRarr2 都有ubound = 14

所以只使用一个循环:

替换:

For a = LBound(BRarr1) To UBound(BRarr1)
    For b = LBound(BRarr2) To UBound(BRarr2)

有类似的东西:

 For ZZ = 0 to 14

并在您使用ZZa

的任何地方使用b