Tuesday, April 26, 2011

The Messagebox









 
      One of the best functions in Visual Basic is the message box.  The message box displays a message, optional icon, and selected set of command buttons.  The user responds by clicking a button.

     The statement form of the message box returns no value (it simply displays the box):
                 
MsgBox (Message, Type, Title)

where

Message        Text message to be displayed
Type               Type of message box (discussed in a bit)
Title                 Text in title bar of message box

You have no control over where the message box appears on the screen.

      The function form of the message box returns an integer value (corresponding to the button clicked by the user).  Example of use (Response is returned value):

Dim Response as Integer
Response = MsgBox(Message, Type, Title)

·         The Type argument is formed by summing four values corresponding to the buttons to display, any icon to show, which button is the default response, and the modality of the message box.
·         The first component of the Type value specifies the buttons to display:

Value    Meaning                                  Symbolic Constant
0             OK button only                       vbOKOnly
1             OK/Cancel buttons               vbOKCancel
2             Abort/Retry/Ignore buttons   vbAbortRetryIgnore
3             Yes/No/Cancel buttons        vbYesNoCancel
4             Yes/No buttons                      vbYesNo
5             Retry/Cancel buttons            vbRetryCancel

·         The second component of Type specifies the icon to display in the message box:

Value    Meaning                                  Symbolic Constant
0             No icon                                    (None)
16           Critical icon                            vbCritical
32           Question mark                       vbQuestion
48           Exclamation point                 vbExclamation
64           Information icon                    vbInformation

      The third component of Type specifies which button is default (i.e. pressing Enter is the same as clicking the default button):

Value    Meaning                                  Symbolic Constant
0             First button default                vbDefaultButton1
256        Second button default          vbDefaultButton2
512        Third button default              vbDefaultButton3

      The fourth and final component of Type specifies the modality:

Value    Meaning                                  Symbolic Constant
0             Application modal                 vbApplicationModal
4096      System modal                        vbSystemModal

If the box is Application Modal, the user must respond to the box before continuing work in the current application.  If the box is System Modal, all applications are suspended until the user responds to the message box.

      Note for each option in Type, there are numeric values listed and symbolic constants.  Recall, it is strongly suggested that the symbolic constants be used instead of the numeric values.  You should agree that vbOKOnly means more than the number 0 when selecting the button type.

      The value returned by the function form of the message box is related to the button clicked:

Value    Meaning                                  Symbolic Constant
1             OK button selected               vbOK
2             Cancel button selected        vbCancel
3             Abort button selected            vbAbort
4             Retry button selected            vbRetry
5             Ignore button selected          vbIgnore
6             Yes button selected              vbYes
7             No button selected                vbNo


·         Message Box Example:


 .

Predefined Dialog Boxes - Syntex 1. Inputbox(Prompt String,Diolog Title)

Syntex

1. Inputbox(Prompt String,Diolog Title)


The easiest way to add a dialog box to your application is to use a predefined dialog, because you don't have to worry about designing, loading, or showing the dialog box. However, your control over its appearance is limited. Predefined dialog boxes are always modal.
The following table lists the functions you can use to add predefined dialog boxes to your Visual Basic application.





Use this function
To do this
InputBox function
Display a command prompt in a dialog box, and return whatever is entered by the user.
MsgBox function
Display a message in a dialog box, and return a value indicating the command button was clicked by the user.






   .
   .

 Prompting for Input with InputBox


Use the InputBox function to solicit data from the user. This function displays a modal dialog box that asks the user to enter some data. The text input box prompts the user for the name of the file to open.
The following code displays the input box 


FileName = InputBox("Enter file to open:", "File Open")


Note   Remember that when you use the InputBox function, you have little control over the components of the dialog box. You can change only the text in the title bar, the command prompt displayed to the user, the position of the dialog box on the screen, and whether or not it displays a Help button.



.

Data types

Data types

Integer
Long
Single
double
Currancy       -Number with fixed decimal point of four position
Byte                -Store 0 to 255 one character
Date                -Store dates and times
String             -Strore textual data
Boolean         -Store boolean value true false
Varient           -Can Store any of the above

Constant value
is a fixed value
Declaration
const pi=3.141593

Data Type                    Suffix
Boolean                        None
Integer                           %
Long (Integer)              &
Single (Floating)         !
Double (Floating)        #
Currency                      @
Date                               None
Object                            None
String                            $
Variant                          None

Example of Variable Scope



