associative array in vba like php

后端 未结 2 481
暗喜
暗喜 2020-12-20 07:31

I need your help for building analytics in Microsoft Excel using VBA.

I have one data sheet with y columns and n lines



        
2条回答
  •  感情败类
    2020-12-20 07:46

    So I set my sheet up like this:

    Then using the following code I loaded the array and cycled through each line in the array. I added the Hours as they met the condition and displayed the result in the immediate window.

    Edit: As far as I know excel does not use column names. So the only way I could come up with is this, Where we add the first row into the array then cycle through them looking for the names in the first row of the array to get the position of that column then use the variable to find again.

    A quicker method would likely be an advanced filter with subtotals. Filter on a different page than the data. Or, the best answer would be using a pivot table.

    Sub nubuk()
    
    Dim arr() As Variant
    Dim smTtl As Double
    Dim i&
    Dim lastrow As Long
    Dim lastcolumn
    Dim t&
    Dim cntry&, stus&, hrs&
    
    With ActiveSheet
        lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row
        lastcolumn = Cells(1, .Columns.Count).End(xlToLeft).Column
        Debug.Print lastcolumn
        arr = .Range(.Cells(1, 1), .Cells(lastrow, lastcolumn)).Value
    End With
    For t = 1 To lastcolumn
        Select Case LCase(arr(1, t))
            Case "country"
                cntry = t
            Case "training status"
                stus = t
            Case "training hours"
                hrs = t
            Case Else
        End Select
    Next t
    For i = LBound(arr, 1) To UBound(arr, 1)
        If arr(i, cntry) = "USA" And arr(i, stus) = "Completed" Then
            smTtl = smTtl + arr(i, hrs)
        End If
    Next
    
    Debug.Print smTtl
    
    End Sub
    

提交回复
热议问题