如果那么声明,VBA,循环

时间:2015-02-09 17:03:34

标签: vba loops if-statement

以下是我想要完成的一个例子是Excel。

食品集团/食品               / 苹果               / 香蕉               / 胡萝卜               /西兰花

我正在写一个If Then Statement来尝试将Foods与他们的小组进行匹配。

(我知道Access会更容易,但我不想继续从Excel复制和粘贴到Access并返回。它只会是6个不同的项目)

我编写的If Then编码仅用于完成第一个单元格。但我的循环不起作用。请帮忙

Sub InsertFoodGroup()

    Dim food As String, group As String
    Dim i As Integer

    i = Cells(2, 2).End(xlDown).Row

    food = Range(Cells(2, 2), Cells(i, 2)).Value

        Do While Cells(i, 2).Value <> ""
            If food = "Apple" Then
                group = "Fruit"
            ElseIf food = "Banana" Then
                group = "Fruit"
            ElseIf food = "Carrot" Then
                group = "Vegetable"
            ElseIf food = "Broccoli" Then
                group = "Vegetable"
            Else
                total = "false"
            End If
            i = i + 1
        Loop

    Range(Cells(2, 21), Cells(i, 21)).Value = group

End Sub

1 个答案:

答案 0 :(得分:1)

我建议使用一个非常简单的UDF:

Public Function foodToGroup(ByVal food As String) As Variant
    Select Case food
        Case "Apple", "Banana":
        foodToGroup = "Fruit"
        Case "Carrot", "Broccoli":
        foodToGroup = "Vegetable"
        Case Else
        foodToGroup = False
    End Select
End Function

因此,假设您的数据位于“A1:A100”中,您只需要在单元格“B1”(或您需要的任何位置)中键入=foodToGroup(A1),然后将该功能向下拖动直至结束数据

请注意,可以通过简单的Excel公式轻松达到此目的:=IF(OR(A1="Banana",A1="Apple"),"Fruit",IF(OR(A1="Carrot",A1="Broccoli"),"Vegetable",FALSE))