我正在创建VBA代码,以在单击“提交”按钮时发送电子邮件。我有2个条件,例如:在A
列中,它将过滤包含"AD"
的数据并将其发送给收件人A。在G
列中,如果数据包含"13"
或"14"
它将被过滤并发送给收件人B。我已经有了第一个条件,但是我不知道如何添加第二个条件。否则不起作用。
Sub BSPProfitCenter_Rectangle3_Click()
Const cFirst As Integer = 20
Const cLast As Integer = 65
Const cRequest As String = "New Request"
Dim i As Integer
For i = cFirst To cLast
If Range("A" & i).Value = cRequest Then
If Range("e" & i).Value = "" Then
MsgBox "Provide the PC name from KE53"
Exit Sub
ElseIf Range("g" & i).Value = "" Then
MsgBox "Please provide the user responsible (Sector) maintained in KE53 for this PC"
Exit Sub
ElseIf Range("K" & i).Value = "" Then
MsgBox "Provide the company code where the PC needs to be extended"
Exit Sub
End If
End If
Next i
ActiveSheet.Unprotect Password:="PROFITCENTER"
Selection.AutoFilter
ActiveSheet.Range("$B$19:$L$65").AutoFilter Field:=1, Criteria1:="=AD*", Operator:=xlAnd
ActiveSheet.SaveAs Filename:="C:\Apps\" & "GSAP Asset Domain PC Request" & Format(Now(), "DD-MM-YYYY")
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.to = "A"
.CC = ""
.BCC = ""
.Subject = "AD Request"
.Attachments.Add ActiveWorkbook.FullName
.Display
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
Exit Sub
'here's the supposed to be additional validation'
If Range("s" & i).Value <> "AD" Then
If Range("G" & i).Value = "13" Or Range("G" & i).Value = "14" Then
ActiveSheet.Unprotect Password:="PROFITCENTER"
Selection.AutoFilter
ActiveSheet.Range("$B$19:$L$65").AutoFilter Field:=6, Criteria1:="=13", _
Operator:=xlOr, Criteria2:="=14"
ActiveSheet.SaveAs Filename:="C:\Apps\" & "GSAP PC Request" & Format(Now(), "DD-MM-YYYY")
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.to = "B"
.CC = ""
.BCC = ""
.Subject = "13 & 14 Request"
.Attachments.Add ActiveWorkbook.FullName
.Display
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End If
End If
End Sub
我希望在一个提交按钮中有2个条件,但是第二个代码不起作用。
答案 0 :(得分:0)
首先,您说:
在A列中,它将过滤包含“ AD”的数据
在编写代码时:
If Range("s" & i).Value <> "AD"
指示了列S
,而不是A
-请注意这一点。
您的If
错误是因为它看起来像这样:
If Range("s" & i).Value <> "AD" Then
If Range("G" & i).Value = "13" Or Range("G" & i).Value = "14" Then
' do all logic here
End If
End If
这也可以改写为:
If Range("s" & i).Value <> "AD" And (Range("G" & i).Value = "13" Or Range("G" & i).Value = "14") Then
' do all logic here
End If
这些条件之间没有任何分隔,您要分别对待。
它应该写为:
If Range("s" & i).Value <> "AD" Then
' send mail to recipient A
End If
If Range("G" & i).Value = "13" Or Range("G" & i).Value = "14" Then
' send mail to recipient B
End If