error "runtime error 91 object variable or with block variable not set" for outlook vba

hrh_dash 41 Reputation points
2022-11-19T15:42:14.853+00:00

Hi All, I am currently facing an issue with this outlook macro.

I would like the code to scan through all mails in my Inbox folder to look out for specific domains.

I don't need a folder to be created if destFolder does not exist but currently the code is not able to read any emails in my inbox as it is running out error "runtime error 91 object variable or with block variable not set"

I did some refer the SMTP code from the this link: how-to-move-email-to-folder-based-on-the-sender-domain

The code is as follows:

Option Explicit  
  
Sub moveemailToFolder()  
      
    Dim strSenderDomain As String  
    Dim strSenderEmailAddress As String  
    Dim objDestFolder As Folder  
    Dim obj         As Object  
    Dim NS          As NameSpace  
    Dim inboxFolder As Outlook.MAPIFolder  
    Dim mail        As MailItem  
      
    Set NS = GetNamespace("MAPI")  
    Set inboxFolder = NS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)  
    Debug.Print inboxFolder  
      
    For Each mail In inboxFolder.Items  
      
        'On Error Resume Next  
          
        Debug.Print obj.Subject  
          
        If obj.SenderEmailType = "EX" Then        ' exchange  
          
        strSenderEmailAddress = obj.Sender.GetExchangeUser().PrimarySmtpAddress  
          
    Else        ' smtp  
          
        strSenderEmailAddress = obj.SenderEmailAddress  
          
    End If  
      
    Debug.Print "SenderEmailAddress: " & strSenderEmailAddress  
      
    strSenderDomain = Mid$(strSenderEmailAddress, InStrRev(strSenderEmailAddress, "@") + 1, _  
                      InStrRev(strSenderEmailAddress, ".") - _  
                      InStrRev(strSenderEmailAddress, "@") - 1)  
      
    Debug.Print "strSenderDomain: " & strSenderDomain  
      
    Set objDestFolder = NS.GetDefaultFolder(olFolderInbox).Folders("test test test>")  
      
    If strSenderDomain Like "*shipping123*" Then  
        obj.Move objDestFolder  
          
    Else  
        MsgBox ("No emails To move.")  
        Exit Sub  
          
    End If  
      
    Set NS = Nothing  
    Set objDestFolder = Nothing  
    Set inboxFolder = Nothing  
      
    End If  
      
Next  
  
End Sub  

therefore, how should the code be amended or rectify?

appreciate the assistance in advance!

Outlook Management
Outlook Management
Outlook: A family of Microsoft email and calendar products.Management: The act or process of organizing, handling, directing or controlling something.
4,900 questions
0 comments No comments
{count} votes

Accepted answer
  1. Tom van Stiphout 1,621 Reputation points MVP
    2022-11-20T00:44:10.217+00:00

    Set a breakpoint at the top of the procedure and step through. What line is causing the error?


0 additional answers

Sort by: Most helpful