如何创建动态数组以循环遍历列表并根据条件

时间:2016-03-07 17:53:31

标签: arrays vba dynamic

下面我列出了“ID”号码及其相关的“号码”及其“值”。我正在尝试创建一个包含动态数组的子函数,该数组收集所有“数字”等于和小于30的“值”。数组填充后,将其求和并放在标题为“30”的标题下或更少”。我一直试图用VBA做这个没有运气。我已经阅读了一些帖子和文件,告诉我如何做到这一点,但我无法理解它。有人可以告诉我如何完成这项工作。它让我疯狂,我确信它很简单,我最终想要扩展它,以便对大于30但小于60的“数字”做同样的事情,依此类推。谢谢

    ID  Number  Value
     0   60     100
     1   31     101
     2   12     102
     3   30     103
     4   21     104
     5   60     105
     30 or less

1 个答案:

答案 0 :(得分:0)

尝试将其粘贴到VB中的新模块中。

这假设您的原始数据位于Sheet(1),排序的数据将位于新的空白工作表中Sheet(2)

Sub AddNumbers()
Dim RowNo, ColNo As Long

'Skip Header Row
RowNo = 2

    Do Until Sheets(1).Cells(RowNo, 1) = ""

        If Sheets(1).Cells(RowNo, 2) <= 30 Then
        Sheets(2).Cells(1, 1) = "30 or less"
        ColNo = 1
        Sheets(2).Cells((Sheets(2).Cells(Rows.Count, 1).End(xlUp).row + 1), ColNo) = Sheets(1).Cells(RowNo, 3)

        ElseIf Sheets(1).Cells(RowNo, 2) > 30 And Sheets(1).Cells(RowNo, 2) <= 60 Then
        Sheets(2).Cells(1, 2) = "Between 30 and 60"
        ColNo = 2
        Sheets(2).Cells((Sheets(2).Cells(Rows.Count, 2).End(xlUp).row + 1), ColNo) = Sheets(1).Cells(RowNo, 3)

        ElseIf Sheets(1).Cells(RowNo, 2) > 60 And Sheets(1).Cells(RowNo, 2) <= 90 Then
        Sheets(2).Cells(1, 3) = "Between 60 and 90"
        ColNo = 3
        Sheets(2).Cells((Sheets(2).Cells(Rows.Count, 3).End(xlUp).row + 1), ColNo) = Sheets(1).Cells(RowNo, 3)

        End If

        RowNo = RowNo + 1

    Loop

    ' Add Subtotals

    ColNo = 1
    Do Until Sheets(2).Cells(1, ColNo) = ""
    Sheets(2).Cells((Sheets(2).Cells(Rows.Count, ColNo).End(xlUp).row + 1), ColNo).Formula = "=SUM(" & Col_Letter(ColNo) & "2:" & Col_Letter(ColNo) & (Sheets(2).Cells(Rows.Count, ColNo).End(xlUp).row) & ")"
    Sheets(2).Cells((Sheets(2).Cells(Rows.Count, ColNo).End(xlUp).row), ColNo).Font.Bold = True
    ColNo = ColNo + 1
    Loop

End Sub

Function Col_Letter(lngCol As Long) As String
Dim vArr
vArr = Split(Cells(1, lngCol).Address(True, False), "$")
Col_Letter = vArr(0)
End Function