计算相同值时VBA双循环不起作用

时间:2016-01-29 01:52:32

标签: arrays vba

我试图计算列中的相同值并将数字分配给数组。但计数部分没有按我的意愿去。数据样本如下所示:

A B C D E
        4
        4
        4
        4
        5
        5
        6
        6
        7
        7
        8
        8
        8

我的代码:

Sub CountSame()

last_row = ActiveSheet.Cells(Rows.count, 1).End(xlUp).Row

For i = 1 To last_row

    n = WorksheetFunction.CountIf(Columns(1), Cells(i, 1))

    Cells(i, 1) = n

    i = i + n - 1

Next

End Sub

结果是

enter image description here

然后我继续分配给数组

Sub CountSame()

last_row = ActiveSheet.Cells(Rows.count, 1).End(xlUp).Row

Dim arr() As Variant
ReDim arr(4)

For i = 1 To last_row

For j = 0 To 4

    n = WorksheetFunction.CountIf(Columns(1), Cells(i, 1))

    arr(j) = n

    i = i + n - 1

Next

Next

MsgBox arr(0)

End Sub

但是arr(0)给了我3而不是4的值。任何人都可以告诉我出了什么问题~~

非常感谢你。

1 个答案:

答案 0 :(得分:0)

你不需要' for循环'对于j。就在' for循环之前'对于i,添加行j = 0

删除' for循环'对于j。 在行I = I + n-1之后添加行 J = J + 1

对于last_row = I,正在执行J = 0到4,因此数组的所有值都具有与last_row对应的值,即3。

Sub CountSame()

last_row = ActiveSheet.Cells(Rows.count, 1).End(xlUp).Row

Dim arr() As Variant
ReDim arr(4)
J=0
For i = 1 To last_row


n = WorksheetFunction.CountIf(Columns(1), Cells(i, 1))

arr(j) = n

i = i + n - 1
J=j+1

Next

MsgBox arr(0)

End Sub