How can I create a case statement (or multiple if statements) within a loop in VBA?
In this example, I have a list of 4 names that correspond to 4 different groups. The names are in column ‘C’ of a spreadsheet and I would like to create a new column, column ‘D’, where each individual’s group name is listed.
Here is the code I am working with at the moment:
Sub AddGroupColumn()
'Counts number of rows in sheet. Loops through rows.
For i = 1 To Range("C1048576").End(xlUp).Row
If Range("C2:C" & i).Value = "john.doe" Then
Set Range("D2:D" & i).Value = "group 1"
If Range("C2:C" & i).Value = "jane.doe" Then
Range("D2:D" & i).Value = "group 2"
If Range("C2:C" & i).Value = "james.doe" Then
Range("D2:D" & i).Value = "group 3"
If Range("C2:C" & i).Value = "jenn.doe" Then
Range("D2:D" & i).Value = "group 4"
Next i
End Sub
Please provide suggestion on how I can fix the code above. I know the syntax is off and I’m not sure if I should use a ‘Case’ statement of ‘If/Then/Else/Elseif’. Here is the error that I am currently receiving:
Compile Error: Next without For
Also, please advise if there is a more efficient way to solve this problem. In the real case, there are 12 names, 12 groups and 100,000 rows of names.
You might put the names and groups into arrays.
Note that in your example, you don’t specify which sheet the ranges apply to. These are called unqualified range references and can cause some unexpected behavior. If your code is in a standard module, unqualified ranges refer to the ActiveSheet. If your code is in a sheet class module, unqualified ranges refer to that sheet.
If some of the names in column C don’t have a group, you have to change the loop to account for that. Like this