跟进之前的帖子(发送电子邮件时如何通过 MailItem.SendUsingAccount 设置 Account 对象?),我对该帖子中的一个回复在设置邮件项的属性时使用 SET 而另一个没有使用 SET 感兴趣。这很奇怪!我有一大堆相当复杂的 VBA 代码,
在可用帐户中查找与包含我想要发送的电子邮件地址的唯一部分的字符串匹配的帐户
创建一个新的邮件项目,然后设置用于发送该邮件的帐户。
在我的代码中,SET 语句需要在步骤 1) 中存在,但在步骤 2) 中不需要存在,这相当奇怪(包括 SET 生成 91 个运行时错误)。我认为帐户对象不知何故变成了该帐户的 SMTP 地址的字符串,然后 Outlook 将从该电子邮件地址开始使用所需的帐户。
谢谢。代码的关键部分:
a) 各种声明
Public g_olapp As outlook.Application
Public g_ol_account As outlook.Account
Private olmsg As outlook.MailItem
b) 初始化
Set g_olapp = New outlook.Application
Set g_ol_account = find_account(g_from_email, b_err)
c) 查找帐户函数,这似乎返回一个对象,需要 SET 语句
Private Function find_account(s As String, b As Boolean) As outlook.Account
Dim p_olaccount As outlook.Account
Dim s_send_from As String
s_send_from = UCase(s)
If s_send_from = "" Then
If MsgBox("No account specified, do you want to use the default account <SPJUDGE> ?", Title:=box_title, Buttons:=vbYesNo + vbQuestion) = vbNo Then
b = True
Exit Function
End If
s_send_from = "SPJUDGE"
End If
Set find_account = Nothing
For Each p_olaccount In g_olapp.Session.Accounts
If (Not InStr(UCase(p_olaccount.SmtpAddress), s_send_from) = 0) Then
Set find_account = p_olaccount
s = p_olaccount.SmtpAddress
Exit Function
End If
Next
MsgBox "Account <" & s_send_from & "> not found" _
& String(2, 13) & "Program terminating", Title:=box_title, _
Buttons:=vbOKOnly + vbCritical
b = True
End Function
d) 制作电子邮件项目
Set olmsg = make_new_email(g_olapp, s_email)
e) 另一个创建新电子邮件对象的函数。
Public Function make_new_email(olapp As Object, s As String) As outlook.MailItem
Dim arr() As String
Dim jloc As Integer
Dim jlb As Integer
Dim recip As outlook.Recipient
Set make_new_email = olapp.CreateItem(olMailItem)
' MsgBox g_ol_account note this does work.
With make_new_email
.SendUsingAccount = g_ol_account ' WHY NOT SET IN THIS LINE ??
If gb_set_reply Then
.ReplyRecipients.add (g_reply_to_email)
End If
.OriginatorDeliveryReportRequested = b_askfor_receipts
.ReadReceiptRequested = b_askfor_receipts
End With
s = Replace(s, "SIMON JUDGE", "", , , vbTextCompare)
arr = Split(s, ";") ' changed from comma Nov 2023
jlb = LBound(arr)
For jloc = jlb To UBound(arr)
Set recip = make_new_email.Recipients.add(Trim(arr(jloc)))
If jloc = jlb Then
recip.Type = olTo
Else
recip.Type = olCC
End If
Next jloc
End Function
在一种情况下,您要分配一个变量,这需要 VB 增加 COM 对象引用计数(因此
Set
)。在另一种情况下,您要设置一个属性(SendUsingAccount
),这本质上是对 之类的函数的调用Set_SendUsingAccount(SomeValue)
。该函数的作用由它自己决定,因此您不需要Set
,