Add contact to group based on custom fields

61 Views Asked by At

I want to loop through all contacts and check for the presence of "check marks" in the following fields: MyCategory, CIC, MC, Asia, Comm, COMI, CoU, RSC, SC, and SRC.

If a contact has a check mark in a particular field, it should be added to the group with the same name as the field.

I can not add contact to the group.

I get

runtime-error "424" (Object required)

Sub AddContactsToGroups2()
    Dim olApp As Outlook.Application
    Dim olNs As Outlook.NameSpace
    Dim olFolder As Outlook.Folder
    Dim olContact As Outlook.ContactItem
    Dim olGroup As Outlook.DistListItem
    Dim strField As Variant
    Dim blnChecked As Boolean
    
    Set olApp = Outlook.Application
    Set olNs = olApp.GetNamespace("MAPI")
    Set olFolder = olNs.GetDefaultFolder(olFolderContacts)
    
    For Each olContact In olFolder.Items
        For Each strField In Array("MyCategory", "CIC", "MC", "Asia", "Comm", "COMI", "CoU", "RSC", "SC", "SRC")
            blnChecked = False
            If Not olContact.UserProperties(strField) Is Nothing Then
                If olContact.UserProperties(strField).Value = True Then
                    blnChecked = True
                    Exit For
                End If
            End If
        Next strField
        
        If blnChecked Then
            'Set olGroup = olNs.CreateItem(olDistributionListItem)
            Set olGroup = olApp.CreateItem(olDistributionListItem)
            olGroup.DLName = strField
            olGroup.AddMembers (olContact) ' here I could not add contact to the group, error "424" (Object required).
            olGroup.Save
        End If
        
    Next olContact
    
    Set olGroup = Nothing
    Set olContact = Nothing
    Set olFolder = Nothing
    Set olNs = Nothing
    Set olApp = Nothing
End Sub
2

There are 2 best solutions below

1
artnib On

To add single contact use AddMember method (instead of AddMembers):

olGroup.AddMember olContact
0
Eugene Astafiev On

The DistListItem.AddMember method accepts a recipient object to be added to the list. You can use the CreateRecipient method of the Namespace class which creates a Recipient instance. The name of the recipient can be a string representing the display name, the alias, or the full SMTP email address of the recipient. For example:

Sub AddNewMember() 
 'Adds a member to a new distribution list 
 Dim objItem As Outlook.DistListItem 
 Dim objMail As Outlook.MailItem 
 Dim objRcpnt As Outlook.Recipient 
 
 Set objMail = Application.CreateItem(olMailItem) 
 Set objItem = Application.CreateItem(olDistributionListItem) 
 'Create recipient for distlist 
 Set objRcpnt = Application.Session.CreateRecipient("Eugene Astafiev") // or email address
 objRcpnt.Resolve 
 objItem.AddMember objRcpnt 
 'Add note to list and display 
 objItem.DLName = "Northwest Sales Manager" 
 objItem.Body = "Regional Sales Manager - NorthWest" 
 objItem.Save 
 objItem.Display 
End Sub