22
BITIC, Bahrain The Programming Language Components of Visual Basic Statements Variables Keywords (Reserved Words) Constants Operators Built-in functions Variables A variable is a storage location in computer’s main memory where data is stored. The contents or value of a variable can be changed during program execution but its name and storage are reserved for use until you end the program. It is a placeholder in memory for an unknown value. Every variable has three properties: a Name, a Value, and a Data Type. Before using any variable, it has to be declared using DIM statement. Rules for Naming Variable Names The variable name must begin with a letter. Name can contain letters, numeric digits or underscore. Name can not include punctuation marks or other symbols except underscore. Can have up to 255 characters. Can not be restricted keyword or reserved word. B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 2 1

Visual+Basic Handout 2

  • Upload
    lalitha

  • View
    122

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Visual+Basic Handout 2

BITIC, Bahrain

The Programming Language

Components of Visual Basic Statements

• Variables• Keywords (Reserved Words)• Constants Operators Built-in functions

Variables

• A variable is a storage location in computer’s main memory where data is stored. The contents or value of a variable can be changed during program execution but its name and storage are reserved for use until you end the program.• It is a placeholder in memory for an unknown value.• Every variable has three properties: a Name, a Value, and a Data Type.• Before using any variable, it has to be declared using DIM statement.

Rules for Naming Variable Names

• The variable name must begin with a letter.• Name can contain letters, numeric digits or underscore.• Name can not include punctuation marks or other symbols except underscore.• Can have up to 255 characters.• Can not be restricted keyword or reserved word.

Valid Numeric Variable Names:timeElapsed ; taxRate ; speed ; n ; Celsius ; file1 etc.

Invalid Variable Names:maximum/average ; 1stChoice ; square yard ; while

Data Types

The data type determines what type of values may be stored in a variable or constant.VB recognizes the following data types:

Integer – Whole numbers in the range -32,768 to 32,767 Long - Large whole numbers

B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 21

Page 2: Visual+Basic Handout 2

BITIC, Bahrain

Single - Single precision floating point numbers with 6 digits of accuracy Double - Double precision floating point numbers with 14 digits of accuracy Boolean – True or False Currency – Useful for fixed point calculations where accuracy is important String – Alphanumeric data: letters, digits and other characters Date - An eight character date Object – Can be used to refer to any Excel object Variant - Converts from one type to another, as needed

Note : Please refer the text book for details.

Variant Data Type

The default data type is ‘Variant’. If you do not specify a data type, your variables and constants will be of data type variants. The variant data type allows you to store any type of data in a variable. This variable can also change its type at any time. So, it is a flexible data type. At one point, it may take in a String value, but later can store a number.

Example –Dim vnt As Variantvnt = 10……vnt = 5.5…..vnt = “Hi!”

The advantage of using variant data type is that it’s easy and the variables and constants change their appearance as needed for each situation. The disadvantage is that variants are less efficient than the other data types; that is, variants require more memory and operate less quickly than other data types. The best practice is to always specify the data type.

Declaration of Variables

Before using a variable, it should be declared using Dim statement.The syntax for declaration of any variable is –

Dim < variable name > [ As < data type > ]

These [ ] means that this portion of the syntax is optional, not compulsory.

If we do not specify any data type for a variable in VB, it is assumed to be of Variant data type. Variant is the default data type for any undeclared variables.Example –

B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 22

Page 3: Visual+Basic Handout 2

BITIC, Bahrain

Dim num1 As IntegerDim name As StringDim num1, num2 As Integer ‘(Here num1 will have data type as Variant)Dim x As Integer, y As IntegerDim amt As DoubleDim start_dt As Date

Default Values of any Variable

When you declare variables, VB gives each variable a default value. This value will be different for the different data types.For numeric data types, it will always be 0 (zero). For a string variable, it will be a blank string (””)

Note: Always use Val function to convert text values to numeric before performing any calculations.

Assigning Values to Variables

The assignment statement can be used as follows to assign value to any variable. You cannot declare a variable and assign a value to it all in one statement. You

must put the assignment statement in a separate line. The syntax is –

variable name = expression Example –

