Saturday, May 28, 2011

Calendar/Time Display




Design a window that displays the current month, day, and year.  Also, display the current time, updating it every second (look into the Timer control).  Make the window look something like a calendar page.  Play with object properties to make it pretty.

My Solution:

Form:


Properties:

Form frmCalendar:
            Caption = My Calendar
            BorderStyle = 1 - Fixed Single

Timer timDisplay:
            Interval = 1000

Label lblDay:
            Caption = Sunday
            FontName = Times New Roman
            FontBold = True
            FontSize = 24

Label lblTime:
            Caption = 00:00:00 PM
            FontName = Times New Roman
            FontBold = True
            FontSize = 24

Label lblYear:
            Alignment = 2 - Center
            Caption = 1998
            FontName = Times New Roman
            FontBold = True
            FontSize = 24

Label lblNumber:
            Alignment = 2 - Center
            Caption = 31
            FontName = Arial
            FontBold = True
            FontSize = 72

Label lblMonth:
            Alignment = 2 - Center
            Caption = March
            FontName = Times New Roman
            FontBold = True
            FontSize = 24


Code:

General Declarations:

Option Explicit


timDisplay Timer Event:

Private Sub timDisplay_Timer()
Dim Today As Variant
Today = Now
lblDay.Caption = Format(Today, "dddd")
lblMonth.Caption = Format(Today, "mmmm")
lblYear.Caption = Format(Today, "yyyy")
lblnumber.Caption = Format(Today, "d")
lblTime.Caption = Format(Today, "h:mm:ss ampm")
End Sub






.

Calendar/Time Display


Design a window that displays the current month, day, and year.  Also, display the current time, updating it every second (look into the Timer control).  Make the window look something like a calendar page.  Play with object properties to make it pretty.

My Solution:

Form:


timDisplay
 
lblTime
 
lblYear
 
lblNumber
 
lblMonth
 
lblDay
 



Properties:

Form frmCalendar:
            Caption = My Calendar
            BorderStyle = 1 - Fixed Single

Timer timDisplay:
            Interval = 1000

Label lblDay:
            Caption = Sunday
            FontName = Times New Roman
            FontBold = True
            FontSize = 24

Label lblTime:
            Caption = 00:00:00 PM
            FontName = Times New Roman
            FontBold = True
            FontSize = 24

Label lblYear:
            Alignment = 2 - Center
            Caption = 1998
            FontName = Times New Roman
            FontBold = True
            FontSize = 24

Label lblNumber:
            Alignment = 2 - Center
            Caption = 31
            FontName = Arial
            FontBold = True
            FontSize = 72

Label lblMonth:
            Alignment = 2 - Center
            Caption = March
            FontName = Times New Roman
            FontBold = True
            FontSize = 24


Code:

General Declarations:

Option Explicit


timDisplay Timer Event:

Private Sub timDisplay_Timer()
Dim Today As Variant
Today = Now
lblDay.Caption = Format(Today, "dddd")
lblMonth.Caption = Format(Today, "mmmm")
lblYear.Caption = Format(Today, "yyyy")
lblnumber.Caption = Format(Today, "d")
lblTime.Caption = Format(Today, "h:mm:ss ampm")
End Sub

Thursday, May 26, 2011

Stopwatch Application - Attaching Code




All that’s left to do is attach code to the application.  We write code for every event a response is needed for.  In this application, there are three such events:  clicking on each of the command buttons.

1.      Double-click anywhere on the form to open the code window.  Or, select ‘View Code’ from the project window.

2.      Click the down arrow in the Object box and select the object named (general).  The Procedure box will show (declarations).  Here, you declare three form level variables:

Option Explicit
Dim StartTime As Variant
Dim EndTime As Variant
Dim ElapsedTime As Variant

The Option Explicit statement forces us to declare all variables.  The other lines establish StartTime, EndTime, and ElapsedTime as variables global within the form.

3.      Select the cmdStart object in the Object box.  If the procedure that appears is not the Click procedure, choose Click from the procedure box.  Type the following code which begins the timing procedure.  Note the Sub and End Sub statements are provided for you:

Sub cmdStart_Click ()
‘Establish and print starting time
StartTime = Now
lblStart.Caption = Format(StartTime, "hh:mm:ss")
lblEnd.Caption = ""
lblElapsed.Caption = ""
End Sub

In this procedure, once the Start Timing button is clicked, we read the current time and print it in a label box.  We also blank out the other label boxes.  In the code above (and in all code in these notes), any line beginning with a single quote () is a comment.  You decide whether you want to type these lines or not.  They are not needed for proper application operation.

4.      Now, code the cmdEnd button. 

Sub cmdEnd_Click ()
‘Find the ending time, compute the elapsed time
‘Put both values in label boxes
EndTime = Now
ElapsedTime = EndTime - StartTime
lblEnd.Caption = Format(EndTime, "hh:mm:ss")
lblElapsed.Caption = Format(ElapsedTime, "hh:mm:ss")
End Sub

