3

I am trying, in the trivial case, to extract Outlook email bodies and paste them into a Worksheet.

However, assigning the .Body (a String) property of olMail object to the EmailBody variable (also a String) triggers an "Application-defined or object-defined error", at line EmailBody = .Body running the below code. I am using the same method seen on numerous other threads except looping through a restricted set of folder items. The olMail.Class = 43 (mailitem). Unsure why ActiveExplorer, GetInspector or the NewMailEx methods are necessary given the below code seems logical.

Why isn't this working?

CODE

Option Explicit

Sub Test()

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.Calculation = xlCalculationManual
    
        ' Part 1
        
            Dim wb              As Workbook, _
                ws              As Worksheet, _
                tStamp1         As String, _
                EmailBody       As String, _
                wsCount         As Integer, _
                j               As Integer
                
                j = 2
                Set wb = ThisWorkbook
                Set ws = wb.Worksheets("Sheet1")
                tStamp1 = Format(DateAdd("h", 10, Date - 3), "ddddd h:nn AMPM")
                
            Dim ol              As Outlook.Application, _
                ns              As Namespace, _
                fol             As MAPIFolder, _
                subFolderItems  As Outlook.Items, _
                olMail          As Object, _
                olMailID        As String, _
                StoreID         As String

                Set ol = New Outlook.Application
                Set ns = ol.GetNamespace("MAPI")
                Set fol = ns.Folders("[insert folder]").Folders("[insert folder]").Folders("[insert folder]")
                Set subFolderItems = fol.Items
                Set subFolderItems = subFolderItems.Restrict("[ReceivedTime] > '" & tStamp1 & "' ")
                       
        ' Part 2
            
            Do
                wsCount = wb.Worksheets.Count
                If wsCount > 1 Then
                    wb.Worksheets(2).Delete
                End If
                j = j + 1
            Loop Until wsCount = 1
            
            For Each olMail In subFolderItems
                With olMail
                    If .Subject Like "*[insert subject]*" Then
                        
                        .BodyFormat = olFormatPlain
                        EmailBody = .Body
                        
                        With wb
                            .Worksheets.Add After:=.Worksheets(1)
                            .Worksheets(2).Range("A1").Value = EmailBody
                        End With
                        ElseIf .Subject = "[insert subject]" Then
                            .Display
                    
                    End If
                End With
            Next olMail

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic

End Sub

EDIT #1

Substituted

                        olMailID = .EntryID
                        StoreID = fol.StoreID
                        Set olMail = ns.GetItemFromID(olMailID)

For

                        .BodyFormat = olFormatPlain

and the error now reverts to "Application-defined or object-defined error".


EDIT #2

Noticed in Locals window that the body carries no value

enter image description here


EDIT #3

So, tried MS suggestions found here but received the same error at line Set wdDoc = myInspector.WordEditor; which lead to here, implying an Outlook security feature is preventing the extraction. Not fully confident this is the cause but does anybody have a better idea?

Option Explicit

Sub Test()

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.Calculation = xlCalculationManual
    
        ' Part 1
        
            Dim wb              As Workbook, _
                ws              As Worksheet, _
                tStamp1         As String, _
                EmailBody       As String, _
                wsCount         As Integer, _
                j               As Integer
                
                j = 2
                Set wb = ThisWorkbook
                Set ws = wb.Worksheets("Sheet1")
                tStamp1 = Format(DateAdd("h", 10, Date - 3), "ddddd h:nn AMPM")
                
            Dim ol              As Outlook.Application, _
                ns              As Namespace, _
                fol             As MAPIFolder, _
                subFolderItems  As Outlook.Items, _
                olMail          As Object, _
                olMailID        As String, _
                StoreID         As String

                Set ol = New Outlook.Application
                Set ns = ol.GetNamespace("MAPI")
                Set fol = ns.Folders("[insert folder]").Folders("[insert folder]").Folders("[insert folder]")
                Set subFolderItems = fol.Items
                Set subFolderItems = subFolderItems.Restrict("[ReceivedTime] > '" & tStamp1 & "' ")
                              
            Dim myInspector As Outlook.Inspector, _
                wdDoc As Word.Document, _
                wdRange As Word.Range
                       
        ' Part 2
            
            Do
                wsCount = wb.Worksheets.Count
                If wsCount > 1 Then
                    wb.Worksheets(2).Delete
                End If
                j = j + 1
            Loop Until wsCount = 1
            
            For Each olMail In subFolderItems
                With olMail
                    If .Subject Like "*[insert subject]*" Then

                        .Display
                        Set myInspector = .GetInspector
                        Set wdDoc = myInspector.WordEditor
                        Set wdRange = wdDoc.Range(0, wdDoc.Characters.Count)
                        wdRange.InsertBefore ("EMAIL BODY")
                         
                    End If
                End With
            Next olMail

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic

