Variable Declaration
eg. f_Age as Integer
The concepts of declaring variables in events, forms or modules will be discussed in the Scope of Variables section.
NOTE: for smaller programs we will be declaring variables in forms or in objects programs. For larger programs with multiple forms we will declare variables in modules.
See Appendix A for a list of Reserved Words.
Examples of Proper Variable Declarations
Valid Variable Name |
Invalid |
Reason for Invalidity |
f_Hourswkd |
Hours |
hours is a reserved word |
f_Salary97 |
97Salary |
name must not begin with a number |
c_Discount_Price |
Discount Price |
name cannot contain a space |
c_FirstName |
Name |
reserved word |
m_FireDepartment |
Fire.Department |
name cannot contain punctuation |
The Dim Statement for Data Types
Before a variables is declared programmers must include the Dim syntax. This indicates to the program that the variables value could change as the program runs.
Syntax
Variable Declaration in an Event:
Dim <NameYouCreate> as Data Type
Variable Declaration in a form's General Declarations:
Dim <f_NameYouCreate> as Data Type
Variable Declaration in a module's General Declarations:
Dim <m_NameYouCreate> as Data Type
Examples
Dim CanadianDollar as Currency
Dim f_ Year as Integer
Dim m_FirstName as String
Dim CorrectAnswer as Boolean
Dim f_Temperature as Long
Dim m_FractionCalc as Single
Dim f_TheCalculation ' this makes f_TheCalculation have the variant data type.
The variant data type takes up a lot of space in memory. It is not good programming practice to declare variables with the variant data type.
You can also declare variables on the same line. It is good programming practice to keep all the same variables of the same data type on the same line.
Dim NumberofDays as Integer, HoursWorked as Integer
Dim m_FirstName as String, m_MiddleName as String, m_LastName as String
Dim f_TaxRate as Integer, f_Subtotal as Integer, f_Total As Integer
The Scope of Variables
Variables may be declared in the following levels in Visual Basic:
Variable Type |
variable name = expression |
Description |
Event |
Dim Fname as Type |
declared in any procedure. |
Form |
Dim f_Fname as Type |
in any procedure. |
Module |
Public m_Fname as Type |
in declaration section of a module, cannot be declared anywhere. |
Variable Assignment Statements
The easiest way to create a variable is to assign a value to the variable's name in a code statement.
An assignment statement assigns a value to the property of an control/object. After the period is the property of the object followed by the equal sign and the value. The value could be a variable or a piece of information.
Syntax
<Object.Property> = <value property >
EXAMPLE |
CHANGES THE... |
txtLname.Text = "Jones" |
the text displayed in the text box to Jones |
HourlyIncome = 10.55 |
|
f_FirstName = "John" |
|
g_PresentAge = 16 |
|
Variables can either hold numbers called numeric data or characters called string data. String data must be placed in quotation marks. Numeric data need not be in quotation marks.
Variables can also be assigned to the value of another variable, the value of an object/control or the value of a mathematical expression.
txtHourlyIncome.Text = f_HourlyIncome
If you prefer output to be tested you can print any output on the form. All you need to do is separate the variables or anything as text with a semi-colon. Remember that variables need not have quotes around them, but the programmers setup must.
For example:
print "The "; f_Chlorine ; "is too high and the"; f_AlgaeCount ; "is normal."
Visual Basic Variable Declaration Exercises
Activity 2.2.1
Variable Declaration |
Explanation |
Correction or Better Choice |
Dim Name as Integer |
|
|
Dim m_FirstName as Integer |
|
|
Dim m_Money Earned as Integer |
|
|
Dim f_Currency as String |
|
|
Dim f_ Person as String |
|
|
Dim m_Name as String |
|
|
Dim GoldbachNo as Integer |
|
|
Dim m_PizzaOrder |
|
|
Dim !Factorial as Double |
|
|
Dim m_Chemicalppms as Double |
|
|
Dim x, y, z as Integer |
|
|
Dim m_Num1 as Integer, m_Num2 as Integer |
|
|
txtCarPayment.txt = m_CarPayment |
|
|
TextOrderNum.Text = m_OrderNum |
|
|
txtCarPayment.txt = m_CarPayment |
|
|
Distance = txtDistance |
|
|
print "Show me the $ "; m_Money "!!!" |
|
|
m_FibonacciNum = "45" |
|
|
Activity 2.2.2
TOPICS: Variable Text Boxes, Label Boxes, Command Boxes and the Message Box.
PART A
You need to create the following:
Your form should appear similar to the following form:
The following will help you create your program:
Label1
CHANGE THE NAME TO: lblTPersonal
CHANGE THE CAPTION TO: MY PERSONAL INFORMATION
Change the FontSize to 18 point.
Label2
CHANGE THE NAME TO:lblFirst
CHANGE THE CAPTION TO: First Name
Label3
CHANGE THE NAME TO: lblLast
CHANGE THE CAPTION TO: Last Name
Label4
CHANGE THE NAME TO: lblHeight
CHANGE THE CAPTION TO: Height
Label5
CHANGE THE NAME TO: lblHair
Please use American spelling of color, since this is American software.
CHANGE THE CAPTION TO: Hair Colour
Text1 Diagram #1
CHANGE THE NAME TO: txtFirstName
CHANGE THE TEXT TO: null, delete text1
As see in Diagram #1
Text2
CHANGE THE NAME TO: txtLastName
CHANGE THE TEXT TO: delete Text2
Text3
CHANGE THE NAME TO: txtHeight
CHANGE THE TEXT TO: delete Text3
Text4
CHANGE THE NAME TO: txtHairColor
CHANGE THE TEXT TO: delete Text4
Command1
CHANGE THE NAME TO: cmdDisplay
CHANGE THE TEXT TO: DISPLAY
Command2
CHANGE THE NAME TO: cmdClear
CHANGE THE TEXT TO: CLEAR
Command3
CHANGE THE NAME TO: cmdExit
CHANGE THE TEXT TO: E&XIT
Double click on the command button, type in End between the sub and end sub.
REMEMBER!!!
Accessing the general declarations area: double click on the form, beside Object click on the arrow down choose (General), beside Proc click on the arrow down choose (Declarations). You are using f_ because your variables are declared at the form level. This will allow you to use the variables anywhere else in the program.
f_FirstName - string
f_LastName - string
f_Height - integer
f_FirstName = txtFirstName.Text
f_LastName = txtLastName.Text
f_Height = txtHeight.Text
The MessageBox displays one of Visual Basic's predefined dialog boxes.
Example #1
MsgBox txtFirstName.Text
or
MsgBox f_FirstName
This will display your first name in the message box.
For string expressions, you must enclose them in quotations
Example #2
MsgBox "Hello"
Syntax
<ReturnValue> = MsgBox (prompt [,buttons][,title][helpfile][,context]
You can also omit the return value and the equal sign.
If you want to display more than one item in the message box it is possible using the ampersand sign (&) . You can use quotes to type in text and for blank spaces between you name.
Example #3
MsgBox f_FirstName & " " & f_LastName & ". " & "Your height is " & f_Height
NOTE: Make sure that you type the line below in one line. The ampersand (&) sign does not need to be bold and large.
MsgBox f_FirstName & " "& f_LastName & " your height is " & f_Height & " and your hair color is " & f_HairColor & ". "
THE KEY FOR UNDERSTANDING:
" " = a space
". " = a period and a space
" and your hair color is" = a space and your hair color is
Double Click on the cmdClear.
Assign all the variables to a null string to clear the text boxes.
txtFirstName.Text = " "
txtLastName.Text = " "
txtHeight.Text = " "
Remember to add in your hair colour text box.
Run the program use F5.
Save the Form File as: frmVariablePractice
Save the project as: VariablePractice.vbp
What is the output? Note the output word for word and space for space.
If you have syntax errors check cmdDisplay. Make sure you have all the quotes and ampersand signs. Ask a friend in the class for help.
Here is what your output could look like:
Activity 2.2.3
Part B
ENHANCEMENTS:
Add some color to your form by changing the properties of the objects. Change the color of the text boxes and label boxes as well as the text.
See is you can add a label box and a text box for your favorite food. Don't forget to declare the variable for your favorite food and assign it to the text box.
Label6
NAME: lblFood
CAPTION: Favorite Food
Text5
NAME: txtFood
TEXT: delete Text5
Assign the food text box to the variable f_Food. Using the ampersand sign add in f_Food to the code in cmdDisplay. For example:
MsgBox f_FirstName & " "& f_LastName & " your height is " & f_Height & " and your hair color is " & f_HairColor & ". " & "Your favorite food is " & f_Food " ."
Note the output in your computer science binders.
Source: http://www.dpcdsb.org/NR/rdonlyres/D6B8202E-2CFD-4A24-B073-EACFB47E12F5/11505/Chapter2_2.doc
Web site to visit: http://www.dpcdsb.org
Author of the text: not indicated on the source document of the above text
If you are the author of the text above and you not agree to share your knowledge for teaching, research, scholarship (for fair use as indicated in the United States copyrigh low) please send us an e-mail and we will remove your text quickly. Fair use is a limitation and exception to the exclusive right granted by copyright law to the author of a creative work. In United States copyright law, fair use is a doctrine that permits limited use of copyrighted material without acquiring permission from the rights holders. Examples of fair use include commentary, search engines, criticism, news reporting, research, teaching, library archiving and scholarship. It provides for the legal, unlicensed citation or incorporation of copyrighted material in another author's work under a four-factor balancing test. (source: http://en.wikipedia.org/wiki/Fair_use)
The information of medicine and health contained in the site are of a general nature and purpose which is purely informative and for this reason may not replace in any case, the council of a doctor or a qualified entity legally to the profession.
The following texts are the property of their respective authors and we thank them for giving us the opportunity to share for free to students, teachers and users of the Web their texts will used only for illustrative educational and scientific purposes only.
All the information in our site are given for nonprofit educational purposes
The information of medicine and health contained in the site are of a general nature and purpose which is purely informative and for this reason may not replace in any case, the council of a doctor or a qualified entity legally to the profession.
www.riassuntini.com