name = “Visual Basic”surname = “Abbas”num1 = 32 + num2a = b/cx = yc = 90amt = 3.2223start_dt = #16/4/2007#

Note: The symbol # called as pound sign tells VB to treat the numbers as date instead of some mathematical expression to be solved. The format of the date to be displayed in the program depends on the current date settings within the Windows OS.

Example of use of String VariablePrivate Sub cmdShow_Click() picOutput.Cls phrase = "win or lose that counts." picOutput.Print "It's not whether you "; phrase

B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 23

Page 4: Visual+Basic Handout 2

BITIC, Bahrain

picOutput.Print "It's whether I "; phraseEnd Sub

Scope of Variables

A variable may exist and be visible for an entire project, for only one form, or for only one procedure. The availability of a variable is referred to as its scope. The scope can be global, module-level or local.

A global variable can be used in all the procedures of a project. Module-level variables are accessible from all procedures of a form. A local variable may be used within the procedure in which it is declared.

Local/Private Variables

Any variable that is declared inside any sub procedure or function is local in scope; it is known only to that procedure or function. They are declared using DIM statement as follows:

[Private] Dim < variable name > [ As < data type >]

Here, the ‘Private’ keyword is optional i.e. not required.

Once the procedure is finished, these local variables and constants are also lost. Variables in different procedures are totally independent. Different procedures can have variables with the same names; however, each variable will have its own memory location

Advantages of Local Variableso Extremely useful for team programmingo To protect side effect (which is an accidental change of the value of the

variable)Example of Local VariablesPrivate Sub cmdButton_Click() Dim var1 As Integer, var2 As Integer,num As Integer var1 = 2 var2 = 4 Call Add(num) Print numEnd SubPrivate Sub Add(num As Integer)

Dim var1 As Integer, var2 As Integer

B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 24

Page 5: Visual+Basic Handout 2

BITIC, Bahrain

var1=1 var2=2

num = var1 + var2 End Sub Module-level/Form-level variables

At times we want to use a particular variable in more than one procedure of a form, then module level variables can be used. The module level variables and constants can be declared in the ‘General Declarations’ section of the form. To display the General Declarations section, first go to code window; then in the Object list, select (General); in the Procedure list, select (Declarations). These variables can be used in all the procedures within that form. Global/Public Variables

If a variable or a constant has to be used in more than one form in the project, then it must be declared as a global variable.

A global variable can be declared as follows-

Public <variable name> [As Datatype]

And, a global constant can be declared as follows-

Public Const <constant name> [As DataType] = value

Static variables

Static variables retain their value for the life of the project rather than being reinitialized for each call to the procedure.

Example, to find the running total, it can be declared as a static variable inside a procedure or function.

Syntax is-

Static <variable name> [As Data type]

The Static statements can appear only in procedures and can never appear in the General Declarations of a module.

Controls as Variables

B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 25

Page 6: Visual+Basic Handout 2

BITIC, Bahrain

The values stored in controls can be used in the program code and thus the controls can be used as variables.

Eg. Label1.Caption =Text1.Text

OrLabel1 = Text1

would copy whatever was in the text box into the label.

Constant

Constants are used to store a value that doesn’t change. A constant has also to be declared as similar to a variable, but its value can not be changed throughout the life of your program. • Types of Constants-

Numeric ConstantsString Constants

Valid Numeric ConstantsInteger Real number-2987 -1900.05+16 0.0185 5 10.56

Invalid Numeric Constants14,005.5 6.8%33- $190.0415 78 3.5&

Numeric Constants in a Statement:tax = 0.02 * (income - 500 )sum = 2 + x + 4.6 + y

String ConstantsA group of alphanumeric data consisting of any type of symbols.

Valid String Constants“A rose by any other name”“Down By the Sea Shore”“134.23”“She said, ‘stop , thief!’”

Invalid String Constants‘Down by the Seashore’

B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 26

Page 7: Visual+Basic Handout 2

BITIC, Bahrain

“134.24“She said, “Stop, thief!”

There are two main advantages of using named constants rather than the actual values in code. The code is easier to read; for example, seeing the identifier MaximumPay is more meaningful than seeing a number, such as 10000. In addition, when a particular constant value is used in several locations throughout our program and if you need to change the value at a later time, you need to change the constant declaration only once and not change every reference to it throughout the code manually.

