如何从工作表数据填充用户定义的类型数组

时间:2019-04-12 06:22:47

标签: excel vba

我有一个用户定义类型的数组,想要从工作表中获取数据到该数组中。我有一个解决方案,但看起来不太优雅。有更好或更简单的方法可以做到这一点吗?

Type Donation
    NBID As Integer
    Amount As Single
    DonationDate As Date
    TrackingCode As String
End Type

Public dons() as Donation

Sub init()
    Dim i As Integer
    Dim tmpDons() As Variant
    Dim donRows as Integer

    tmpDons = Sheets("Appeal Dons").UsedRange.Value2
    donRows = UBound(tmpDons)
    ReDim dons(donRows - 2)

    For i = 2 To donRows
        dons(i - 2).NBID = tmpDons(i, 1)
        dons(i - 2).Amount = tmpDons(i, 2)
        dons(i - 2).TrackingCode = tmpDons(i, 3)
        dons(i - 2).DonationDate = tmpDons(i, 4)
    Next
End Sub

1 个答案:

答案 0 :(得分:0)

尝试:

Option Explicit

Sub test()

    Dim arr As Variant
    Dim i As Long

    With ThisWorkbook.Worksheets("Sheet1")
        'Import to array the used range
        arr = .UsedRange

        'Loop from L to U arr bound
        For i = LBound(arr) To UBound(arr)
            'Code
        Next i

    End With

End Sub