Excel - 选择具有多个条件的案例

时间:2016-12-14 16:46:40

标签: excel vba excel-vba

下面的代码是我的完整Sub的摘录,因为它在这里更容易阅读。我需要为一些案例添加更多标准,我不确定如何实现它。

总结一下这是做什么的,如果列K有一个以B,M或D开头的单词,它会运行一组案例。如果列K有一个以A开头的单词,则它会运行一组不同的情况。再次,这是有效的。但在某些情况下,我需要它有更多的标准,而不是只看O列。

例如,在第一种情况下,它需要检查“伊利诺伊大学”和“UofI”,但它还需要检查P列中“Urbana”和“Chicago”的值。我怎么能这样做?

Sub Test4()
    Dim LastRow As Long
    Dim i As Long
    LastRow = Range("O" & Rows.Count).End(xlUp).Row
    For i = 84 To LastRow
        If Range("K" & i) Like "B*" Or Range("K" & i) Like "M*" Or Range("K" & i) Like "D*" Then
            Select Case Range("O" & i)
                Case "University of Illinois", "UofI"
                    Range("N" & i) = "1234"
            End Select
        End If
        If Range("K" & i) Like "A*" Then
            Select Case Range("O" & i)
                Case "New York University", "NYU"
                    Range("N" & i) = "5075"
            End Select
        End If
    Next i
End Sub

3 个答案:

答案 0 :(得分:3)

在正常情况下,Select Case语句不适用于Like运算符。但是,有一种解决方法。

为了Select Case使用Like,我们会添加True表达式。

<强>代码

Sub Test4()

    Dim LastRow As Long
    Dim i As Long

    LastRow = Range("O" & Rows.Count).End(xlUp).Row
    For i = 84 To LastRow

        Dim wordStr
        wordStr = Range("K" & i)

        ' adding True to enter the below Case with Like
        Select Case True
            Case wordStr Like "B*", wordStr Like "M*", wordStr Like "D*"
                Select Case Range("O" & i)
                    Case "University of Illinois", "UofI"
                        Range("N" & i) = "1234"

                End Select

            Case wordStr Like "A*"
                Select Case Range("O" & i)
                    Case "New York University", "NYU"
                        Range("N" & i) = "5075"

                End Select

        End Select
    Next i

End Sub

答案 1 :(得分:2)

Select Case Range("O" & i)
    Case "University of Illinois", "UofI"
        Select Case Range("P" & i")
            Case "Urbana", "Chicago"
                Range("N" & i) = "1234"
        End Select
End Select

这样就够了吗?没有经过测试,请反馈,以便我们为您提供解决方案

答案 2 :(得分:0)

因为你需要抓住“以”开头的单词,你可以这样做

Sub Test4()
    Dim LastRow As Long, i As Long

    LastRow = Range("O" & Rows.count).End(xlUp).row
    For i = 84 To LastRow
        Select Case Left(Range("K" & i).Value, 1)
            Case "B", "M", "D"
                Select Case Range("O" & i).Value
                    Case "University of Illinois", "UofI"
                        Range("N" & i) = "1234"
                End Select
            Case "A"
                Select Case Range("O" & i).Value
                    Case "New York University", "NYU"
                        Range("N" & i) = "5075"
                End Select
        End Select
    Next i
End Sub