在VBA excel中存储具有countif的数组的结果

时间:2015-02-07 20:53:19

标签: excel vba excel-vba countif

我正在为他们在列表中出现的顺序分配数字,我使用excel中的countif函数来做这样的事情,

=COUNTIF(A$2:A2,A2)

Number  Count
10        1
10        2
10        3
11        1
11        2
11        3
12        1

我希望使用VBA实现同样的目标。但是,这里有具体细节。

  • 我想获取一个变量并计算countif函数然后循环它们。
  • 一旦变量包含所有数字(数组),我想将它们粘贴到一个位置。

4 个答案:

答案 0 :(得分:0)

假设列A按照上面的列表排序,您可以使用以下内容。

Dim arr(100,1) as double '100 = arbitrary number for this example
dim n as double

n=1

arr(roW,0) = Cell(roW + 2, 1).value
arr(roW,1) = n

For roW = 1 to 100
    IF Cell(roW + 2, 1).value = Cell(roW + 1, 1).value Then
        n = Cell(roW + 2, 1).value
    Else 
        n=1
    End if
    arr(roW,0) = Cell(roW + 2, 1).value
    arr(roW,1) = n
Next

Range("C2:D102")=arr

答案 1 :(得分:0)

这是我的建议。

Sub Counts()
Dim ws As Worksheet
Set ws = ThisWorkbook.ActiveSheet
Dim lngLastRow As Long
lngLastRow = ws.UsedRange.Rows.Count
Dim Arr() As Variant
'Taking values in column A into an array
Arr = ws.Range("A2:A" & lngLastRow).Value
Dim Arr2() As Variant
'another Array for Countif results
ReDim Arr2(lngLastRow - 2, 0)
Dim count As Long
Dim i As Long, j As Long 'counters

    'counting
    For i = LBound(Arr) To UBound(Arr)
        count = 0
        For j = LBound(Arr) To i
            If Arr(j, 1) = Arr(i, 1) Then count = count + 1
        Next
        'filling the array with results
        Arr2(i - 1, 0) = count
    Next
    'sending results back to the worksheet
    ws.Range("B2:B" & lngLastRow).Value = Arr2

Set ws = Nothing
End Sub

答案 2 :(得分:0)

另一种选择,

Sub GetUniqueAndCountif()
    Dim cUnique As Collection
    Dim Rng As Range
    Dim Cell As Range, nW As Range
    Dim sh As Worksheet
    Dim vNum As Variant

    Set sh = ThisWorkbook.Sheets("Sheet1")
    Set Rng = sh.Range("A2", sh.Range("A2").End(xlDown))
    Set cUnique = New Collection

    On Error Resume Next
    For Each Cell In Rng.Cells
        cUnique.Add Cell.Value, CStr(Cell.Value)
    Next Cell
    On Error GoTo 0

    For Each vNum In cUnique
        Set nW = Cells(Rows.Count, "C").End(xlUp).Offset(1, 0)
        nW = vNum
        nW.Offset(, 1) = WorksheetFunction.CountIf(Rng, nW)
    Next vNum

End Sub

Before After

答案 3 :(得分:0)

以下代码将结果评估为单个数组公式,并将其分配给变量v。您可以根据需要调整引用并添加变量声明。

Sub CountifArray()
v = Evaluate(Replace("INDEX(COUNTIF(OFFSET(y,,,ROW(y)-MIN(ROW(y))+1),y),)", "y", "A2:A8"))
Range("B2:B8") = v
End Sub