Procedure Routine1 has access to X, Y, and A (loses value upon termination)
Procedure Routine2 has access to X, Y, and B (retains value)
Procedure Routine3 has access to X, Z, and C (loses value)

Variable Declaration - 3. Explicitly


There are many advantages to explicitly typing variables.  Primarily, we insure all computations are properly done, mistyped variable names are easily spotted, and Visual Basic will take care of insuring consistency in upper and lower case letters used in variable names.  Because of these advantages, and because it is good programming practice, we will explicitly type all variables.


To explicitly declare variables
Type
Option Explicit -  in the Declarations section of a class, form, or standard module:
–or–
From the Tools menu, choose Options, click the Editor tab and check the Require Variable Declaration option. This automatically inserts the Option Explicit statement in any new modules, but not in modules already created; therefore, you must manually add Option Explicit to any existing modules within a project.

   To explicitly type a variable, you must first determine its scope.  There are four levels of scope:

·          Procedure level
·          Procedure level, static
·          Form and module level
·          Global level

   Within a procedure, variables are declared using the Dim statement:

Dim MyInt as Integer
Dim MyDouble as Double
Dim MyString, YourString as String

Procedure level variables declared in this manner do not retain their value once a procedure terminates.

    To make a procedure level variable retain its value upon exiting the procedure, replace the Dim keyword with Static:

Static MyInt as Integer
Static MyDouble as Double

   Form (module) level variables retain their value and are available to all procedures within that form (module).  Form (module) level variables are declared in the declarations part of the general object in the form's (module's) code window.  The Dim keyword is used:

Dim MyInt as Integer
Dim MyDate as Date

   Global level variables retain their value and are available to all procedures within an application.  Module level variables are declared in the declarations part of the general object of a module's code window.  (It is advisable to keep all global variables in one module.)  Use the Global keyword:

Global MyInt as Integer
Global MyDate as Date

·         What happens if you declare a variable with the same name in two or more places?  More local variables shadow (are accessed in preference to) less local variables.  For example, if a variable MyInt is defined as Global in a module and declared local in a routine MyRoutine, while in MyRoutine, the local value of MyInt is accessed.  Outside MyRoutine, the global value of MyInt is accessed.


Variable Declaration - 2. Implicit

To implicitly type a variable, use the corresponding suffix shown above in the data type table.  For example,

creates a string variable
TextValue$ = "This is a string"


creates an integer variable.
Amount% = 300


Do  not need declare variable before use it

Private Sub Command1_Click()
    ProName = "Book"
    Quantity = 20
    ProCode = "Al001"
    SalesPrice = 200.75
    Tax = 50
    Total = Quantity * SalesPrice + Tax
    Debug.Print "Proname", "Quantity", "SalesPrice", "Total Price"
    Debug.Print ProName, Quantity, SalesPrice, Total
End Sub

Output

Proname         Quantity         SalesPrice    Total Price
Book                20                    200.75            4065

Note

Visual Basic automatically creates a variable with that name, which you can use as if you had explicitly declared it. While this is convenient, it can lead to subtle errors in your code if you misspell a variable name.


Private Sub Command1_Click()
ProName = "Book"
      Quantity = 20
      ProCode = "Al001"
      SalesPrice = 200.75
      Tax = 50
      Total = Quantity * SalesPrice + Txa
      Debug.Print "Proname", "Quantity", "SalesPrice", "Total Price"
      Debug.Print ProName, Quantity, SalesPrice, Total
End Sub

eg.
Proname     Quantity     SalesPrice       Total
Book             20                200.75            4015

Variable Declaration -1 . Default


Dim variablename
Variables declared with the Dim statement within a procedure exist only as long as the procedure is executing. When the procedure finishes, the value of the variable disappears. In addition, the value of a variable in a procedure is local to that procedure — that is, you can't access a variable in one procedure from another procedure. These characteristics allow you to use the same variable names in different procedures without worrying about conflicts or accidental changes.

Static Variables declaration

Static <variablename >

Variables have a lifetime, the period of time during which they retain their value. The values in module-level and public variables are preserved for the lifetime of your application. However, local variables declared with Dim exist only while the procedure in which they are declared is executing. Usually, when a procedure is finished executing, the values of its local variables are not preserved and the memory used by the local variables is reclaimed. The next time the procedure is executed, all its local variables are reinitialized.
However, you can preserve the value of a local variable by making the variable static. Use the Static keyword to declare one or more variables inside a procedure, exactly as you would with the Dim statement:
Eg
Static Depth 

