如何将工作表中的行读入VBA中的自定义类数组?

时间:2014-08-20 00:52:59

标签: excel excel-vba vba

我有以下Excel数据:

id  name    Math  Science   English   History
1   James   51    40        94        14
2   John    12    43        15        62
3   Bob     11    88        57        61
4   Peter   25    50        11        45

我想把它读成一个 Class Student 的数组,它将拥有所有6个属性。

我如何在中进行此操作?

1 个答案:

答案 0 :(得分:10)

说你的“Sheet1”电子表格看起来像这样:

enter image description here

当您打开Visual Basic编辑器 ALT + F11 时,您需要右键单击您的VBA项目并插入2个模块:一个标准Module1和一个类模块。

将类模块重命名为Student并用

填充它
Public Id As Long
Public Name As String
Public Math As Long
Public Science As Long
Public English As Long
Public History As Long

Public Function GetAverage()
    GetAverage = (Math + Science + English + History) / 4
End Function

Module1

Sub Main()

    Dim students As New Collection ' collection to store all students


    Dim cell As Range ' iterator
    Dim person As Student

    ' for each cell in column A
    For Each cell In Sheets(1).Range("A2:A" & Range("A" & Rows.Count).End(xlUp).Row)
        ' create a new student object
        Set person = New Student
        ' fill the data
        person.Id = cell
        person.Name = cell.Offset(0, 1)
        person.Math = cell.Offset(0, 2)
        person.Science = cell.Offset(0, 3)
        person.English = cell.Offset(0, 4)
        person.History = cell.Offset(0, 5)

        ' add the student to the collection of students
        students.Add person
    Next

    ' open Immediate Window CTRL + G or VIEW -> Immediate Window
    Dim s As Student
    For Each s In students
        Debug.Print "ID: " & s.Id & vbTab & "Name: " & s.Name, "Math: " & s.Math, "Science: " & s.Science, "English: " & s.English, "History: " & s.History, "Avg: " & s.getAverage()
    Next

End Sub

现在,如果您运行 F5 您的宏并查看您的立即窗口,您将把电子表格中的所有数据以编程方式加载到集合中;

enter image description here

*注意:I have reblogged this with some additional details