Forum

How to use Class mo...
 
Notifications
Clear all

How to use Class module in VBA

3 Posts
2 Users
0 Reactions
148 Views
(@julian)
Posts: 82
Estimable Member
Topic starter
 

I got a sample code from ChatGPT regarding Class module as below in bold font but had no idea to implement it onto VBE. I never used the class module in VBA. Please help me to get acquainted with it with a Excel sample file. Thanks.

Let’s create a BankAccount class with three properties (AccountNumber, Balance, and AccountType) and two methods (Deposit and Withdraw). We then create a new instance of the BankAccount class and assign it to the variable myAccount, set its properties, and call its Deposit and Withdraw methods to modify the account balance. Finally, we display the current account balance in a message box.

Public Class BankAccount

    Public AccountNumber As Long

    Public Balance As Double

    Public AccountType As String

    Public Sub Deposit(amount As Double)

        Balance = Balance + amount

    End Sub

    Public Sub Withdraw(amount As Double)

        If amount <= Balance Then

            Balance = Balance - amount

        Else

            MsgBox "Insufficient funds."

        End If

    End Sub

End Class

With this class module, you can create new instances of the BankAccount class and use its properties and methods to manage the account balance.

Dim myAccount As New BankAccount

myAccount.AccountNumber = 123456789

myAccount.AccountType = "Savings"

myAccount.Deposit 1000

myAccount.Withdraw 500

MsgBox "Current balance: " & myAccount.Balance

 
Posted : 20/02/2023 7:59 pm
(@debaser)
Posts: 837
Member Moderator
 

Insert a class module, rename it BankAccount and then paste in this part of the code:

 

    Public AccountNumber As Long

    Public Balance As Double

    Public AccountType As String

    Public Sub Deposit(amount As Double)

        Balance = Balance + amount

    End Sub

    Public Sub Withdraw(amount As Double)

        If amount <= Balance Then

            Balance = Balance - amount

        Else

            MsgBox "Insufficient funds."

        End If

    End Sub

 

Then add a normal module and paste in this:

Sub demo_it()
Dim myAccount As New BankAccount

myAccount.AccountNumber = 123456789

myAccount.AccountType = "Savings"

myAccount.Deposit 1000

myAccount.Withdraw 500

MsgBox "Current balance: " & myAccount.Balance
End Sub

 

and run it.

 

IMO this is quite a lazy implementation as you should use property procedures rather than simple public member variables.

 
Posted : 21/02/2023 5:38 am
(@julian)
Posts: 82
Estimable Member
Topic starter
 

Thanks a lot for leading me to a new learning journey.

 
Posted : 21/02/2023 9:06 pm
Share: