dave
dave

Reputation: 59

Vba: case within if statement

I do not know want i'm doing wrong. In column H there a values like Bank, Chair Table. If in the column is table then i want to run a case, the case of column C. In case in column C is value 10 or 20 this has the be copied to column F. In case else the row has to get a color. Now every r column C with values <> 10, 20 get a message, also if there is in column H Chair or other

What is wrong in the code?

Dim i As Long

For i = 2 To Worksheets("Read DBF").Range("I" & Rows.Count).End(3).Row
    If Worksheets("Read DBF").Cells(i, "I") = "OLN" Then
      Select Case Worksheets("Read DBF").Cells(i, "C")
          Case 10, 20, 30
              Worksheets("Read DBF").Cells(i, "F") = Worksheets("Read DBF").Cells(i, "C")
          Case Else
              MsgBox "Wrong number"
       End Select
    End If
Next i
Sheet1.Activate
End Sub

Upvotes: 1

Views: 659

Answers (1)

user4039065
user4039065

Reputation:

I strongly suspect that the 10, 20, 30 values may be text masquerading as numbers. 10 is NOT the same thing as "10" . Check their default cell alignment. Text is left-aligned and numbers/dates are right-aligned. You can test for both.

Dim i As Long

With Worksheets("Read DBF")
    For i = 2 To .Range("I" & Rows.Count).End(3).Row
        If UCase(.Cells(i, "I").Value) = "OLN" Then
            Select Case LCase(.Cells(i, "H").Value2)
                Case "bank"
                    'do something for 'bank'
                Case "chair"
                    'do something for 'chair'
                Case "table"
                   Select Case .Cells(i, "C").Value2
                       Case 10, 20, 30, "10", "20", "30"
                           .Cells(i, "F") = .Cells(i, "C").Value2
                       Case Else
                           .Cells(i, 1).Resize(1, 26).Interior.Color = vbRed
                           MsgBox "Wrong number"
                    End Select
                Case Else
                    'not 'bank', 'chair' or 'table'
            End Select
        End If
    Next i
End With

I've nested a second Select Case statement into conditions where column H is 'table'. There are placeholders for 'bank' and 'chair'.

I've also added a With ... End With statement to make your code a little more readable.

Upvotes: 2

Related Questions