Excel VBA如何从函数返回null
我有这个功能Excel VBA如何从函数返回null,excel,vba,null,Excel,Vba,Null,我有这个功能 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 em
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。错误只有
变量
可以为空
,而使用无
:
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
Ref:只需使用“”,或“”,您可以尝试使用哪种方法,如下所示:
否则
设置emp=“”“”
请注意,之间没有空格。我发现函数不返回任何内容会导致异常 我所做的是编写一个sub,它接受一个ByRef参数,该参数是您的返回值 与此相反:
Public Function test() as SomeClass
set test = Nothing
End Function
我写道:
Public Sub test(ByRef result as SomeClass)
result = Nothing
End Sub
感谢您的回复,我尝试将其设置为nothing,但仍然得到运行时错误91:Object variable或with block variable not set。您需要
set emp=nothing
还将该集合添加到“return”行。