By declaring a constant, you can assign the number/value to a meaningful name in one place in your program and then use that meaningful name elsewhere in your program. Now, if you need to change this value, you just change at one place and everywhere it’s used in your program will automatically use this new changed value.

Such a constant can be declared like –

Const < constant name > As < data type > = <value>Examples –

Const conHello As String = “Hello Visual Basic Programmers”Const Pi As Single = 3.14Const errmsg As String = “Incorrect Input”

Usage –Sub Command1_click()

Const conHello As String = “Hello Visual Basic Programmers”………….Label1.Caption = conHello…………..

End Sub

Option Explicit Statement

The option explicit statement can be used to force explicit declaration of variables in the program. Attempting to use an undeclared variable causes an error at compile time.

Example-Option Explicit ' Force explicit variable declaration.Dim MyVar ' Declare variable.MyInt = 10 ' Undeclared variable generates error.MyVar = 10 ' Declared variable does not generate error

Also, the option explicit option can be set as follows-

B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 27

Page 8: Visual+Basic Handout 2

BITIC, Bahrain

1. From the Tools menu- select Options2. On the Editor tab, make sure that Require Variable Declaration is selected.3. Click the OK button.

When you turn on the Require Variable Declaration option, VB automatically adds the Option Explicit statements to all the new forms you create after that point

Operators

Operators Description

Arithmetic Operators Operators used to perform mathematical calculations.

Comparison Operators Operators used to perform comparisons.

Concatenation Operators

Operators used to combine strings.

Logical Operators Operators used to perform logical operations.

Arithmetic OperatorsOperator Operation Basic expression Example

^ Exponentiation A ^ B 4 ^ 2 = 16 * Multiplication A * B 4 * 2 = 8 / Division A / B 4/3 = 1.33 + Addition A + B 4 + 2 = 6 - Subtraction A – B 4 – 2 = 2 \ Integer Division A \ B 4 \ 3 = 1 MOD Remainder A mod B 4 Mod 3 = 1

Note:Integer Division (\) divides one number by another number but truncates the decimal portion of the number.Mod Operator

Used to divide two numbers and return only the remainder.

Example-

10 Mod 5 ' Returns 0.10 Mod 3 ' Returns 1.

Comparison Operators

= <> < > >= <= Like Is

B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 28

Page 9: Visual+Basic Handout 2

BITIC, Bahrain

Logical Operators

AND OR NOT

Concatenation Operators& Operator + Operator

Operator PrecedenceThe order in which operations are performed determines the result. When several operators occur together in an expression, each part is evaluated in a predetermined order called as operator precedence.

When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last.

Comparison operators all have equal precedence; that is, they are evaluated in the left-to-right order in which they appear. The order of precedence for logical operators is – NOT, AND and then OR.

The hierarchy of operations in arithmetic expressions from highest to lowest is as follows-

1. Exponentiation

2. Multiplication and division

3. Addition and subtraction

When multiplication and division occur together in an expression, each operation is evaluated as it occurs from left to right. When addition and subtraction occur together in an expression, each operation is evaluated in order of appearance from left to right.

Parenthesis can be used to change the order of evaluation. Operations within parentheses are always performed before those outside. Within parentheses, however, operator precedence is maintained.

ExamplesEvaluate the following expressions:X=8/4/2x = 3 * 6 - 12 / 3 x = 4 ^ (8 / 4)y = 12 + 6 / (3 * (10 - 9))z = 5 + 4 ^ 2m = 6 / 3 + 3

B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 29

Page 10: Visual+Basic Handout 2

BITIC, Bahrain

Reserved Words/Keywords

• Words that have predefined meaning to Visual Basic are known as keywords or reserved words. • They can not be used as variable names.

Example: Print ; Cls ; If ; While

Internal Documentation

• An apostrophe (‘) can be used to indicate comments; comments are ignored by Visual Basic. • The keyword Rem can also be used instead of an apostrophe for comments.• Remarks can also be placed after program statement too.

End Statement

The End statement stops the execution of a project. It can be used in the sub procedure for an Exit button or an Exit menu choice.

Visual Basic Print Method

