2014-09-25 73 views
1

我有3個If語句,無論「dept」的值如何,總是會導致錯誤。
如果我刪除兩個If語句,只剩下一個,它就可以工作。我究竟做錯了什麼?多個VBA如果或者陳述

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 
+0

我已經編程了20年以上,剛剛從你那裏學到了一些新的東西'Application.WorksheetFunction.VLookup(...'。不知道內置的公式函數是可用的像那謝謝! – DarrenMB 2014-09-25 15:08:31

回答

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 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 
+0

謝謝你,現在都在工作。 – Bobby 2014-09-26 14:13:29

0

我認爲Dept是一個字符串變量。

然後代碼應該是這樣的:

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

VBA interprtates你的布爾條件爲 (Dept = "Dept1") or CBool("Dept2") VBA propably有困難時期你的字符串轉換成一個布爾值。

0

你嘗試加入

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

也許因爲還是部門,它始終是真實的。所有的中頻條件得到執行