【问题标题】:'run time error 424: object required' after changing function parameter to variant将函数参数更改为变体后的“运行时错误 424:需要对象”
【发布时间】:2019-08-29 17:46:31
【问题描述】:

我写了一个函数来查找特定范围内具有特定值的单元格。但我不断收到“需要对象”错误:如果 rng 为空。

如果我将函数参数(搜索值)类型设置为字符串,则不会出现此错误,仅当函数参数(搜索值)类型为变体时才会出现此错误。

这是我的代码:

Function TgtCell(SearchRange As Range, Optional SearchValue As Variant) As Range
    For Each Rng In SearchRange
        If IsMissing(SearchValue) Then
            If Rng Is Empty Then  'this is the line with the error
                TgtCell = Rng
                Exit For
            End If
        Else
            If Rng.Value = SearchValue Then
                Set TgtCell = Rng
                Exit For
            End If
        End If
    Next
End Function

下面是我的测试代码:

Sub test1()
Set Rng = TgtCell(Range([a1:a14], Cells(Rows.Count, 1)))
Rng.Select
End Sub

请帮助我理解为什么会这样。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    如果您想检查单元格/范围是否为“空”,请使用 IsEmpty。

    Function TgtCell(SearchRange As Range, Optional SearchValue As Variant) As Range
    Dim rng As Range
    
        For Each rng In SearchRange
            If IsMissing(SearchValue) Then
                If IsEmpty(rng) Then  'this is the line with the error
                    Set TgtCell = rng
                    Exit For
                End If
            Else
                If rng.Value = SearchValue Then
                    Set TgtCell = rng
                    Exit For
                End If
            End If
        Next rng
    
    End Function
    
    Sub test1()
    Dim rng As Range
    
        Set rng = TgtCell(Range([a1:a14], Cells(Rows.Count, 1)))
    
        rng.Select
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多