If variables are not implicitly or explicitly typed, they are assigned the variant type by default.  The variant data type is a special type used by Visual Basic that can contain numeric, string, or date data.

     
Private Sub Command1_Click()
    Dim ProName
    Dim Quantity, ProCode, Slaesprice
    ProName = "Book"
    Quantity = 200
    ProCode = "Al001"
    Salesprice = 2000.75
    Debug.Print ProName; Quantity, ProCode, Salesprice
End Sub

Output
Book 200      Al001          2000.75


Variables


·         We’re now ready to attach code to our application.  As objects are added to the form, Visual Basic automatically builds a framework of all event procedures.  We simply add code to the event procedures we want our application to respond to.  But before we do this, we need to discuss variables. 

·         Variables are used by Visual Basic to hold information needed by your application.  Rules used in naming variables:

A variable name:
·          Must begin with a letter.
·          Must not exceed 255 characters
·          Can't contain an embedded period or embedded type-declaration character.
·          Must be unique within the same scope, which is the range from which the variable can be referenced — a procedure, a form, and so on.
·          They may include letters, numbers, and underscore (_)
·          You cannot use a reserved word (word needed by Visual Basic)

Comment


Comment statements begin with the keyword Rem or a single quote (').  For example:
     
Rem This is a remark
' This is also a remark
x = 2 * y ' another way to write a remark or comment

You, as a programmer, should decide how much to comment your code.  Consider such factors as reuse, your audience, and the legacy of your code.

Visual Basic Statements and Expressions


    The simplest statement is the assignment statement.  It consists of a variable name, followed by the assignment operator (=), followed by some sort of expression.
     
      Examples:
     
            StName="Saman"
            Speed=60
            Energy = Mass * LIGHTSPEED ^ 2
            NetWorth = Assets - Liabilities
     
The assignment statement stores information.

·         Statements normally take up a single line with no terminator.  Statements can be stacked by using a colon (:) to separate them.  Example:

StartTime = Now : EndTime = StartTime + 10

(Be careful stacking statements, especially with If/End If structures.  You may not get the response you desire.)
     
·         If a statement is very long, it may be continued to the next line using the continuation character, an underscore (_).  Example:

Months = Log(Final * IntRate / Deposit + 1) _
/ Log(1 + IntRate)

Handling some of the common controls

 The Text Box    

The text box is the standard control that is used to receive input from the user as well as to display the output. It can handle string (text) and numeric data but not images or pictures. String in a text box can be converted to a numeric data by using the function Val(text). The following example illustrates a simple program that processes the inputs from the user.

 Example 

In this program, two text boxes are inserted into the form together with a few labels. The two text boxes are used to accept inputs from the user and one of the labels will be used to display the sum of two numbers that are entered into the two text boxes. Besides, a command button is also programmed to calculate the sum of the two numbers using the plus operator. The program use creates a variable sum to accept the summation of values from text box 1 and text box 2.The procedure to calculate and to display the output on the label is shown below. The output is shown in bellow 

Private Sub Command1_Click()
‘To add the values in text box 1 and text box 2
Sum = Val(Text1.Text) + Val(Text2.Text)
‘To display the answer on label 1
Label1.Caption = Sum

End Sub 







The Label     

The label is a very useful control for Visual Basic, as it is not only used to provide instructions and guides to the users, it can also be used to display outputs. One of its most important properties is Caption. Using the syntax label.Caption, it can display text and numeric data . You can change its caption in the properties window and also at runtime.  

The Command Button 

The command button is a very important control as it is used to execute commands. It displays an illusion that the button is pressed when the user click on it. The most common event associated with the command button is the Click event, and the syntax for the procedure is
Private Sub Command1_Click ()
Statements
Statements
Statements
Statements
End Sub

How Names are Used in Object Events




    The names you assign to objects are used by Visual Basic to set up a framework of event-driven procedures for you to add code to.  The format for each of these subroutines (all object procedures in Visual Basic are subroutines) is:

Sub ObjectName_Event (Optional Arguments)
            .
            .
End Sub

    Visual Basic provides the Sub line with its arguments (if any) and the End Sub statement.  You provide any needed code.


In the Caption properties of the three command buttons, notice the ampersand (&).  The ampersand precedes a button's access key.  That is, in addition to clicking on a button to invoke its event, you can also press its access key (no need for a mouse).  The access key is pressed in conjunction with the Alt key.  Hence, to invoke 'Begin Timing', you can either click the button or press Alt+B.  Note in the button captions on the form, the access keys appear with an underscore (_).