如何创建具有多个OR条件的if语句?



基本上,在我的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个字符,因此使用

然后,对于紧凑的代码使用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

最新更新