如何在VBA Excel UDF参数中使用比较运算符?

如何在VBA Excel UDF参数中使用比较运算符?,excel,vba,udf,Excel,Vba,Udf,我如何编写UDF,使它们在参数中接受比较运算符 当使用标准函数时,您可以这样写=countif(range;x),并且可以得到范围内等于x的单元格数 在VBA中复制此函数的外观如下所示: Function countifUDF(rng As Range, x As Integer) count = 0 For Each cell in rng.Cells If cell.Value = x Then count = count + 1

我如何编写UDF,使它们在参数中接受比较运算符

当使用标准函数时,您可以这样写=countif(range;x),并且可以得到范围内等于x的单元格数

在VBA中复制此函数的外观如下所示:

Function countifUDF(rng As Range, x As Integer)
    count = 0
    For Each cell in rng.Cells
        If cell.Value = x Then
            count = count + 1
        Next cell
    countifUDF = sum
End Function
使用标准函数时,可以向函数传递比较运算符,如=countif(range;“”和arr(1)=”然后 x=替换(x,“>”,“”) x=替换(x,“=”,“”) 对于rng.单元格中的每个单元格 如果cell.Value>=x,则 计数=计数+1 如果结束 下一个细胞 ElseIf arr(0)=“&x”as'>x”为什么我必须将x字符逐个拆分,并评估用户键入的比较运算符类型。

尝试以下操作:

Function countifUDF(rng As Range, x As Integer)
    Dim cell As Range
    Dim Count As Integer

    Count = 0
    For Each cell In rng.Cells
        If cell.Value < x Then Count = Count + 1
    Next cell

    countifUDF = Count

End Function
函数countifUDF(rng作为范围,x作为整数)
暗淡单元格作为范围
将计数设置为整数
计数=0
对于rng.单元格中的每个单元格
如果单元格值 使UDF()将第二个参数视为<强>字符串< /强>:

Function countifUDF(rng As Range, x As Variant) As Long
    Dim cell As Range, Count As Long, CH As String, VL As Long

    VL = Replace(Replace(x, ">", ""), "<", "")
    CH = Left(CStr(x), 1)
    Count = 0

    If CH = ">" Then
        For Each cell In rng.Cells
            If cell.Value > VL Then
                Count = Count + 1
            End If
        Next cell
    ElseIf CH = "<" Then
        For Each cell In rng.Cells
            If cell.Value < VL Then
                Count = Count + 1
            End If
        Next cell
    Else
        For Each cell In rng.Cells
            If cell.Value = x Then
                Count = Count + 1
            End If
        Next cell
    End If
    countifUDF = Count
End Function
函数countifUDF(rng作为范围,x作为变量)作为长度
变暗单元格作为范围,计数作为长度,通道作为字符串,VL作为长度
VL=替换(替换(x,“>”,“),”然后
对于rng.单元格中的每个单元格
如果单元格值>VL,则
计数=计数+1
如果结束
下一个细胞

ElseIf CH=“谢谢!我怀疑一个解决方案看起来会像这样,但实际上希望通过某种方式传递,>=,@user3805500您的想法很有趣………如果您用您的最终方法更新您的问题,我们将不胜感激!在问题中发布了我的解决方案,它并不漂亮。
Function countifUDF(rng As Range, x As Variant) As Long
    Dim cell As Range, Count As Long, CH As String, VL As Long

    VL = Replace(Replace(x, ">", ""), "<", "")
    CH = Left(CStr(x), 1)
    Count = 0

    If CH = ">" Then
        For Each cell In rng.Cells
            If cell.Value > VL Then
                Count = Count + 1
            End If
        Next cell
    ElseIf CH = "<" Then
        For Each cell In rng.Cells
            If cell.Value < VL Then
                Count = Count + 1
            End If
        Next cell
    Else
        For Each cell In rng.Cells
            If cell.Value = x Then
                Count = Count + 1
            End If
        Next cell
    End If
    countifUDF = Count
End Function