• Print: Print is a method used to display data on the screen.• It can be used to print value of variables. • It can be used to print value of arithmetic expressions.

Note: Methods are in-built code routines hidden inside the control. Like statements in other languages, they perform actions. But each control has a different set of methods that can be used with it.For example –

o List Box has methods like AddItem, RemoveItem etc.o Form has Print methodo Picture Box has Print method, Cls method

Example of Print MethodPrivate Sub cmdCompute_Click() Picture1.Print 3 - 2 Picture1.Print 3 * 2 Picture1.Print 3 / 2 Picture1.Print 3 ^ 2 Picture1.Print 2 * (3 + 4)End Sub

B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 210

Page 11: Visual+Basic Handout 2

BITIC, Bahrain

Example of Print Method x = 15 y = 5picOutput.Print (x + y) / 2, x / yOutput will be -

10 3

Example of Print MethodSub Command1_Click()

Form1.Print “Hello World”End Sub

Here, “Hello World” will be displayed on the form itself.

Concatenation Operator

• Two strings can be combined with the concatenation operator.• Concatenation operator is represented with the ampersand ( & ) sign.

Example of Concatenation:

str1 = “Hello”str2 = “World”picOutput.Print str1& str2

Output is – “HelloWorld”

Example of ConcatenationtxtBox.Text = “32” & Chr(176) & “ Fahrenheit”

Output is - 32°Fahrnheit

Using Text Boxes for Input/Output

• By default, the text property of the text box holds string values.• The contents of a text box should be changed to a number before being assigned to a numeric variable.

Example : Convert kilometers into centimeters and vice versa

B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 211

Page 12: Visual+Basic Handout 2

BITIC, Bahrain

Private Sub txtMeter_LostFocus() txtcentm.Text = Str(Val(txtmeter.Text ) * 100)End SubPrivate Sub txtCentm_LostFocus() txtMeter.Text = Str(Val(txtCentm.Text) / 100)End Sub

Example:Print the ASCII value for any pressed key. Write the code in KeyPress Event Procedure

Private Sub text1_KeyPress(KeyAscii As Integer) Text1.Text = "" Picture1.Cls Picture1.Print Chr(KeyAscii); " has ASCII value"; KeyAsciiEnd Sub

Note: Here KeyPress is an event for the text box which takes the ASCII value of the pressed key as a parameter. The above code can be used to print the ASCII value of any key that the user is pressing on the keyboard.

Standard Built-in Functions of VB

Types of Standard Functions• Numeric Functions (manipulate numbers)• String Functions (manipulate strings)

Numeric FunctionsCommon Examples:

Val(string) is a built-in VB function to convert any given string into a value.Example-Val (text1.Text) changes the input string into a number.

num = Val (text1.Text)

Rnd FunctionReturns a random number from 0 up to 1 ( excluding 1).

Example: Displays a random integer from 1 through 6. picBox.Print Int( 6 * Rnd) + 1

B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 212

Page 13: Visual+Basic Handout 2

BITIC, Bahrain

Sqr(number) FunctionReturns the square root of a number.

Round(n,m)) FunctionRound off the number n to m places.

Example for some commonly-used numeric functionsPrivate Sub cmdEvaluate_Click() Dim n As Single, root As Single picResults.Cls n = 6.76 root = Sqr(n) picResults.Print root; Int(n); Round(n,1) End Sub

String Functions

Commonly-Used String Functions Function: Left (“Penguin”,4) ‘Output is “Peng” Purpose: Returns the number of specified characters, starting at the beginning of the

string.

Function: Right (“Gotham City”, 4) ‘Output is “tham”Purpose: Returns the number of specified characters from the end of the string. Function: Mid (“Commissioner”, 4, 3) ‘Output is “mis”Purpose: Returns the character string starting at the position indicated by the first

number and continuing for the length specified by the second number. Function: UCase ( “Yes”) ‘Output is “YES”Purpose: Converts any lowercase letters in string to uppercase.

Function: LCase ( “Yes”) ‘Outputis “yes”Purpose: Converts any uppercase letters in string to lowercase. Function: InStr (“John Smith”, ” “) ‘Output is 5Purpose: Searches for the first occurrence of one string in another and gives the

