Dobi Tamás
Dobi Tamás

Reputation: 25

Excel VBA Cannot return from function

Here is my code:

Function GetAttachmentById(Id As String) As Attachment
    Dim newAttachment As Attachment
    
    Set newAttachment = New Attachment
    
    Dim Directory As String
    
    Directory = "C:\Users\user\Desktop\VBA"
    
    Dim fso, newFile, folder, Files
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    Set folder = fso.GetFolder(Directory)
    Set Files = folder.Files
    
    For Each file In Files
    
        If InStr(file.Name, Id) > 0 Then
            newAttachment.Id = Id
            newAttachment.AttachmentName = file.Name
            newAttachment.AttachmentPath = file.Path
        End If
        
    Next file
    
    GetAttachmentById = newAttachment

On the last line where I try to return my Attachment object I get the error:

Object variable or With block variable not set

As I can see in the debugger, the newAttachment is created well and I have no "with" block so I am not sure where to go next.

Upvotes: 0

Views: 33

Answers (1)

rohrl77
rohrl77

Reputation: 3337

You are missing the Set statement in your last line of code.

Set GetAttachmentById = newAttachment

Upvotes: 4

Related Questions