簡體   English   中英

如何創建具有多個 OR 條件的 if 語句?

[英]How to create a if statement with multiple OR conditions?

基本上在我的 if 語句中,我首先需要查看字符串是否為 7 個字符,以及該單元格中的第 7 個字符是否是“A、J、S、T、N、V”中的一個字符。

這就是我到目前為止所擁有的(我知道它不起作用,但我不確定如何實現這些多個“OR”

If Len(Cells(i, 7).Value) = 7 And Left(Cells(i, 7), 1) = "A" Or "J" Or "S" Or "T" Or "N" Or "V" Then
                    Cells(i, 29).Value = "Client and Account fields switched"
Else
Else If

先感謝您! 我是新人哈哈

你需要測試每一個:

If Len(Cells(i, 7).Value) = 7 And _
    (Left(Cells(i, 7), 1) = "A" Or _
     Left(Cells(i, 7), 1) = "J" Or _
     Left(Cells(i, 7), 1) =  "S" Or _
     Left(Cells(i, 7), 1) =  "T" Or _
     Left(Cells(i, 7), 1) =  "N" Or _
     Left(Cells(i, 7), 1) =  "V") Then
                Cells(i, 29).Value = "Client and Account fields switched"
Else If

首先,您要求第 7 個字符,因此使用Right

然后,使用InStr編寫緊湊的代碼:

If Len(Cells(i, 7).Value) = 7 And InStr(1, "AJSTNV", Right(Cells(i, 7), 1), vbtextcompare) > 0 Then
    Cells(i, 29).Value = "Client and Account fields switched"
Else
Else If

或者,我更喜歡簡單且可維護的方法:

If Len(Cells(i, 7).Value) = 7 Then
    Select Case Right(Cells(i, 7), 1)
        Case "A", "J", "S", "T", "N", "V"
            Cells(i, 29).Value = "Client and Account fields switched"
    End Select
End If

Application.Match

  • 請注意,此選項不區分大小寫,即A=a

編碼

Option Explicit

Sub testMatch()
    If Len(Cells(i, 7).Value) = 7 Then
        If IsNumeric(Application.Match(Right(Cells(i, 7), 1), _
                Array("A", "J", "S", "T", "N", "V"), 0)) Then
            Cells(i, 29).Value = "Client and Account fields switched"
        Else
        End If
    Else
    End If
End Sub

通過實現變量,前一個可以變得更具可讀性:

Sub testMatchReadable()
    Const LettersList As String = "A,J,S,T,N,V"

    Dim Letters() As String: Letters = Split(LettersList, ",")
    Dim cValue As Variant: cValue = Cells(i, 7).Value

    Dim cMatch As Variant

    If Not IsError(cValue) Then
        If Len(cValue) = 7 Then
            cMatch = Application.Match(Right(cValue, 1), Letters, 0)
            If IsNumeric(cMatch) Then
                Cells(i, 29).Value = "Client and Account fields switched"
            Else
            End If
        Else
        End If
    End If

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM