Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA How to return null from a function

Tags:

null

excel

vba

I have this function

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
        emp = Null ' Heres what I'd like to do
    End If

    parseEmployee = emp
End Function

And I'd like to return null in case that the employee is not found in the sheet, is that possible? I get an object or variable nblock not set. error

like image 227
Tristian Avatar asked Jan 31 '12 00:01

Tristian


1 Answers

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 = emp
End 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?

like image 175
Mitch Wheat Avatar answered Oct 17 '22 23:10

Mitch Wheat