vba VBA如何从函数返回null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9073082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 12:30:00  来源:igfitidea点击:

VBA How to return null from a function

excelvbanull

提问by Tristian

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

如果在工作表中找不到该员工,我想返回 null,这可能吗?我得到一个未设置的对象或变量 nblock。错误

回答by Mitch Wheat

Only a Variantcan be Null, instead use Nothing:

只有 aVariant可以是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 

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?

参考:什么都没有?空的?丢失的?空值?

回答by AKirby50

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

我发现从函数返回 Nothing 会导致异常。

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

我所做的是编写一个子程序,它接受一个 ByRef 参数作为您的返回值。

Instead of this:

取而代之的是:

Public Function test() as SomeClass
     set test = Nothing
End Function

I wrote this:

我写了这个:

Public Sub test(ByRef result as SomeClass)
     result = Nothing
End Sub

回答by Heidi

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

只需使用“”“”或“”,哪个有效,您可以尝试,如:

Else Set emp = """"

否则设置 emp = """"

note that there is no space between

请注意,之间没有空格