【发布时间】:2015-10-06 00:08:56
【问题描述】:
此代码删除子文件夹中的所有联系人,然后将更新的工作表从 excel 拍摄到 Outlook 的正确联系人输入值。
我收到错误:运行时错误 438 - 对象不支持该属性或方法:
.FullName = Range("D" & i).Value
所以我显然没有做对。我是否使用了错误的操作?我没有将对象引用到正确的库吗?我可以看到 excel 中的值加载到每个项目中,它只是没有进入 Outlook。我哪里错了?
由于多个 Outlook 版本,这是使用后期绑定,因此引用对象库不是一个选项。
Sub XL2OLContacts()
Dim olApp As Object 'using late binding to ensure compatibility for all office versions
Dim olItem As Object
Dim olFolder As Object
Dim olConItems As Object
Set olApp = CreateObject("Outlook.Application") 'opens outlook
Set olNamespace = olApp.GetNamespace("MAPI") 'setting MAPI location for contacts
Set activefolder = olNamespace.Folders 'making default user contacts active folder
n = 1 'counter starting
Do Until activefolder.Item(n) = (Environ$("Username")) & "@###.com" 'this says USERNAME@###.com will be the default user profile for contact location
n = n + 1
Loop
Set myfolder = activefolder.Item(n) 'default folder active
Set myfolder2 = myfolder.Folders("Contacts").Folders("Call Observation List") 'setting contacts subfolder to var now
Do
For Each ContactItem In myfolder2.Items
ContactItem.Delete
Next ContactItem
Loop Until myfolder2.Items.Count = 0 'otherwise it would only delete a handful each time it ran for some reason
n = 1
Do Until activefolder.Item(n) = (Environ$("Username")) & "@###.com"
n = n + 1
Loop
Set myfolder = activefolder.Item(n)
Set myfolder2 = myfolder.Folders("Contacts").Folders("Call Observation List")
lastrow = Sheets("CSV Page").Range("A" & Sheets("CSV Page").Rows.Count).End(xlUp).Row
For i = 1 To lastrow
Sheets("CSV Page").Activate
If ActiveSheet.Range("C" & i).Value = "" Then
Set olConItem = olApp.CreateItem(olContactItem)
With olConItem
.FullName = Range("D" & i).Value
.EmailAddress = Range("F" & i).Value
.HomePhone = Range("L" & i).Value
.MobilePhone = Range("N" & i).Value
.JobTitle = Range("Z" & i).Value
.Notes = Range("AC" & i).Value
.Save
End With
End If
Application.StatusBar = "Updating Contacts: " & Format(i / lastrow, "Percent") & " Complete"
Next i
End Sub
【问题讨论】:
-
所以我的帖子被编辑和格式化了。哈哈谢谢。它在粘贴时丢失了格式。为什么要添加 Option Explicit?隐式声明所有 var 是使其正常工作的唯一方法吗?
-
将 Option Explicit 设置为 Off 通常不是一个好习惯。您可能会在一个或多个位置拼错变量名,这会在程序运行时导致意外结果。
-
始终使用
Option Explicit!将它包含在您的代码中将使您能够更早地捕获和理解此错误。
标签: excel vba outlook late-binding