excel VBA函数-如何将函数参数类型设置为条件?

3npbholx  于 2023-01-14  发布在  其他
关注(0)|答案(1)|浏览(140)

我创建了一个函数searchRow来获取目标值所在的行。
对于参数value,如何将此参数设置为条件?这样我就可以使用excel中的函数,如searchRow(<3, A1:A100),而不是仅使用值,如searchRow(10, A1:A100)

Function searchRow(value As String, targetRange As range) As Double
    
    Dim currentRange As range
    
    For Each currentRange In targetRange.Cells
        If currentRange.value = value Then
            searchRow = currentRange.Row
            Exit For
        End If
    Next currentRange
    
End Function
ajsxfq5m

ajsxfq5m1#

您可以在这里利用Worksheet.Evaluate,并在每次迭代时完成表达式,以便在该工作表的上下文中对其进行求值:

Public Function SearchRow(ByVal Value As Variant, ByVal TargetRange As Range) As Variant

    If IsError(Value) Then
        SearchRow = Value
        Exit Function
    End If

    Dim Context As Worksheet
    Set Context = TargetRange.Parent

    Dim CurrentRange As Range

    Dim ValueExpression As String
    Dim ExpressionResult As Variant

    Dim Operators As Variant
    Operators = Array("<", "<=", "=", "!=", "=>", ">")

    Dim LocalValue As String
    Dim ValueString As String
    Dim HasOperator As Boolean
    
    For Each CurrentRange In TargetRange.Cells

        LocalValue = Value
        ValueString = CurrentRange.Value
        ValueExpression = vbNullString
        ExpressionResult = Empty
        HasOperator = False

        Dim CurrentOperator As Long
        For CurrentOperator = LBound(Operators) To UBound(Operators)
            If Len(ValueString) > Len(CurrentOperator) Then
                If Left$(ValueString, Len(CurrentOperator)) = CurrentOperator Then
                    HasOperator = True
                    Exit For
                End If
            End If
        Next

        'if there's no operator, assume equals and still evaluate:
        If Not HasOperator And IsNumeric(Value) Then LocalValue = "=" & Value
        
        If ValueString <> vbNullString Then
            ValueExpression = ValueString & LocalValue
        
            On Error Resume Next
            ExpressionResult = CBool(Context.Evaluate(ValueExpression))
            On Error GoTo 0
        
            If Err.Number <> 0 Then
                SearchRow = CVErr(xlErrValue)
                Exit Function
            End If
            
            If Not IsEmpty(ExpressionResult) Then
                'now we know the result is safe to meaningfully treat as a Boolean:
                If ExpressionResult Then
                    SearchRow = CurrentRange.Row
                    Exit Function
                End If

            End If

        End If
    Next CurrentRange
    SearchRow = CVErr(xlErrNA)
End Function

注意Variant返回类型是如何被用来向工作表生成有意义的错误代码的。
因为第一个参数是String,所以当我们想给予它一个 string literal 时,我们需要用双引号把第一个参数括起来,所以用法看起来像=SearchRow("<3",A1:A100),但是也可以处理42SomeNamedRange,并且在输入中给定一个错误值时会像SUM一样失败。

相关问题