2015-02-07 32 views
0

我賦予它們出現在列表中,我這樣做,在Excel中像這樣利用COUNTIF函數數字的順序,存儲結果就像VBA的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函數,然後循環它們。
  • 一旦變量具有所有數字(數組),我想將它們粘貼到一個位置。

回答

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 
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 
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

0

下面的代碼評估結果作爲一個數組公式,並指定這一個varaiable訴你能適應參考和補充根據需要進行變量聲明。

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