Here, when the End Timing button is clicked, we read the current time (End Time), compute the elapsed time, and put both values in their corresponding label boxes.

5.      And, finally the cmdExit button.

Sub cmdExit_Click ()
End
End Sub

This routine simply ends the application once the Exit button is clicked.

6.      Did you notice that as you typed in the code, Visual Basic does automatic syntax checking on what you type (if you made any mistakes, that is)?

7.      Run your application by clicking the Run button on the toolbar, or by pressing <f5>.  Pretty easy, wasn’t it?

8.      Save your application - see the Primer on the next page.  Use the Save Project As option under the File menu.  Make sure you save both the form and the project files.

If you have the time, some other things you may try with the Stopwatch Application:

A.     Try changing the form color and the fonts used in the label boxes and command buttons.

B.     Notice you can press the ‘End Timing’ button before the ‘Start Timing’ button.  This shouldn’t be so.  Change the application so you can’t do this.  And make it such that you can’t press the ‘Start Timing’ until ‘End Timing’ has been pressed.  Hint:  Look at the command button Enabled property.

C.    Can you think of how you can continuously display the ‘End Time’ and ‘Elapsed Time’?  This is a little tricky because of the event-driven nature of Visual Basic.  Look at the Timer tool.  Ask me for help on this one.



Quick Primer on Saving Visual Basic Applications:

When saving Visual Basic applications, you need to be concerned with saving both the forms (.FRM) and modules (.BAS) and the project file (.VBP).  In either case, make sure you are saving in the desired directory.  The current directory is always displayed in the Save window.  Use standard Windows techniques to change the current directory.

There are four Save commands available under the File menu in Visual Basic:

Save [Form Name]            Save the currently selected form or module with the current name.  The selected file is identified in the Project window.
Save [Form Name] As      Like Save File, however you have the option to change the file name
Save Project                       Saves all forms and modules in the current project using their current names and also saves the project file.
Save Project As                 Like Save Project, however you have the option to change file names.  When you choose this option, if you have not saved your forms or modules, you will also be prompted to save those files.  I always use this for new projects.

Wednesday, May 25, 2011

Visual Basic Functions



Visual Basic offers a rich assortment of built-in functions.  The on-line help utility will give you information on any or all of these functions and their use.  Some examples are:

            Function       Value Returned

            Abs                 Absolute value of a number

            Asc                 ASCII or ANSI code of a character

            Chr                 Character corresponding to a given ASCII or ANSI code

            Cos                 Cosine of an angle

            Date                Current date as a text string

            Format            Date or number converted to a text string

            Left                 Selected left side of a text string

            Len                 Number of characters in a text string

            Mid                  Selected portion of a text string

            Now                Current time and date

            Right              Selected right end of a text string

            Rnd                Random number

            Sin                  Sine of an angle

            Sqr                  Square root of a number

            Str                   Number converted to a text string

            Time               Current time as a text string

            Timer              Number of seconds elapsed since midnight

            Val                  Numeric value of a given text string





.

Sunday, May 22, 2011

Synchronizing the Drive, Directory, and File List Boxes Example


Savings Account - Decisions


1.   Here, we modify the Savings Account project to allow entering any three values and computing the fourth.  First, add a third command button that will clear all of the text boxes. Assign the following properties:
     
            Command3:
                        Caption                      Clear &Boxes
                        Name                         cmdClear
     
      The form should look something like this when you’re done:

     
     
     
2.   Code the cmdClear button Click event:
     
      Private Sub cmdClear_Click ()
      ‘Blank out the text boxes
      txtDeposit.Text = ""
      txtInterest.Text = ""
      txtMonths.Text = ""
      txtFinal.Text = ""
      End Sub

This code simply blanks out the four text boxes when the Clear button is clicked.


3.      Code the KeyPress event for the txtFinal object:

Private Sub txtFinal_KeyPress (KeyAscii As Integer)
      ‘Only allow number keys, decimal point, or backspace
      If (KeyAscii >= vbKey0 And KeyAscii <= vbKey9) Or KeyAscii = vbKeyDecPt Or KeyAscii = vbKeyBack Then
      Exit Sub
Else
  KeyAscii = 0
  Beep
End If
End Sub

We need this code because we can now enter information into the Final Value text box.

4.      The modified code for the Click event of the cmdCalculate button is:



Private Sub cmdCalculate_Click()
Dim IntRate As Single
Dim IntNew As Single
Dim Fcn As Single, FcnD As Single
‘Read the four text boxes
Deposit = Val(txtDeposit.Text)
Interest = Val(txtInterest.Text)
IntRate = Interest / 1200
Months = Val(txtMonths.Text)
Final = Val(txtFinal.Text)
‘Determine which box is blank
‘Compute that missing value and put in text box
If txtDeposit.Text = "" Then
‘Deposit missing
  Deposit = Final / (((1 + IntRate) ^ Months - 1) / IntRate)
  txtDeposit.Text = Format(Deposit, "#####0.00")
