2

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.

3 Answers 3

3

Your IF statements as written all need to have ELSE IF for the second IF statement on, followed by an END IF statement at the end of your grouping.

You can certainly do a CASE statement, as follows:

Sub AddGroupColumn()
   'Counts number of rows in sheet. Loops through rows.
   For i = 1 To Range("C1048576").End(xlUp).Row
       Select Case Range("C2:C" & i).Value
           Case "john.doe"
                Range("D2:D" & i).Value = "group 1"
           Case "jane.doe"
                Range("D2:D" & i).Value = "group 2"
           ' The rest of your case statements go here ...
       End Select
    Next i 
End Sub
7
  • Looks good but for the line reading "Case "john.doe", I get a type mismatch error (13).
    – AME
    Aug 6, 2012 at 18:30
  • What does Range("C2:C" & i).Value evaluate to for that line? Aug 6, 2012 at 18:38
  • I'm not sure how to tell. Column C just has text values.
    – AME
    Aug 6, 2012 at 18:46
  • You can put a break point on that line, and when you hit that line, in the immediate window, enter ?Range("C2:C" & i).Value to see what the value is. Aug 6, 2012 at 18:47
  • 1
    Range("C2:C" & i) where "i" is anything but 2 will return an array. That's why you're getting the type mismatch. Aug 6, 2012 at 19:18
2

You might put the names and groups into arrays.

Sub AddGroupColumn()

    Dim rCell As Range
    Dim rRng As Range
    Dim vaNames As Variant
    Dim vaGroups As Variant
    Dim lMatch As Long

    vaNames = Array("john.doe", "jane.doe", "james.doe", "jenn.doe")
    vaGroups = Array("group 1", "group 2", "group 3", "group 4")

    With Sheet1
        Set rRng = .Range("C1", .Cells(.Rows.Count, 3).End(xlUp))
    End With

    For Each rCell In rRng.Cells
        lMatch = Application.WorksheetFunction.Match(rCell.Value, vaNames, False)
        rCell.Offset(0, 1).Value = vaGroups(lMatch - 1)
    Next rCell

End Sub

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

For Each rCell In rRng.Cells
    On Error Resume Next
        lMatch = Application.WorksheetFunction.Match(rCell.Value, vaNames, False)
    On Error GoTo 0

    If lMatch - 1 > LBound(vaGroups) Then
        rCell.Offset(0, 1).Value = vaGroups(lMatch - 1)
    Else
        rCell.Offset(0, 1).Value = "No group"
    End If
Next rCell
7
  • Thanks, I like that you're using the match function in Excel. However, this line 'Set rRng = .Range("C1", .Cells(.Rows.Count, 3).End(xlUp))' returns error '424' Object Required, when I run this code.
    – AME
    Aug 6, 2012 at 19:36
  • Forgot about WorksheetFunction.Match which is basically what I'm doing with my inner For loop. +1
    – JimmyPena
    Aug 6, 2012 at 19:36
  • The Sheet1 reference may be causing you problems. You can use With ActiveSheet or With ThisWorkbook.Worksheets("Sheet1"). You just need a sheet reference that exists. Aug 6, 2012 at 20:15
  • Ok, I referenced ActiveSheet. However, the 'lmatch' line returns another error: "Unable ot get the Match property of the WorsheetFunction class".
    – AME
    Aug 6, 2012 at 20:27
  • 1
    By default, the Array function returns a zero based array, but the Match function returns the position starting with 1. So I have to subtract 1 to get the right match. If you have Option Base 1 at the top of your module, then Array will be 1 based and no subtraction is necessary. Aug 7, 2012 at 16:00
1

You can do all of this using arrays, no need for If or Select Case statements. This avoids having to write each value one at a time to the worksheet.

Tested and works using your sample input (assumes single column of input data):

Sub AddGroupColumn()

Dim inputRange As Excel.Range
Dim inputData As Variant
Dim outputData As Variant
Dim i As Long, j As Long
Dim nameslist As Variant
Dim groupslist As Variant

' **** EDIT THESE AS NEEDED, however they MUST correspond
Const NAMES_LIST As String = "john.doe,jane.doe,james.doe,jenn.doe"
Const GROUPS_LIST As String = "group 1,group 2,group 3,group 4"

' create arrays of names and groups
nameslist = Split(NAMES_LIST, ",")
groupslist = Split(GROUPS_LIST, ",")

' define input range
Set inputRange = Range("C2:C" & Range("C" & Rows.Count).End(xlUp).row)

' read column C values into array
inputData = inputRange.value
' resize output array to match input array
ReDim outputData(LBound(inputData) To UBound(inputData), 1 To 1)

' evaluate input array, output to another array
For i = LBound(inputData) To UBound(inputData)
  For j = LBound(nameslist) To UBound(nameslist)
    If inputData(i, 1) = nameslist(j) Then ' given input value is matched on the names list
      outputData(i, 1) = groupslist(j) ' output array is the corresponding group name
      Exit For ' exit loop since we found what we need in this loop
    End If
  Next j
Next i

  ' write output data to output range
  inputRange.Offset(, 1).value = outputData

End Sub

This procedure will scale when you apply it to your actual data. Just edit the two constants, making sure that their values correspond.

By using Rows.Count it will always grab the correct range regardless of the Excel version. The arrays will resize themselves no matter how much data you have. The only assumption it makes is that your input data is in one column.

Also note that we only touch the worksheet three times: once to define the input range, once to grab the values in column C, and once to write back the calculated values to column D.

Sample Input

sample input

After running code

sample output

2
  • I like this approach, but for some reason, this code deletes the entire 'name' column and doesn't return groups. It is not working in my spreadsheet.
    – AME
    Aug 6, 2012 at 19:28
  • Step through the code and make sure you copied the entire procedure. I tested it in Excel 2003. I assume you are using Excel 2007+ because you have 100k+ rows. Also see the commentary at the bottom of Dick's answer and see if that applies to you.
    – JimmyPena
    Aug 6, 2012 at 19:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.