gpt4 book ai didi

excel - VBA 如何从函数返回 null

转载 作者:行者123 更新时间:2023-12-02 03:44:43 24 4
gpt4 key购买 nike

我有这个功能

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 未设置。错误

最佳答案

只有 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

引用号:Nothing? Empty? Missing? Null?

关于excel - VBA 如何从函数返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9073082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com