我在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
答案 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