End Sub

EDIT #4

Here is the same approach as first described. I have copied it exactly and still find the same error at same place, so this must be security or Outlook upgrade related.


EDIT #5

So, after rethinking through the problem, have tried navigating around the plausible security issue by running the below code in Outlook. Yet, the same error appears at line .SaveAs (Str), olTXT (enumeration and syntax seem fine).

Option Explicit

Sub Test()
        
    Dim ol              As Application, _
        ns              As Namespace, _
        fol             As MAPIFolder, _
        subFolderItems  As Items, _
        olMail          As Object, _
        Str             As String, _
        tStamp1         As String

        tStamp1 = Format(DateAdd("h", 10, Date - 1), "ddddd h:nn AMPM")
        Set ol = New Application
        Set ns = ol.GetNamespace("MAPI")
        Set fol = ns.Folders("[insert folder]").Folders("[insert folder]").Folders("[insert folder]")
        Set subFolderItems = fol.Items
        Set subFolderItems = subFolderItems.Restrict("[ReceivedTime] > '" & tStamp1 & "' ")
    
    For Each olMail In subFolderItems
        With olMail
            If .Subject Like "*[insert subject]*" Then
                
                Str = "[insert file path]"
                Str = Str & .Subject & ".txt"

                .SaveAs (Str), olTXT
            
            End If
        End With
    Next olMail

End Sub

EDIT #6

Looked here which lead to here where this section

enter image description here

is important. No Admin rights so avenue of enquiry is moot.

  • Why do this `Set olMail = ns.GetItemFromID(olMailID)` when you already have a reference to olMail ? Likely that’s not a good idea inside a `with` block – Tim Williams Sep 05 '21 at 22:08
  • `VBA 1004 Error` is a runtime error in VBA which is also known as `application-defined or object-defined` error and why is that because `we have limited number of columns` in excel and when our code gives the command to go out of range we get `1004 error`, there are other situations when we get this error when we refer to `a range which does not exist in the sheet`. I think the email body is larger than what excel can handle. [Source](https://www.wallstreetmojo.com/vba-1004-error/) – iѕєρєня Sep 05 '21 at 22:09
  • @TimWilliams, due to trouble-shooting errors, the thinking was perhaps `olMail` hadn't instantiazed properly ... though local windows looked fine. How would blocking with `With` effect? – Geoffrey Turner Sep 05 '21 at 22:39
  • @TimWilliams, to clarify: removing `olMailID`, `StoreID` and setting 'olMail', results in the "Method 'Body' of object_'_MailItem' failed" error again. – Geoffrey Turner Sep 05 '21 at 22:57
  • @iѕєρєня, it is odd. Body contents are minimal, much too small to bother Excel size constraints. Had a look at the source link provided and didn't see any other associations to the current problem. – Geoffrey Turner Sep 06 '21 at 00:02
  • @GeoffreyTurner the link just talked about the error you've got. if the code gets at least one e-mail before it throws an error, you can check which mail is a problematic one. but if its not even starting, the error is wrong and you have to debug the code line by line. I don't use outlook, but if I would I could've check it on my PC to see if I can find the error root. – iѕєρєня Sep 06 '21 at 13:26
  • Have you tried `.HTMLBody`? – Jeremy Thompson Sep 07 '21 at 03:01
  • @JeremyThompson, same error sadly. – Geoffrey Turner Sep 07 '21 at 10:21
  • Is that a signed/encrypted message by any chance? – Dmitry Streblechenko Sep 08 '21 at 17:55
  • Hi @DmitryStreblechenko. Doesn't look to be - how do I check? – Geoffrey Turner Sep 08 '21 at 23:54
  • Look at the message icon in the Outlook Explorer for that message. – Dmitry Streblechenko Sep 09 '21 at 04:14
  • Not that I can see. Also ran an advanced search just in case. – Geoffrey Turner Sep 09 '21 at 04:39

0 Answers0