December 12, 2016
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
Trusted Members
Moderators
November 1, 2018
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.
Answers Post
1 Guest(s)