在VBA中创建自定义计数功能

时间:2017-11-09 11:27:13

标签: arrays excel vba excel-vba

您好我想创建一个函数来计算数组中具有特定特征的值的数量,并需要您的帮助:

基本上,数组列表如下所示(简称为alr):

1111111 1111110 1111101 1101001 1011111 1011110 1011101 1011100 1011001

我在单元格A1中有一个值(让我们说1101001)

我想计算数组中大于单元格A1中的值的数量,并且特定值与单元格A1之间的差值具有数字之和< = 7

我的代码如下:

Function NumOps(Curr_ConFig As Variant, ListOfOptions As Range)

    Dim Array1 As Variant
    Dim i As Long
    Dim k As Long
    Dim C As Integer

    Array1 = ListOfOptions
    C = 0

    For i = LBound(Array1) To UBound(Array1)

        k = i - Curr_ConFig

        If k < 0 Then
            C = C
        ElseIf SumDigits(k) > 7 Then
            C = C
        Else: C = C + 1
        End If     
    Next i
    NumOps = C
End Function

Curr_ConFig应该是单元格A1。 ListOfOptions应该是Excel中数组的范围。

假设我已经成功创建了SumDigits()函数。

有人能指出我正确的方向吗?感谢

2 个答案:

答案 0 :(得分:1)

有效的代码:

Function NumOps(Curr_ConFig As Range, ListOfOptions As Range)

Dim count As Integer
Dim cell As Range
count = 0

For Each cell In ListOfOptions.Cells
    If Val(cell) >= Val(Curr_ConFig) And SumDigits(Val(cell) - Val(Curr_ConFig)) <= 7 Then
        count = count + 1
    End If
Next

NumOps = count

End Function

答案 1 :(得分:0)

您的问题的详细信息有点不清楚,但这应该有所帮助:

Function NumOps(Curr_ConFig As Range, ListOfOptions As Range) ' assuming Curr_ConFig is passed in as a Range (Cell)
    Dim count As Integer
    count = 0

    For each cell in ListOfOptions.Cells
        If CInt(cell) > CInt(Curr_Config) And SumDigits(Curr_Config) <= 7 Then ' CInt() converts a string to an integer
            count = count + 1
        End If     
    Next

    NumOps = count
End Function