ElseIf txtInterest.Text = "" Then
‘Interest missing - requires iterative solution
  IntNew = (Final / (0.5* Months * Deposit) - 1) / Months
  Do
    IntRate = IntNew
    Fcn = (1 + IntRate) ^ Months - Final * IntRate / Deposit - 1
    FcnD = Months * (1 + IntRate) ^ (Months - 1) - Final / Deposit
    IntNew = IntRate - Fcn / FcnD
  Loop Until Abs(IntNew - IntRate) < 0.00001 / 12
  Interest = IntNew * 1200
  txtInterest.Text = Format(Interest, "##0.00")
ElseIf txtMonths.Text = "" Then
‘Months missing
  Months = Log(Final * IntRate / Deposit + 1) / Log(1 + IntRate)
  txtMonths.Text = Format(Months, "###.0")
ElseIf txtFinal.Text = "" Then
‘Final value missing
  Final = Deposit * ((1 + IntRate) ^ Months - 1) / IntRate
  txtFinal.Text = Format(Final, "#####0.00")
End If
End Sub       

In this code. we first read the text information from all four text boxes and based on which one is blank, compute the missing information and display it in the corresponding text box.  Solving for missing Deposit, Months, or Final information is a straightforward manipulation of the equation given in Example 2-2.

If the Interest value is missing, we have to solve an Mth-order polynomial using something called Newton-Raphson iteration - a good example of using a Do loop.  Finding the Interest value is straightforward.  What we do is guess at what the interest is, compute a better guess (using Newton-Raphson iteration), and repeat the process (loop) until the old guess and the new guess are close to each other.  You can see each step in the code.

5.      Test and save your application.  Go home and relax.




.

Saturday, May 21, 2011

Synchronizing the Drive, Directory, and File List Boxes




·         The drive, directory, and file list boxes are almost always used together to obtain a file name.  As such, it is important that their operation be synchronized to insure the displayed information is always consistent.

·         When the drive selection is changed (drive box Change event), you should update the directory path.  For example, if the drive box is named drvExample and the directory box is dirExample, use the code:

dirExample.Path = drvExample.Drive

·         When the directory selection is changed (directory box Change event), you should update the displayed file names.  With a file box named filExample, this code is:

filExample.Path = dirExample.Path

·         Once all of the selections have been made and you want the file name, you need to form a text string that correctly and completely specifies the file identifier.  This string concatenates the drive, directory, and file name information.  This should be an easy task, except for one problem.  The problem involves the backslash (\) character.  If you are at the root directory of your drive, the path name ends with a backslash.  If you are not at the root directory, there is no backslash at the end of the path name and you have to add one before tacking on the file name. 

·         Example code for concatenating the available information into a proper file name and then loading it into an image box is:

Dim YourFile as String

If Right(filExample.Path,1) = "\" Then
  YourFile = filExample.Path + filExample.FileName
Else
  YourFile = filExample.Path + "\" + filExample.FileName
End If
imgExample.Picture = LoadPicture(YourFile)

Note we only use properties of the file list box.  The drive and directory box properties are only used to create changes in the file list box via code.



.

Wednesday, May 18, 2011

Visual basic List Boxes

        1. Drive List Box





·         The drive list box control allows a user to select a valid disk drive at run-time.  It displays the available drives in a drop-down combo box.  No code is needed to load a drive list box; Visual Basic does this for us.  We use the box to get the current drive identification.

·         Drive List Box Properties:

Drive                     Contains the name of the currently selected drive.

·         Drive List Box Events:

Change               Triggered whenever the user or program changes the drive selection.




         2.    Directory List Box






·         The directory list box displays an ordered, hierarchical list of the user's disk directories and subdirectories.  The directory structure is displayed in a list box.  Like, the drive list box, little coding is needed to use the directory list box - Visual Basic does most of the work for us.

·         Directory List Box Properties:

Path                       Contains the current directory path.

·         Directory List Box Events:

Change                  Triggered when the directory selection is changed.


  
           3.   File List Box



·         The file list box locates and lists files in the directory specified by its Path property at run-time.  You may select the types of files you want to display in the file list box.

·         File List Box Properties:

FileName                Contains the currently selected file name.
Path                       Contains the current path directory.
Pattern                   Contains a string that determines which files will be displayed.  It supports the use of * and ? wildcard characters.  For example, using *.dat only displays files with the .dat extension.

·         File List Box Events:

DblClick                 Triggered whenever a file name is double-clicked.
PathChange           Triggered whenever the path changes in a file list box.

·         You can also use the MultiSelect property of the file list box to allow multiple file selection.


.