如何在VBA中使用多案例语句

时间:2019-01-27 06:27:57

标签: excel vba

我有两列,分别是A和B。在A列中,我有Apple,香蕉,Brinjal之类的值,在B列中有“成熟”和“不成熟”的值。在C列中,我要检查它是水果还是蔬菜,然后成熟或未成熟。我想要以下结果。

如何使用多个Case语句?

Please see the below table

Private Sub CommandButton1_Click()
     Dim category As String, result As String
     For i = 2 To 1000
         category = Range("A" & i).Value
         Select Case category
             Case "Apple"
                   result = "Fruit"
             Case "Brinjal"
                   result = "Vegetable"
         End Select
         Range("C" & i).Value = result
     Next
End Sub

2 个答案:

答案 0 :(得分:2)

您可以使用逗号指定值列表:

Private Sub CommandButton1_Click()
    Dim category As String, result As String
    For i = 2 To 1000
        category = Range("A" & i).Value
        Select Case category
            Case "Apple", "Banana", "Orange"
                result = "Fruit"
            Case "Brinjal"
                result = "Vegetable"
            Case else
                result = vbnullstring
            End Select
        Range("C" & i).Value = Range("B" & i).Value & " " & result
    Next i
End Sub

答案 1 :(得分:1)

如果我很好理解...

For i = 1 To 4
    category = Range("A" & i).Value
    Select Case category
        Case "Apple", "Orange", "Banana"
            result = "Fruit"
        Case "Brinjal","xxx"
            result = "Vegetable"
        Case Else
            result = ""
    End Select

    'If th onlys status possibles are ripe and not riped

    Range("C" & i).Value = Range("B" & i).Value & " " & result
Next