我有一个36K行的电子表格。每条36K线将匹配约350个数字中的一个。当该数字匹配时,我将文本和冒号输入到与匹配数字相同的行中的另一列。我的问题是:
这一次适用于一行,但我不想为每一行执行此操作。我意识到我必须为350个不同的数字中的每一个设置值。
Sub CategoryChanger()
Select Case Range("AS2").Value
Case 1492
Range("T2") = "IT DOES NOT WORKS"
Case 1491
Range("T2") = "IT WORKS"
End Select
End Sub
提前致谢。
答案 0 :(得分:2)
使用For Each ... Next
语句进行基本循环迭代:
Sub CategoryChanger()
Dim rng as Range
Dim r as Range
Dim result as String
'## Define a range to represent the cells over which you would like to iterate:
'## Modify as needed...
Set rng = Range("AS2:AS100")
'## Iterate each cell in the Range defined "rng"
For Each r in rng.Cells
Select Case r.Value
Case 1492
result = "IT DOES NOT WORKS"
Case 1491
result = "IT WORKS"
End Select
'## Print result in the cell 10 columns to right
'## Modify as needed
r.Offset(0, 10).Value = result
Next
End Sub
使用350多个值来检查30,000行数据,您可以更好地将其作为另一个(隐藏)工作表上的表进行索引,并使用WorksheetFunction.VLookup
进行查找,而不是强制执行查找表壳开关是这样的。
在这种情况下,您将完全省略Select Case
块,并且只是这样做(假设您添加名为“Lookup”的工作表并将查找表放在A1范围内:B350):
Sub CategoryChanger()
Dim rng as Range
Dim r as Range
Dim result as String
'## Define a range to represent the cells over which you would like to iterate:
'## Modify as needed...
Set rng = Range("AS2:AS100")
'## Iterate each cell in the Range defined "rng"
For Each r in rng.Cells
On Error Resume Next
result = Application.WorksheetFunction.VLookup(r.Value, Worksheets("Lookup").Range("A1:B350"), 2, False)
If Err.Number <> 0 Then result = "NOT FOUND!"
On Error GoTo 0
'## Print result in the cell 10 columns to right
'## Modify as needed
rng.Offset(0, 10).Value = result
'Clear out the "result" value for the next iteration:
result = vbNullstring
Next
End Sub
我不确定哪种方法会针对此用途进行优化。