[英]Select CASE / CASE over range of cells
我有一个包含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
提前谢谢。
使用For Each ... Next
基本循环迭代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
进行查找,而不是像这样通过Case开关来强制查找。
在那种情况下,您将完全省略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
我不确定会为此用途进行优化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.