VBA 中的双 For 循环,不同的下标
Double For loops in VBA, different subscripts
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
但当然显示"subscript out of range",我也用For Each试过,但同样的问题...
请帮忙:D
根据您上面的尝试,您需要一个 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
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
但当然显示"subscript out of range",我也用For Each试过,但同样的问题...
请帮忙:D
根据您上面的尝试,您需要一个 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