VBA How to return null from a function VBA How to return null from a function vba vba

VBA How to return null from a function


Only a Variant can be Null, instead use Nothing:

Public Function parseEmployee(ByVal employeeId As Integer, _                                ByVal ws As Worksheet) As employee     Dim emp As New employee     Dim empRow As Range     If sheetContainsEmployee(employeeId, ws) Then         Set empRow = ws.Rows(ws.Columns(ID_COLUMN).Find(employeeId).Row)         emp.id = employeeId         emp.Name = empRow.Cells(1, NAME_COLUMN).Value     Else         Set emp = Nothing    End If     Set parseEmployee = empEnd Function 

The way you would test:

  Dim emp As employee   Set emp = parseEmployee( ... )  If emp Is Nothing Then      Debug.Print "No employee returned."  End If

Ref: Nothing? Empty? Missing? Null?


I have found that returning Nothing from a function causes an exception.

What I did instead was to write a sub that takes a ByRef parameter that is your return value.

Instead of this:

Public Function test() as SomeClass     set test = NothingEnd Function

I wrote this:

Public Sub test(ByRef result as SomeClass)     result = NothingEnd Sub


just use """", or "", which one will work, you could try, as:

Else Set emp = """"

note that there is no space between