多个VBA If Or语句

时间:2014-09-25 14:15:52

标签: excel vba excel-vba

无论“dept”的值如何,我都有3个if语句总是导致为真 如果我删除两个If语句,只留下一个它可以工作。我做错了什么?

Dim Dept As String
Dim wb As Workbook

Set wb = ThisWorkbook


Dept = Application.WorksheetFunction.VLookup(Name, Sheet1.Range("F10"), 1)

If Dept = "Dept1" Or "Dept2" Then
wb.SendMail "email address", Subject:="Subject heading 1"

End If

If Dept = "Dept3" Or "Dept4" Then
wb.SendMail "email address", Subject:="Subject heading 2"

End If

If Dept = "Dept5" Or "Dept6" Then
wb.SendMail "email address", Subject:="Subject heading 3"

End If

3 个答案:

答案 0 :(得分:2)

你不能在这里使用或喜欢它。你必须重复变量:

If Dept = "Dept1" Or Dept = "Dept2" Then
wb.SendMail "email address", Subject:="Subject heading 1"

End If

If Dept = "Dept3" Or Dept = "Dept4" Then
wb.SendMail "email address", Subject:="Subject heading 2"

End If

If Dept = "Dept5" Or Dept = "Dept6" Then
wb.SendMail "email address", Subject:="Subject heading 3"

End If

或者你可以使用Select Case:

Select Case Dept
  case "Dept1", "Dept2"
wb.SendMail "email address", Subject:="Subject heading 1"
case "Dept3", "Dept4"
wb.SendMail "email address", Subject:="Subject heading 2"
case "Dept5", "Dept6"
wb.SendMail "email address", Subject:="Subject heading 3"

End Select

答案 1 :(得分:0)

我认为Dept是一个String变量。

然后代码应该如下:

If Dept = "Dept1" Or Dept = "Dept2" Then
   wb.SendMail "email address", Subject:="Subject heading 1"
End If

VBA将您的布尔条件插入 (Dept = "Dept1") or CBool("Dept2") VBA可能很难将您的String转换为布尔值。

答案 2 :(得分:0)

您是否尝试添加



If Dept = "Dept1" Or Dept = "Dept2" Then




可能自从Or就是Dept,它总是如此。所有IF条件都被执行