vbaoutlook

How to return function value with folder-type value so that code can test if found


This first bit of code calls a function that should return a folder with the name "MyFolder" or Nothing. I then want to test

Is folder = Nothing then 'or an equivalent

I have discovered that IsObject returns true if sf_folder / sf_HEM_find_folder() is Nothing which then does not work as hoped.

I tried types Object and Folder with no change in behaviour.

What is the best solution please?

  Dim sf_folder As Object
  Dim Err_text As String
  
   Set sf_folder = sf_HEM_find_folder("MyFolder")
  
  If Not IsObject(sf_folder) Then
    Err_text = "Folder " & sf_text & " not found"
    GoTo ErrorHandler
  End If
  
  VbMsgBoxResult = MsgBox "MyFolder found", vbOK

The function is...

Function sf_HEM_find_folder(ByVal sf_folder_name As String) As Object

'The calling code must ensure that the current folder is email
'returns nothing if folder not found

  Dim sf_folder As Object
  Dim sf_f0 As Folder

  Set sf_HEM_find_folder = Nothing
  
  Set sf_f0 = Application.ActiveExplorer.CurrentFolder

' Iterate through first group sub-folders of the inbox to find the one specified in sf_folder_name

  For Each sf_folder In sf_f0.Folders
' * Until the end of list
'   Find the folder by name

    If sf_folder.Name = sf_folder_name Then
      sf_HEM_find_folder = sf_folder
      Exit For
    End If
  Next sf_folder
  
End Function

Solution

  • To compare an object to Nothing, you need to replace the = with Is

    If Object Is Nothing Then
       ` Do Stuff
    End If
    

    If you want to return an Object, you cant just assign it to the function name like you would with a String (or other value type), it needs to be Set

    Set sf_HEM_find_Folder = sf_folder