[英]Select CASE / CASE over range of cells
I have a spreadsheet with 36K lines. 我有一个包含36K行的电子表格。 Each of the 36K lines will be matched to one of about 350 numbers.
每条36K线将与大约350个数字之一匹配。 When that number is matched, I will have text and colons input into another column on the same row as the matching number.
匹配该数字后,我将在与该匹配数字相同的另一行中输入文本和冒号。 The questions I have are:
我的问题是:
This works for one row at a time, but I don't want to have to do this for each row. 一次只能工作一行,但是我不想为每一行都这样做。 I realize I will have to put values for each of the 350 different numbers.
我意识到我将必须为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
Thanks ahead of time. 提前谢谢。
Basic loop iteration using For Each ... Next
statement: 使用
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
With 350+ values to check against 30,000 rows of data, you may be better served to index this as a table on another (hidden) worksheet and use the WorksheetFunction.VLookup
to do the lookup, rather than forcing through a Case switch like this. 使用350个以上的值来检查30,000行数据,可以更好地将其作为另一个(隐藏)工作表上的表进行索引,并使用
WorksheetFunction.VLookup
进行查找,而不是像这样通过Case开关来强制查找。
In that case you would omit the Select Case
block altogether, and simply do like so (assuming you add a worksheet named "Lookup" and put your lookup table in range A1:B350): 在那种情况下,您将完全省略
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
I am not sure which would be optimized for this use. 我不确定会为此用途进行优化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.