I have a spreadsheet with 36K lines. Each of the 36K lines will be matched to one of about 350 numbers. 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.
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:
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.
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):
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.