2015-10-06 23 views
0

此代碼刪除子文件夾中的所有聯繫人,然後將更新後的表格從excel發送到Outlook的正確聯繫人輸入值。Excel到Outlook聯繫人,對象不支持此屬性或方法

我收到錯誤:運行時錯誤438 - 對象不在該行支持此屬性或方法:

.FullName = Range("D" & i).Value 

所以我顯然不是這樣做的權利。我使用錯誤的操作?我沒有引用一個對象到正確的庫嗎?我可以看到從每個項目的Excel加載值,這只是沒有進入展望。我哪裏錯了?

由於多個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 [email protected]###.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 
+0

所以我的文章被編輯和格式化。哈哈謝謝。它在粘貼上丟失了格式。爲什麼添加Option Explicit?隱含地聲明所有變量是實現這個工作的唯一方法嗎? –

+0

將Option Explicit設置爲Off通常不是一種好的做法。您可能會在一個或多個位置拼錯變量名稱,這會在程序運行時導致意外的結果。 – 0m3r

+0

始終使用'Option Explicit'!在你的代碼中使用它可以讓你更早地捕獲和理解這個錯誤。 –

回答

1

如果您延遲綁定您的代碼,Outlook庫中的常量將不會被定義,如olContactItem。由於您的代碼頂部沒有Option Explicit,因此VBA假定您要創建一個名爲olContactItem的新變量,默認初始值爲0

這意味着您實際上正在創建MailItem,因爲那是olApp.CreateItem(0)會執行的操作。添加下面這行代碼的開頭:

Const olContactItem as Long = 2 
相關問題