IF语句-在一个范围内找到多个字符串

时间:2019-07-03 05:14:45

标签: excel vba

如果.text为“ A”,“ B”和Or(“ A”,“ B”),我试图编写一个if语句来针对3种情况做一些动作。 当范围同时包含“ A”和“ B”时,我遇到了问题,我只想知道在我正在查找的范围内找到两个字符串的最佳方法是什么。

ElseIf Master.Range("V13:V18").Text Like "A" Or Master.Range("V13:V18").Text Like "B" Then

*为了在3种情况下保持清晰而编辑了数据集

case 1    case 2    case 3
1 A        1 B       1 A
2 A        2 B       2 A
3 A        3 B       3 A
4 A        4 B       4 B
5 A        5 B       5 A
6 A        6 B       6 B

这是我编写的代码的一部分。

If Master.Range("V13:V18").Text Like "A" Then
do something..
ElseIf Master.Range("V13:V18").Text Like "B" Then
do something..
ElseIf Master.Range("V13:V18").Text Like "A" Or Master.Range("V13:V18").Text Like "B" Then
do something..

2 个答案:

答案 0 :(得分:0)

尝试一下:

Sub Test()

Dim A As Long, B As Long
With ThisWorkbook.Sheets("Master")
    A = Application.WorksheetFunction.CountIf(.Range("V13:V18"), "A")
    B = Application.WorksheetFunction.CountIf(.Range("V13:V18"), "B")
    If A = .Range("V13:V18").Cells.Count Then
        MsgBox "All A"
    ElseIf B = .Range("V13:V18").Cells.Count Then
        MsgBox "All B"
    ElseIf A + B = .Range("V13:V18").Cells.Count Then
        MsgBox "Both A and B"
    Else
        MsgBox "Other values too"
    End If
End With

End Sub

答案 1 :(得分:-1)

使用此代码:

If Master.Range("V13:V18").Find("B") Is Nothing Then

    a = "A"
    '''Do Something ...all cells have "A"

ElseIf Master.Range("V13:V18").Find("A") Is Nothing Then

    a = "B"
    '''Do Something ...all cells have "B"

Else: a = "AB" '''Do Something ...all cells have "A or B"


End If

MsgBox a

Msgbox会向您显示3种情况下的正确情况。