excelvba

Start a condition with specific text VBA


I have this code that doesn't work properly. For every row in column color its giving "Green" results. Could anyone help me find what's wrong with the code.

Example of the data:
Example

No Fruit Color
1 Mango
2 Apple
3 Tangerine
4 Durian
5 Cherry
6 Mango

    Sub warna()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim rng As Variant
    Dim vl As Range

    Set wb = ThisWorkbook
    Set ws = wb.Sheets("Sheet1")
    Set rng = ws.Range("B2:B" & ws.Cells(ws.Rows.Count, 1).End(xlUp).Row)
    Set vl = ws.Range("B:B")

        For Each vl In rng
            Select Case vl.Formula
                Case "Mango": rng.Offset(0, 1).Formula = "Green"
                Case "Apple": rng.Offset(0, 1).Formula = "Pink"
                Case "Tangerine": rng.Offset(0, 1).Formula = "Orange"
                Case "Cherry": rng.Offset(0, 1).Formula = "Red"
            End Select
        Next vl
    End Sub


Solution

  • The adjustment to your code as suggested in the comment

    ' Set vl = ws.Range("B:B")  <= not needed at all
    
        For Each vl In rng
            Select Case vl.value
                Case "Mango": vl.Offset(0, 1).value = "Green"
                Case "Apple": vl.Offset(0, 1).value = "Pink"
                Case "Tangerine": vl.Offset(0, 1).value = "Orange"
                Case "Cherry": vl.Offset(0, 1).value = "Red"
            End Select
        Next vl
    

    rng.Offset(0, 1).Formula= "Green" will fill all cells in C2:C7 with Green and as the last iteration of the loop meets the condition Case "Mango" it fills the cells with Green.