excelvbafor-loopselect-case

How do I assign the return value of a case statement to the cell to the right of the current cell in a For loop?


Background

In VBA, you can assign the return value of a Select Case statement to specific cells as shown below:

  1. Add the Select Case structure.

    Select Case score Case Is >= 80 result = "very good" Case Is >= 70 result = "good" Case Is >= 60 result = "sufficient" Case Else result = "insufficient" End Select

Explanation: Excel VBA uses the value of the variable score to test each subsequent Case statement to see if the code under the Case statement should be executed.

  1. Write the value of the variable result to cell B1.

Range("B1").Value = result

This is straightforward to me, however, I am trying to loop through a column of cells to do the same thing with a for loop. The code above does this for one instance. However, I want to do this for each cell and categorize the result in the cell to the right.

Attempted solution

Below is the code I used so far:

....variables defined at the beginning as strings
Set MyRange = Sheet6.Range("A2:A355")
For each cell In MyRange
    Select Case cell.Value
        Case Is = raid
            result = "area"
        Case Is = fifty
            result = "one"
        ... more cases ad nauseum
    End Select
Next

You can assign a specific cell with the range method approach above. But I want to assign the resulting string one cell to the right (i.e., in column B but the same row). Hence my question...

Question

How do I specify that I want the result of a case statement to be output once cell to the right of the current cell within a For loop in VBA?


Solution

  • You just need:

    cell.Offset(0, 1).Value = result
    

    following your End Select