我正在尝试创建一个宏,使某人能够输入文件名,然后输入将选择特定发行列表的电子邮件列表编号。我在网上结合了很多不同的代码来创建它。如果我只是在“.to =”中发送电子邮件,它就能正常工作。但我想基于哪个列表#该人员想要发送工作簿来实现if语句。当我运行宏时,它不会发送任何东西,我假设我的if语句不能正常工作。有什么建议?
Sub Mail_workbook_Test()
Dim OutApp As Object
Dim OutMail As Object
Dim Date1 As Date
Date1 = Format(Now, "yyyy-mm-dd")
'Date and format
Filename = Application.InputBox("Enter File Name:", "Input Box Text", "File Name")
'Type in File Name
List = Application.InputBox("Enter Email List:", "Input Box Text", "List#")
'Type in Email List
If List = "List1" Then
emailaddress = "email3@provider.com; email4@provider.com"
ElseIf List = "List2" Then
emailaddress = "email@provider.com; email2@provider.com"
End If
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.to = emailaddress
.CC = ""
.BCC = ""
.Subject = "" + Filename + "" & " " & Date1
.Body = "Hi Everyone," & Chr(10) & Chr(10) & "Please let me know if you get this!" & Chr(10) & Chr(10) & "Thanks!"""
.Attachments.Add ("C:\Users\Desktop\" + Filename + ".xlsx")
.Send 'or use .Display
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
答案 0 :(得分:1)
我无法测试,因为我的家用机器上没有Outlook,但是如果您怀疑它是 If 例程,那么它会失败,那么我建议添加一个额外的声明来捕获用户输入不好。这是完整的 If 语句,带有额外的最终'Else'(意思是“如果以前的条件都没有达到,那么就这样做”):
If List = "List1" Then
emailaddress = "email3@provider.com; email4@provider.com"
ElseIf List = "List2" Then
emailaddress = "email@provider.com; email2@provider.com"
Else
MsgBox "Sorry, your list selection was not recognised."
Exit Sub
End If
这样可以保证您的'emailaddress'变量设置正确,或者您收到有用的错误消息。希望这是一些帮助。
答案 1 :(得分:1)
我会在你的代码中评论但不正确的一些管家项目:
On Error Resume Next
,这可能会阻止您查看可能是失败根本原因的错误情况。 FileDialog
而不是输入框来选择文件。这减轻了输入框中(非常可能)用户错误的可能性。我相信,但未经测试,.To
属性处理displayname,根据文档情况就是这样:
此属性仅包含显示名称。 To属性对应于MAPI属性PidTagDisplayTo。应使用Recipients集合来修改此属性。
所以你可以试试这个:
Dim recipient as Variant
With OutMail
For each recipient in Split(emailaddress, ";")
.Recipients.Add Trim(recipient)
Next
.CC = ""
.BCC = ""
.Subject = "" + Filename + "" & " " & Date1
.Body = "Hi Everyone," & Chr(10) & Chr(10) & "Please let me know if you get this!" & Chr(10) & Chr(10) & "Thanks!"""
.Attachments.Add ("C:\Users\Desktop\" + Filename + ".xlsx")
.Send 'or use .Display
End With