1

I am working on a simple Select Case in Excel 2013. I want the value in column R to be based on the value in column Q. But I get a type mismatch error. This is a shortened version of cases since, there are actually 20, but here is what I'm using to test (the following presents the type mismatch error):

Sub laranges()
Select Case Range("Q:Q").Value
    Case 0 To 0.49
    Range("R:R").Value= "Low"
    Case 0.5 To 0.99
    Range("R:R").Value= "Medium"
    Case Else
    Range("R:R").Value = "High"
End Select

End Sub

The following works if I change it to select only one cell (I have tested it on several cells and they were all successful individually):

Sub laranges()
Select Case Range("Q2").Value
    Case 0 To 0.49
    Range("R2").Value = "Low"
    Case 0.5 To 0.99
    Range("R2").Value = "Medium"
    Case Else
    Range("R2").Value = "High"
End Select

End Sub

Obviously I'm not referencing the ranges correctly. I have also tried changing the range to Q2:Q3 and R2:R3, but I get the same error. But if I reference Q2 and Q3 individually they run successfully.

How can I properly reference the ranges? I have looked at Ozgrid, MSDN, as well as several threads on SO but I just haven't been successful.

user1916528
  • 379
  • 4
  • 23

2 Answers2

3

You need to iterate on the range

Sub laranges()
Dim sResult As String
For Each oCell In Range("Q:Q")
    Select oCell.Value
        Case 0 To 0.49
            sResult = "Low"
        Case 0.5 To 0.99
            sResult = "Medium"
        Case Else
            sResult = "High"
    End Select

    oCell.Offset(0, 1).Value = sResult
Next oCell

Putting this type of logic in the s/s itself would be much more efficient.

yk11
  • 768
  • 4
  • 9
1

you could try this "formula" approach

Sub main()
' for "Choose" function clever use, see tobriand's answer in http://stackoverflow.com/questions/5488692/case-function-equivalent-in-excel

With ActiveSheet.Range("Q:Q").SpecialCells(xlCellTypeConstants, xlNumbers).Offset(, 1)

    .FormulaR1C1 = "=CHOOSE(   1   +   LOG(1 + (2*AND(RC[-1]>=0,RC[-1]<=0.49) ) + (4*AND(RC[-1]>=0.5,RC[-1]<=0.99)) ,2)," _
                     & "    ""High"" ,                 ""Low"",                          ""Medium"")"
    .Value = .Value

End With

End Sub
user3598756
  • 28,893
  • 4
  • 18
  • 28