我是vba的新手,正在开发一个可以自动重新排列电子表格的项目。在众多步骤中的一个步骤中,我循环遍历单元格以进行匹配和填充。它有效,但有效率问题。
**更具体的**
谢谢大家这么快回复我。我还想在循环中放入一个if语句。这是我最终想要实现的目标:
sheet1
C1 C2 C3
R1
R2
R3
sheet2
Row Col Ind
R1 C1 b
R1 C2 a
R1 C3 b
R2 C1 b
R2 C2 a
R2 C3 b
R3 C1 b
R3 C2 a
R3 C3 b
我写的代码:
Sub test()
Dim field As Range, crit1 As Range, crit_search1 As Range, crit2 As Range, crit_search2 As Range, ind As Range
Dim i As Integer, j As Integer, m As Integer
Set field = Sheets("Sheet1").Cells(i, j)
Set crit1 = Sheets("sheet1").Cells(i + 1, 1)
Set crit_search1 = Sheets("sheet2").Cells(m + 1, 1)
Set crit2 = Sheets("sheet1").Cells(1, j + 1)
Set crit_search2 = Sheets("sheet2").Cells(m + 1, 2)
Set ind = Sheets("sheet2").Cells(m + 1, 3)
For i = 1 To 3
For j = 1 To 3
For m = 1 To 9
If crit1 = crit_search1 And crit2 = crit_search2 Then
field = ind
Next
Next
End Sub
而且,我想得到的结果:
Sheet1
C1 C2 C3
R1 b a b
R2 b a b
R3 b a b
基本上,我通过匹配Row和Col标准来填充2D矩阵。
如果有更好的解决方案,请随时删除我的代码。谢谢大家!
答案 0 :(得分:0)
这里完全不需要循环。您可以设置范围内每个单元格的值,只需说Range.Value = [value]
作为示例:
Sub test()
Dim field As Range
Dim i As Integer, j As Integer
Set field = Sheets("Sheet1").Range(Cells(1,1), Cells(i, j))
field.value = "a"
End Sub
这会将A1中的每个单元格设置为i
和j
对应的任何单元格,而不是任何循环。
答案 1 :(得分:0)
在您发布的示例中,您将field
设置为固定范围 - 或者至少它会因为您尝试引用Cells(0,0)
而没有错误... / p>
如果你想对阵列进行操作,那么就像这样:
Sub test()
Dim arr
Dim i As Long, j As Long
'fill array from sheet
arr = Sheets("Sheet1").Cells(1,1).resize(100,100)
'modify array
For i = 1 To 100
For j = 1 To 100
arr(i,j) = "R" & i & ":C" & j
Next
Next
'put array back on sheet
Sheets("Sheet1").Cells(1,1).Resize(100,100).Value = arr
End Sub
答案 2 :(得分:0)