vbaoutlookoutlook-2013

macro Outlook 2013: changing address from undisclosed recipient to my address


I have a macro in Outlook 2013 that changes the address: from undisclosed recipient to my address. After runnung the macro on the message with the undisclosed recipient the following error occurs: Run time error "483" "Object doesn't support this property or method". System Windows 11 Pro, are installed: Microsoft Visual C++ 2005, 2008, 2010, 2013. Below is the macro code:

Attribute VB_Name = "ThisOutlookSession"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = True
Option Explicit

Public WithEvents olInboxItems As Items
Attribute olInboxItems.VB_VarHelpID = -1

Sub ChangeFieldTo()

    On Error GoTo GetChangeFieldTo_err

    Dim ns As NameSpace
    Dim Inbox As MAPIFolder
    Dim Item As Object
    
    Set ns = GetNamespace("MAPI")
    Set Inbox = ns.GetDefaultFolder(olFolderInbox)
    
    
' Empty Inbox?
    If Inbox.Items.Count = 0 Then
        MsgBox "No messages in inbox.", vbInformation, _
               "Nothing found!"
        Exit Sub
    End If
    
' Change To
    For Each Item In Inbox.Items
        If Item.To <> "k...user@gmail.com" Then
            Item.To = "k...user@gmail.com"
            Item.Save

        End If
    Next Item

' Clear memory
GetChangeFieldTo_exit:
    Set Item = Nothing
    Set ns = Nothing
    MsgBox "Done!", vbInformation
    Exit Sub

' Handle errors
GetChangeFieldTo_err:
    MsgBox "An unexpected error occurred." _
        & vbCrLf & "Please provide the administrator with the following information." _
        & vbCrLf & "Macro name: ChangeFieldTo" _
        & vbCrLf & "Error number: " & Err.Number _
        & vbCrLf & "Error description: " & Err.Description _
        , vbCritical, "Error!"
    Resume GetChangeFieldTo_exit
    
End Sub

Solution

  • Your code assumes that you can only have MailItem objects in the folder, but you can also have reports or meeting invitations/updates, which expose a different set of properties.

    Check if you really have a mail item first by looking at the Class property (exposed by all OOM objects):

    For Each Item In Inbox.Items
       if Item.Class = 43 'OlObjectClass.olMail
            If Item.To <> "k...user@gmail.com" Then
                Item.To = "k...user@gmail.com"
                Item.Save
    
            End If
        End If
    Next Item