【发布时间】:2018-09-06 04:39:01
【问题描述】:
我有以下宏,它在 Excel 中获取电子邮件地址列表,并在 Outlook 的“我的联系人”部分下创建/更新 Outlook 分发列表。
如何调整此代码,以便它在名为“共享测试”的共享邮箱中创建/更新联系人,而不仅仅是在我的邮箱中?
Const DISTLISTNAME As String = "Test"
Const olDistributionListItem = 7
Const olFolderContacts = 10
Sub test() 'Worksheet_Change(ByVal Target As Range)
Dim outlook As Object ' Outlook.Application
Dim contacts As Object ' Outlook.Items
Dim myDistList As Object ' Outlook.DistListItem
Dim newDistList As Object ' Outlook.DistListItem
Dim objRcpnt As Object ' Outlook.Recipient
Dim arrData() As Variant
Dim rng As Excel.Range
Dim numRows As Long
Dim numCols As Long
Dim i As Long
Dim msg As String
msg = "Worksheet has been changed, would you like to update distribution list?"
If MsgBox(msg, vbYesNo) = vbNo Then
Exit Sub
End If
Set outlook = GetOutlookApp
Set contacts = GetItems(GetNS(outlook))
'On Error Resume Next
Set myDistList = contacts.Item(DISTLISTNAME)
On Error GoTo 0
If Not myDistList Is Nothing Then
' delete it
myDistList.Delete
End If
' recreate it
Set newDistList = outlook.CreateItem(olDistributionListItem)
With newDistList
.DLName = DISTLISTNAME
.Body = DISTLISTNAME
End With
' loop through worksheet and add each member to dist list
numRows = Range("A1").CurrentRegion.Rows.Count - 1
numCols = Range("A1").CurrentRegion.Columns.Count
ReDim arrData(1 To numRows, 1 To numCols)
' take header out of range
Set rng = Range("A1").CurrentRegion.Offset(1, 0).Resize(numRows, numCols)
' put range into array
arrData = rng.Value
' assume 2 cols (name and emails only)
For i = 1 To numRows
'little variation on your theme ...
Set objRcpnt = outlook.Session.CreateRecipient(arrData(i, 1) & "<" & arrData(i, 2) & ">")
'end of variation
objRcpnt.Resolve
newDistList.AddMember objRcpnt
Next i
newDistList.Save
'newDistList.Display
End Sub
Function GetOutlookApp() As Object
'On Error Resume Next
Set GetOutlookApp = CreateObject("Outlook.Application")
End Function
'To My Contacts
Function GetItems(olNS As Object) As Object
Set GetItems = olNS.GetDefaultFolder(olFolderContacts).Items
End Function
Function GetNS(ByRef app As Object) As Object
Set GetNS = app.GetNamespace("MAPI")
End Function
【问题讨论】:
-
第一个好的步骤是摆脱所有那些
On Error Resume Next并向我们展示您的代码产生的实际错误。我一直不明白为什么人们会这样做。为什么你不想知道代码中的错误在哪里? -
您好,感谢您的回复。但是,上面的代码不会出错,并且非常适合将联系人上传到我邮箱的“我的联系人”中。但我正在寻找一种将联系人上传到共享邮箱的方法,所以想知道如何为此调整代码。
-
好吧,如果它工作得很好,你为什么不删除那些表达式?只会让我们手头的事情变得更容易,所以我们不必预测您的代码会出现任何继承错误
-
是的,我会感谢你的。好建议。我是 VBA 的新手,刚刚在另一个论坛上找到了上述内容,但只是想知道如何调整它。谢谢
-
On Error Resume Next被严重滥用,因此大多数时候 Rawrplus 的建议是有效的。 cpearson.com/excel/errorhandling.htm。首次使用On Error Resume Next是有益的。你会发现你必须保持它未注释。小心只绕过您知道的错误,并根据需要处理或不处理。On Error Resume Next的第二个实例既无益也无害。