VBA code to create a simple school data structure using VBA


 Option Explicit


' Declare custom types for student and teacher

Type Student

    Name As String

    Age As Integer

    Class As String

End Type


Type Teacher

    Name As String

    Age As Integer

    Subject As String

End Type


' Declare arrays to store students and teachers

Dim students() As Student

Dim teachers() As Teacher


Sub AddStudent(name As String, age As Integer, class As String)

    ' Add a new student to the students array

    Dim index As Integer

    index = UBound(students) + 1

    ReDim Preserve students(index)

    students(index).Name = name

    students(index).Age = age

    students(index).Class = class

End Sub


Sub AddTeacher(name As String, age As Integer, subject As String)

    ' Add a new teacher to the teachers array

    Dim index As Integer

    index = UBound(teachers) + 1

    ReDim Preserve teachers(index)

    teachers(index).Name = name

    teachers(index).Age = age

    teachers(index).Subject = subject

End Sub


Sub Main()

    ' Initialize the students and teachers arrays

    ReDim students(0)

    ReDim teachers(0)

    

    ' Add some students

    AddStudent "John", 10, "5A"

    AddStudent "Mary", 11, "5A"

    AddStudent "Tom", 9, "4B"

    

    ' Add some teachers

    AddTeacher "Mr. Smith", 35, "Math"

    AddTeacher "Ms. Johnson", 28, "Science"

    

    ' Print the student and teacher data to the Immediate window

    Dim i As Integer

    Debug.Print "Students:"

    For i = 1 To UBound(students)

        Debug.Print students(i).Name & " (" & students(i).Age & " years old, Class " & students(i).Class & ")"

    Next i

    Debug.Print ""

    Debug.Print "Teachers:"

    For i = 1 To UBound(teachers)

        Debug.Print teachers(i).Name & " (" & teachers(i).Age & " years old, Subject " & teachers(i).Subject & ")"

    Next i

End Sub

This code defines custom types Student and Teacher, and creates arrays students and teachers to store the data. The AddStudent and AddTeacher subroutines are used to add new students and teachers to the arrays. Finally, the Main subroutine initializes the arrays with some sample data, and prints the student and teacher data to the Immediate window. You can modify the code to add more fields to the Student and Teacher types, or to perform different operations on the data.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.