position at which the string is found. String-Related Numeric Function

Function: Len (“John Smith”)

B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 213

Page 14: Visual+Basic Handout 2

BITIC, Bahrain

Purpose: Returns the number of characters in the string.

Function: Chr(Ascii Value) Purpose: Converts the ASCII value into its corresponding character.

Changing Multiple Properties of a Control- With Statement

Sometimes, we want to change the multiple properties of a control, then the ‘With’ statement can be used.

Syntax of ‘With’ statement is as follows-

With <control name>Statement(s)

End With

Example,

With txtTitle

.Visible = True

.Forecolor = vbWhite

.Font.Bold = True

.Font.Italic = True

.SetFocus

End With

The real advantage is that the ‘With’ statement is more efficient. The VB project will run a little faster , if you use With.

Setting a Border And Style

Most controls can appear to be three dimensional or flat. Labels, text boxes, option buttons and images all have an Appearance property, with choices of 0 – Flat, or 1 – 3D. To make a label or an image appear 3D, you must first give it a border. Set the Borderstyle to 1 – Fixed Single. The Appearance property defaults to 1 – 3D.

B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 214

Page 15: Visual+Basic Handout 2

BITIC, Bahrain

Defining Keyboard Access Keys

The keyboard can be used to select the options on the interface by pressing the Alt key and the hot key. The access keys can be set for command buttons, option buttons and check boxes in their ‘Caption’ property. Type an & in front of the character you want for the access key. VB will underline that character.

---***---

What have we learnt?

1. Which different component windows are present on the Visual Basic desktop?

2. What are variables? How any variable is declared in Visual Basic? Give some examples

3. List the different data types present in Visual Basic.

4. Define Variant data type available in Visual basic. Give one example to support your answer.

5. How the controls are used as variables in VB? Give example.

6. Describe local, global, module-level and static variables.

7. Define static variables? Give example.

8. What are constants? Which are the two different types of constants in VB? Give example for each type.

9. What is the main advantage of using a constant in a program?

10. How a constant can be declared in a VB program? Give examples for declaring a constant.

11. List the different arithmetic operators in VB with one example for each.

12. Write a short note on ‘Operator Precedence’.

13. Explain the usage of ‘With’ statement.

14. Explain the use of ‘Option Explicit’ statement.

15. What is the function of concatenation in VB? Give example.

16. Explain-

a) Val function

b) SetFocus method

17. Write a program to convert a given quantity in kilograms to pounds, using the formula-

1 Kilogram = 2.2 pounds

Write a VB program to enter two numbers in two text boxes and find their product.

B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 215

Page 16: Visual+Basic Handout 2

BITIC, Bahrain

18. Write the code that multiplies the two entered numbers in the text boxes and display the result on pressing the ‘Enter key’ after the second number.

Private Sub Text2_KeyPress(KeyAscii As Integer)

Dim num1 As Integer, num2 As Integer

If KeyAscii = 13 Then

num1 = Text1.Text

num2 = Text2.Text

MsgBox "Result is " & Str(num1 + num2)

End If

End Sub

19. Write a program that accepts a character. If the character is a lowercase letter, convert the letter to uppercase and display the letter in its uppercase form.

20. Write a program to convert centimeters into meters and vice-versa using the formula-

1 meter = 100 cm

Hint: Use Text boxes to take the input in meter and centimeter. The conversion code can be attached to the ‘Change’ event of the text boxes.

Solution:

Private Sub txtCm_Change()

Dim cm As Single

cm = Val(txtCm.Text)

txtMt = cm / 100

End Sub

Private Sub txtMt_Change()

Dim m As Single

m = Val(txtCm.Text)

txtCm = m * 100

End Sub

21. Write a program which displays the ASCII value of any key (printable) pressed by the user.

Solution:

Private Sub text1_KeyPress(KeyAscii As Integer)

Text1.Text = ""

Picture1.Cls

Picture1.Print Chr(KeyAscii); " has ANSI value"; KeyAscii

End Sub

-----***-----

B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 216

Page 17: Visual+Basic Handout 2

BITIC, Bahrain

B.Sc.(IT ) – Windows Programming in Visual Basic Handout # 217