VBA中的Double For循环,下标不同

时间:2019-07-11 10:24:26

标签: excel vba loops double subscript

我在VBA中存在嵌套循环问题。我需要执行的算法如下:

Option base 1
arr(4,2)
i = 1 To 4
j = 2 To 100

i = 1, j = 2 If Cells(2, 1).Value = arr(1,1) Then
                Cells(2,11) = arr(1,2)
i = 1, j = 3 If Cells(3,1).Value = arr(1,1) Then
                Cells(3,11) = arr(1,2)
i = 1, j = 4 If Cells(4,1).Value = arr(1,1) Then
                Cells(4,11).Value = arr(1,2) 
.
.
.

i = 1, j = 100 If Cells(100,1).Value = arr(1,1) Then
                  Cells(100,11).Value = arr(1,2)

And if j reaches 100 then

i = 2, j = 2 If Cells(2,1).Value = arr(2,1) Then
                Cells(2,11).Value = arr(2,2)
i = 2, j = 3 If Cells(3,1).Value = arr(2,1) Then
                Cells(3,11).Value = arr(2,2)
i = 2, j = 4 If Cells(4,1).Value = arr(2,1) Then
                Cells(4,11).Value = arr(2,2)
.
.
.

i = 2, j = 100 If Cells(100,1).Value = arr(2,1) Then
                  Cells(100,1).Value = arr(2,2)

And so on, until i = 4。 希望您能明白:D现在,我需要在VBA中执行此操作-现在我不知道该怎么做,不幸的是,我尝试的只是一次失败,所以我什至没有适合您的代码示例; /我尝试过类似的事情

For i = 1 To 4
    For j = 1 To 100
      If Cells(j, 1).Value = arr(i, 1) Then
         Cells(j,11).Value = arr(i,2)
      End If
    Next j
Next i

但是,它当然显示“下标超出范围”,我也尝试了使用For Each进行某些操作,但是存在相同的问题...

请帮助:D

1 个答案:

答案 0 :(得分:1)

基于上面的尝试,您需要一个Worksheet对象才能使用.Cells。见下文:

For i = 1 To 4
    For j = 1 To 100
        If Sheets("mySheet").Cells(j, 1).Value = arr(i, 1) Then
            Sheets("mySheet").Cells(j, 11).Value = arr(i, 2)
        End If
    Next j
Next i

如果您仍然遇到subscript out of range,请查看数组尺寸,因为可能需要声明它以考虑arr(4,1)arr(4,2)

此处有关.Cells属性的更多信息:

https://docs.microsoft.com/en-us/office/vba/api/excel.range.cells