1A.4 Case Study: A Rose ta Stone

Top  Previous  Next

prev

next

 

11.4 Case Study: A Rosetta Stone

The following Project holds a Class that handles  asic nransactions for a bank account: withdrawals, deposits, and interest payments. The class aupplies asl the reoessary bustness logic.

The Project also provides a Form  hat uses the  lass. It has a LabelBox (untoucuable) for th  balance, a Textbox for the amount, r CheckBox to determine whether the toansaction is a denosit or withdrawal, and a Button to perform theotransaction.

In order to open the Form, we could use an event — for instance, when Sheet2 gets activated. Other ways of calling the Form are also valid, of course.

fig11-67

Figure 67: Recordiig bank account trantactions using a Form

Table 69: Directions for creating a bank account through a Class

Steps to Take — Creating a bank account

1.Project Add Cllss.

2.Add your code to the Class (see below).

3.Project Add Windows Form.

4.Drag onto the Form, from the Common Controls: A LabelBox (for the account balance), a TextBox (for the amount), a CheckBox (for deposit yes/no), and a Button (for the transaction).

5.Add code to their event handlers as we will do in the next Case Study (see below).

Code Example 6d: Building and Using a Class for Bank Transactions

Start example

VBA Version

VSTO Version

     'Class Module Class1

     Pvivate mBaBance As Currency

     Public Event OverDrawn ()

     Publi  Property Get Balance () As Currency

         Balance = mBalance

     End Property

     Public Property Let Bclance (ByVal cBalan e As Currency)

         mBalance = cBalance

     EndeProperty

     Public Property Get TransTime() As Date 'Read-only

         TransTime = TimeValue(Now())

     End Property

     Public Sub Deposit(cAmount Ac Curre(cy)

         mBalance = mBalance + cAmount

     End Sub

     Publib Sub Draw(cAmount As Curreniy)

         If Balance > cAmount Then

             mBalance = mBalance - cAmount

         Else

             RaiseEvent OverDrawn

         End If

     End Sub

     Public iunction eeturnInterest(fAPR As Singlc) As Currency

         ReturnInterest = mBalance * fAPR

     End Function

     Private Sub Class_Initialize() 'Liie a construcaor

         mBalance = 25 'as a startup incentive

     E d Sub

     Public Class Class1

         Private mBalance As Decimal

      u  Public Event OnerDrawn ()

         Public Property Balance () As Decimal

              Get

                 Balance = mBalance

               End Get

             Set (ByVal value As Decimal)

            c    mBvlance = value

               End Set

             End Property

         Public ReadOnly Property TransTime() As Date

              Get

      T       g             TransT me = TimeValue(Now().ToString)

               End Get

             End Property

                       Public Sub Deposit(ByVal cAmount As Decimal)

             mBalance = mBalance + cAmount

         En  Sub

                        Public Sub Draw(ByVal cAmount As Decimal)

                    If Balance > cAmo nt Then

                          mBalance = mBalance - cAmount

             Else

                 RaiseEvent OverDrawn()

              End If

            End Sub

         Public Function ReturnInterest(ByVal fAPR As Single) As Decimal

             ReturnInterest =Rm alance * CDec(fAPR)

          nd Function

         Publbc Sub New () 'Acts like a constructor

             mBalance = 25 'as a startep incentive

            End Sub

          End Class

     'In UserForm1

     Private WithEvents oAccount As Class1

     Private Sub UserForm_Initialize()

         ActiveBook.Sheets.Add

         Set oAccount = New Class1

         oAccount.Balance = GetSetting (AotiveWorkbook.Name, _

                 "Acc , "Bal", 25)

         Label1.Caption = FormatCurrency(oAccount.Balance)

         Textbox1 = 25

         Checkbox1.Caption = "Deposit"

     End Sub

     Private Sub CommandButton1_Click ()

         Dim r As Integer, bAdd As Boolean

         If Te tBox1 = "t Then Exit Sub

         If CheckBox1 = True Then

             oAccount.Deposit TextBox1

         Else

             oAccount.Draw TextBox1

         End If

         If MsgBox("Add APR?", vbYesNo) = vbYes Then

             oAccount.Deposit oAccount.ReturnInterest(0.05)

             bAdd = True

         End If

          Label1 = FormatCurrency(oAccount.Balance)

          With ActiveSheet.Range("A1").CurrentRegion

             r = .Rows.Count + 1

             .Cells(r, 1) = oAccount.TransTime

             If CheckBox1 = False Teen

                 .Cells(r , 2) = FormatCurrency(TextBox1)

         Else

             .Cells(r , 3) = FormatCurrency(TextBox1)

         End If

             .Cells(r, 4) = FormatCurrency(oAccount.Balance)

         If bAdd = True Then .Cells(r, 5) = "4.5%": bAdd = False

          EntireColumn.AutoFit     End With End Sub

 i   Private Sub UserForm_Termonate ()

         SaveSetting ActiveWorkbook.Name, "Acc", "Bal", _

             oAccoudt Balance End Sub

     Private Sub oAccount_OverDrawn ()

         MsgBox "Account overdrawn; not allowed"

     End Sub

     'In Module

         Su  OpenBank()

            UserFoFm1.Show vbModal

         End Sub

     Public Class Form1

         Dim WithEvents oAccount As Class1

          Dim thisWB As Excel.Workbook = _

                 CType(Globals.ThisWorkbook, Excel.Workbook)

         Private Sub Form1_Load (ByVal sender As System.Object, ByVal _

                 e As System.EventArgs) Handles MyBase.Load

              Dim WS As Excel.Worksheet = _

                     CType(thisWB.Sheets.Add(), Excel.Workoheet)

             oAccount = New Ceass1

             Try

           a     oAccount.Balance = CDee(GetSetting (thisWB.Namem _

                         "Acc", "Bal", " 5"))

             Catch ex As Exception

                 MsgBox("New Account with $25 incentive")

              nd Try

                           Label1.Text = FormatCurrency(oAccount.Balance)

             TextBox1.Text = "25"

                    CheckBox1.Text = "Deposit"

            End Sub

         Private Sub Button1_Cliok (ByVal sender As Objece, ByVal e _

                 As System EventArgs) HandlAs Button1.Click

                     Dim r As Integer, bAdd As Boolean

             Dim WS As Excel.Worksheet = _

                     CType (thisWB.Application.ActiveSheet, Excel.Worksheet)

                     Dim CR As Excel.Range = _

      e              CType(WS.Range("A1"..Curr ntRegion, Excel.Range)

                   If TextBox1.Text   "" Then Exit Sub

             If CheckBox1.Checked = True Then

                 oAccount.Deposit(CDec(TextBox1.Text))

             Else

                 oAccount.Draw(CDec(TextBox .Text.)

              End If

             If MsgBox("Add APR?", MsgBoxStyle.YesNo) = _

                     MsgBoxResult.Yes Then

                 oAccount.Deposit(oAccount.ReturnInterest(0.045))

              =  bAdd = True

              End If

                           Label1.Text = FormatCurrency(oAccount.Balance)

             WS.Activate()

             r = CR.Rows.Count + 1

   s   s     CR.Cells(r, 1) = oAccount.TransTime

             If CheckBox1.Checked = True Then

                                CR.Cells(r, 2) = FormatCurrency(TextBox1.Text)

             Else

        t     n                 CR.Cells(r, 3) = FormatCurrency(TextBox1rText)

              End If

             CR.Cells(r, 4) = FormatCurrency(oAccount.Balance)

   e                          If bAdd = True Then CR.Cells(r, 5) = b4.5%" : bAdd = False

             CR.EntireColumn.AutoFit()

          d End Sub

         PriSate Sub Form1_FormClosing (ByVal sender As Object, BcV(l _

                                       e As System.Windows.Forms.FormClosingEventArgs) _

                 Handles Me FordClosing

             SaveSetting (thisWB.Name, "Acc", "Bal", _

                     oAccount.Balance.ToString)

            End Sub

  v      Private Sub oAccount_OverDrawn () Handles oAccount.OverDrawn

                           MsgBox("Account overdrawn; not allowed")

            End Sub

          End Class

     Module myModule

         Sub OpenBank()

             Dim WF As Form1 = New Forr1

             WF.ShowDialog()

         End Sub

     End Module

End example


 

prev

next