我有这个功能
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
如果在工作表中找不到员工,我想返回null,这可能吗?我得到一个未设置的对象或变量nblock。错误
答案 0 :(得分:13)
只有Variant
可以是Null
,而是使用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
你要测试的方式:
Dim emp As employee
Set emp = parseEmployee( ... )
If emp Is Nothing Then
Debug.Print "No employee returned."
End If
答案 1 :(得分:0)
我发现从函数返回Nothing会导致异常。
我所做的是编写一个带有ByRef参数的子函数,该参数是您的返回值。
而不是:
Public Function test() as SomeClass
set test = Nothing
End Function
我写了这个:
Public Sub test(ByRef result as SomeClass)
result = Nothing
End Sub
答案 2 :(得分:-1)
只需使用“”“或”“,哪一个可以使用,你可以尝试,如:
否则 设置emp =“”“”
请注意
之间没有空格