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

问题描述 投票:0回答:1

我有一个用户定义类型的数组,并希望从工作表中获取数据到此数组。我有一个解决方案,但它似乎不优雅。有没有更好或更简单的方法来做到这一点?

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
excel vba
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.