a variable (x) is declared as an integer data type, meaning it can only accept numeric values the...
Post on 22-Dec-2015
243 views
TRANSCRIPT
A variable (X) is declared as an integer Data Type, meaning it can only accept numeric values
The Text Box is named BoxContents
The Variable X is assigned the value of the Height property of BoxContents (Text Box)
The Text property of BoxContents consists of a literal and the value of the variable X
The Text in BoxContents is also printed on the form
Before Project Execution
During Project Execution
Additional Instructions
Make the Text Box blank once the contents have been printed
Notify the user that the Text Box is blank
Add this Code to the End of the Sub-Procedure
BoxContents.Text =“”‘Empties whatever is in the text box
Print “The Text Box (BoxContents) is now blank”‘Prints this message on the form
Operators and Operands in Expressions
An Operand can be thought of as something that has a value
An Operator is the symbol of an operation carried out on at least 2 operands
There are 3 main types of Operator in VB, which take the following Order of Precedence:
- Arithmetic Operators- Relational (Comparison) Operators
- Logical Operators
Expressions
An Expression is a Visual Basic Action
There are 2 types of Expression in VB:
- Simple- Compound
An expression is formed by combining Operators and Operands in a meaningful way
The purpose of an expression is to perform a calculation and produce a result, or to cause some action to occur
Simple Expression: (A+B)
Compound Expression: An expression with more than 1 OPERATION is called a Compound Expression
[(A+B)*(C-D)]
(A, B, C, D) are the Operands(*, +, -) are the Operators
Each of these Operator Symbols represents an Operation
Arithmetic Operators
The hierarchy of operations, or order of precedence, in arithmetic expressions from the highest to the lowest is:
[1] Exponentiation: ^ (2 ^ 3 = 8)[2] Multiplication and Division: * /[3] Addition and Subtraction: + --
Example
3 + 4 * 2 = 11However, the order of evaluation can be changed by using
parentheses: ()(3 + 4) * 2 = 14
If one set of parentheses are used inside another set, the parentheses are referred to as nested
((3 + 3) / 3) * 4 = 8
(((4 + 3 * 4) / 2) * 4 + (4 + 10 / 2 - 3)) = ?
Nested
What Data Types would be assigned to the Variable X as a result of each of the following Operations
(2 + 4) (integer + integer) = integer/Long (2 - 4) (integer - integer) = integer/Long (2 * 4) (integer * integer) = integer/Long (2 / 4) (integer / integer) = Single/Double
(Two + Four) (string + string) = string (TwoFour)
Val Function
A Function performs an action and returns a value
The expression to operate upon, known as the argument, (or multiple arguments), must be enclosed in parentheses
Val an abbreviation for value
Val(ExpressionToConvert)
The expression that is converted, can be the Property of a Control, a Variable, or a Constant
The Val Function returns (produces) a value that can be used as a part of a statement, such as an assignment
statement
iQuantity = Val(txtQuantity.Text)
The Val Function converts an argument to numeric, by beginning at the Left-Most Character
If that character is a numeric digit, decimal point, or sign, Val converts the character to numeric and moves to the next character. As soon as a non-numeric character is
found, the operation stops
Conversion Function
The Conversion Function checks if the value stored in the Property of a Control or a Variable is of a specific Data Type required in the execution of a statement(s),
and if not the Conversion Function will return a ‘Run-Time Error’ Message
The Text in Text Boxes is treated as a String, however in performing Arithmetic Operations (such as ^ * / + -),
numeric values are required in the Text property of the Text Boxes
VB Conversion Functions
CInt - Converts a value to an Integer CLng - Converts a value to a Long Integer
CSng - Converts a value to a Single Precision number CDbl - Converts a value to a Double Precision nember
CCur - Converts a value to Currency CStr - Converts a value to a String
CVar - Converts a value to a Variant
CInt Function
Dim X As IntegerX = CInt(Text1.Text)
Print X
Dim X As Integer, Y As IntegerY = CInt(X) * 2
Print Y
CInt(“12”) the brackets are by default - 12CInt(“Twelve”) - Error
CInt(Text1.Text) - the value of the Text in Text1, if it is valid
cHours = 12.2
cPayRate = 5
cTotalPay = ?
In the Sample code the Val Function is replaced by the CCur Function
The value stored in the Text Property of the Hours text box is converted from a String to Currency and the value is assigned to the Variable cHours as a Currency Data Type
If the value in the Text Property is not consistent with the Currency Data Type, then a ‘Run-Time Error’ will occur and the program will stop executing
Using the Val Function and the CCur Function, after multiplication, returns the value of 61
Hours.Text = 12.2
PayRate.Text = 5
However, if the value of Hours.Text = 12.2’
How would the Functions handle it?
The Val Function will convert the value stored in the Property of the control, to a numeric value, before
assigning it as the value of the variable for use in an Arithmetic Calculation
The Conversion Function checks if the value stored in the Property of a Control is of a specific Data Type
required in the execution of a statement(s) (numeric for the purpose of calculation), and if not the Conversion
Function will return a ‘Run-Time Error’ Message
Basic Elements of Programming
A VB program is built from statements, statements from expressions, expressions from operators and operands,
and operands from variables/constants and the properties of objects
Operand
Operand
Operator Expression Statement
Programming Constructs
VB code is generally comprised of combinations of the following program statements
Sequence: Consisting of a number of instructions which are processed in sequence
Selection: Consisting of branches in the VB program, containing different instructions which are processed depending on the results of certain tested conditions
Iteration: Consisting of groups of statements which are repeatedly executed until a certain tested condition is
satisfied
Selection (Branching Constructs in VB)
Branching constructs are used to control program flow
A Condition/Expression is evaluated, and the result determines which statements the program executes
There are 2 main types of Branching Construct in VB:
IF statementsSELECT CASE statements
Program Statements
Program Statements
Program Statements
Program Statements
Evaluate an
Expression
Outcome A Outcome B
If Statements
Projects can take one action or another, based on a condition
Make a decision and take alternate courses of action based on the outcome
If..Then statement syntax:
If [Condition/Expression] ThenAction/Statements
ElseAction/Statements
End If
The word Then must appear on the same line as If
Else and End If must appear on separate lines
The statements underneath the Then and Else clause are indented for ‘readability’ and ‘clarity’ (always indent code,
especially with If statements, the indentation helps to visualise the intended logic and saves on project debugging time)
If..Then statements are generally used in conjunction with the Relational (Comparison) Operators
These Relational (Comparison) Operators are used to compare expressions, and return a result of either True or
False (Boolean Data Type)
The test of an If statement is based on a condition
To form conditions, Relational(Comparison) Operators are used, resulting in an outcome being either ‘True’ or ‘False’
(Boolean Data Type)
There are 6 Relational(Comparison) Operators in VB:
Order of Precedence of Relational Operators> greater than
< less than= equal to
<> not equal to>= greater than or equal to
<= less than or equal to
Conditions can be formed with
- numeric variables and constants- string variables and constants
- object properties, and- arithmetic expressions
However, comparisons have to be made on like data types
strings compared to stringsnumeric values compared with numeric values
whether a variable, constant, property of an object, or arithmetic expression
Dim Num1 as Integer
If Num1 > 10 ThenPrint “Num1 is greater than 10”
End If
If Num1 > 10 ThenPrint “Num1 is greater than 10”
ElsePrint “Num1 is less than 10”
End If
Val(Text1.Text)
Val(Text1.Text)
Multiple Branching
The logic of a program may require that there be more than one branch in the program
In this case the ElseIf keyword(clause) is added to the If..Then statement to increase flexibility
An infinite amount of ElseIf statements can be included into the If..Then statement
If..Then..Else statement syntax:
If [Condition/Expression] ThenAction/Statements
ElseIf [Condition/Expression] ThenAction/Statements
ElseAction/Statements
End If
Dim Temperature As Single
If Temperature <= 0 ThenPrint “Freezing”
ElseIf Temperature >= 30 ThenPrint “Hot”
ElsePrint “Moderate”
End If
If..Then..Else statements have a definite hierarchy
The order of an If..Then..Else statement is important, due to the fact that if the first line of the If..Then..Else statement is
‘True’, then none of the other ElseIf statements will be processed/executed
If..Then statements can be given greater flexibility in 2 main ways:
[1] Using Logical Operators [2] Nesting If..Then statements
Logical Operators
Logical Operators should be used when a limited number of conditions are to be tested
The 3 most commonly used Logical Operators in VB are in ‘Order of Precedence’:
ANDOR
NOT
Compound conditions/expressions are created using Logical Operators
Use compound conditions/expressions to test more than
one condition
AND Both conditions must be true for the entire condition to be true
OR If one condition or both conditions are true, the entire condition is true
NOT Reverses the condition, so that a true condition will evaluate false and vice versa
The use of parentheses can change the ‘Order of Precedence’ of these Logical Operators
Always plan the use of Logical Operators, as their use can often involve confusing logic
Dim StudentName As StringDim Age As Integer
If StudentName = “Dave” AND Age >= 23 Then
If StudentName = “Dave” OR Age >= 23 Then
If StudentName = “Dave” AND NOT Age <= 23 Then
Logical Operator Guidelines
Result = Expression1 Logical Operator Expression2
If Expression1 AND Expression2 Then Result True True True True False False False True False False False False
If Expression1 OR Expression2 Then Result True True True True False True False True True False False False
Nesting If..Then Statements
If..Then statements that contain additional If..Then statements are said to be nested If statements
If more than one Expression has to be checked in the program, If..Then statements can be nested
You may nest If..Then statements in both the Then and Else portion of the statement syntax
You can continue to nest If..Then statements within If..Then statements as long as each If has an End If
Nested If..Then statement syntax: (nested in the Then clause)
If [Condition/Expression] ThenIf [Condition/Expression] Then
Action/StatementsElse
Action/StatementsEnd If
ElseAction/Statements
End If
Nested If..Then statement syntax: (nested in the Else clause)
If [Condition/Expression] ThenAction/Statements
ElseIf [Condition/Expression] Then
Action/StatementsElse
Action/StatementsEnd If
End If
The first If..Then statement which the program encounters is called the OUTER If..Then statement
Any If..Then statements placed within the first statement are called INNER If..Then statements
INNER If..Then statements are only processed when the OUTER If..Then statement is True
Nested If..Then statements have to be carefully structured
There is a definite Order/Hierarchy in relation to the way in which they are processed
If..Then statements
If..Then statements check the value of an expression and carry out different instructions based on the result
If..Then statements are a useful and flexible method of allowing a program to branch into different directions
If..Then statements become more powerful and flexible through the use of:the ELSEIF clause
NESTED IF..THEN statements, andLOGICAL OPERATORS
If..Then statements must be carefully structured as there is a definite order in which the conditions are tested
Using If..Then statements with Option Buttons and Check Boxes
In using If..Then statements, with Option Buttons and Check Boxes, no action should be taken in the click events
for these controls
Code should be written in the Click_Event of a Command Button, where certain actions will be performed when the command button is clicked, relating to the selection of an option button (value property of the option button), or the checking of a check box (value property of the check box)
Private Sub Command1_Click
If Option1.Value = True ThenPrint “Option1 Selected”
ElseIf Option2.Value = True ThenPrint “Option2 Selected”
ElseIf Option3.Value = True ThenPrint “Option3 Selected”
ElseIf Option4.Value = True ThenPrint “Option4 Selected”
ElsePrint “No Option Selected, Please Select Option”
End If
End Sub
Private Sub Command1_Click
If Check1.Value = 1 ThenPrint “Check1 Selected”
ElseIf Check2.Value = 1 ThenPrint “Check2 Selected”
ElseIf Check3.Value = 1 ThenPrint “Check3 Selected”
ElseIf Check4.Value = 1 ThenPrint “Check4 Selected”
ElsePrint “Nothing Checked”
End If
End Sub
Comparing Numeric Values
If Val(Text1.Text) = MaxPrice Then
(Is the current numeric value stored in the Text property of Text1 equal to the value stored in MaxPrice)
Even though an equal sign (=) means replacement in an assignment statement, in a relation test (using relational
operators) an equal sign is used to test for equality
Comparing Strings
String variables can be compared to other string variables or ‘string literals’ enclosed in quotation marks
The comparison begins with the Left-Most character and proceeds one character at a time from left to right
Each character is compared in the strings, and as soon as one is less than another the comparison is terminated and the string with the lower ranking character is judged less than the other
The determination of which character is less than other is based on the code used to store characters internally in the
computer
ASCII code (American Standard Code for Information Interchange) has an established order called the collating sequence, for all letters, numbers, and special characters
All numeric digits are less than all letters
Comparing the Text Property of Text Boxes
The Text Property can behave like a Variant, a String, a Number
A numeric expression/calculation on a Text Property can be forced by using the Val function
Testing for Boolean (True/False)
If X = True Then…. is equivalent to:If X Then….
Boolean Variables hold the value ‘0’ when False, and ‘-1’ when True
Any variable can be tested for ‘True’/‘False’
VB considers any numeric variable with a value of ‘0’ to be False, any other value will evaluate True
The variable or expression is referred to as an ‘implied condition’
iCounter = 10
If iCounter = 10 Then...
If iCounter Then...
Comparing Uppercase and Lowercase Characters
When comparing strings, the case of the characters is important
An Uppercase character is not equal to a Lowercase character
By using the String Function Ucase or Lcase, the Uppercase or Lowercase equivalent of a string can be compared
Ucase(string)Lcase(string)
Text1.Text Ucase(Text1.Text) Lcase(Text1.Text)
User types in Basic
BASIC basic
If Ucase(Text1.Text) = “BASIC” ThenPrint “Hello”
End If
When the text of Text1 is converted to Uppercase, it must be compared to an Uppercase ‘Literal’ (BASIC), if it is to
evaluate True
Select Case Statements (Case Structure)
A Select Case statement executes one of several groups of statements, depending on the value of an expression
An expression is selected and tested against a number of possible cases
The expression to be tested is usually a variable or object property
There is no limit to the number of statements that can follow a Case statement
If any of these cases match the value of the expression, the statements that follow are executed
Select Case statement syntax:
Select Case [Expression]Case [Expression Value/Constant List]
StatementsCase [Expression Value]
StatementsCase [Expression Value]
StatementsCase Else
StatementsEnd Select
The [Expression Value/Constant List] is the value that is required to be matched, and can be of the following types:
numeric or string type variable or constanta range of values
a relational conditionor a combination of these
To test a single variable or expression for multiple values, the Case Structure provides a flexible and powerful solution
Any program decisions that can be coded with a Case Structure can also be coded with Nested If Statements, but
usually the Case structure is simpler and clearer
When using a Relational Operator the word Is must be usedCase Is >= 100
To indicate a Range of Constants, use the word ToCase 25 To 90
To test for a String Value, quotation marks must be included around the literals
Case “Visual Basic”
In using Strings, the case(Upper/Lower) of the characters must be exact between the expression being tested and the
[Expression Value/Constant List] Select Case Ucase(Text1.Text)
Case “VISUAL BASIC”
A combination of Relational/Logical Operators, using Variables and ConstantsCase Is >= 10 AND Num1 <= 20
Although the Case Else clause is optional, generally it will be included in the Select Case statements
The statements coded underneath Case Else will execute only if none of the other Case Conditions is matched
The Case Else clause will provide checking for any invalid or unforeseen values of the expression being tested
If the Case Else clause is omitted and none of the Case Conditions is True, the program will continue execution at the
statement following the End Select
If more than one Case value is matched by the expression, only the statements in the first Case clause will be executed,
identifying a definite Hierarchy
Testing Option Buttons using the Case Structure
The Case Structure is ideal for testing which Option Button is selected