Variables & Function Calls
Overview u Variables Programmer Defined & Intrinsic Data Types Calculation issues u Using Functions The val() function The msgbox() function
Types of Data u Numeric Can contain only numbers Real numbers, integers, currency, dates Used for arithmetic calculations u String (text) May contain any symbol No arithmetic calculations Append, insert, extract
Variables - The Concept u Variables are named containers of data They are not displayed on a form The contents can change during runtime u Variables vary in size and purpose Some types of data require more memory than others Each variable belongs to a type The type of a variable determines its size, and what operations (such as add, substract, append) will work on the variable
VB Variables u Variables are not created using the tool box Instead, they are declared within the program Declaring a variable sets aside memory for the variable assigns a name to that space in memory describes what type of data can be stored there u Variables don’t work with the properties window Changes to a variable must be made in a program
Declaring a Variable u A declaration begins with the Dim statement This alerts VB that a new variable is being defined u A declaration contains a variable name and type Just as each control must have a (name), like lblInput, and type, like label u The form of a declaration: Dim as For example: Dim intCount as Integer
Numeric Variable Types u There are several different numeric variable types, each with varying Precision Size Representation scheme u Selecting the wrong type for variables can hurt the performance of a program
Counting Things u Integer types BYTE Small range of values, 0 to 255 INTEGER -32,768 to +32,767 LONG -2,147,483,648 to +2,147,483,647
Measuring Things u SINGLE Positive or negative As close to zero as E-45 As large as E38 u DOUBLE Positive or negative As close to zero as E-327 As large as E308
Highest Precision u Scaled integers u CURRENCY +/-922,337,203,685, u DECIMAL +/-79,228,162,514,262,337,593,543,950,335 +/ no rounding, slow but sure
Storage Space & Prefixes u BYTE 1 byte byt u INTEGER 2 bytesint u LONG 4 byteslng u SINGLE 4 bytessng u DOUBLE 8 bytesdbl u BOOLEAN 2 bytesbln u CURRENCY 8 bytescur u DECIMAL14 bytesdec
Establishing Values Dim intValue as integer intValue = 12 intValue = ”12” intValue = 12.5 intValue = Due to automatic type conversion, all result in the integer variable intValue being set to 12
Operators & Precedence 1.^ Exponentiation 2.- Unary Negation 3.* / Multiplication and Division 4.\ Integer Division 5. MOD Remainder Addition and Subtraction (otherwise left to right)
Precedence Examples sng A = ( ) / ( ) results: sng A = sng B = ( ) / results: sng B = 0.50 sng C = 3 * 4 / 2 * 3 results: sng C = sng D = ( 3 * 4 ) / ( 2 * 3 ) results: sng D = 2.00
Real & Integer Arithmetic sng A = 5 / 2 results: sngA = 2.50 sng B = 5 \ 2 results: sngB = 2.00 int C = 5 MOD 2 results: int C = 1 int D = 5 / 2 results: intD = 2
Text Strings u Used to hold an arbitrary list of characters u The size can be predetermined, or allowed to change as the program runs u The.caption property of a label is a string, as is the text property of a textbox
String Variables Variable and fixed length strings: Dim strNamer As String Dim strMiddle As String * 1 Dim strState As String * 2 strNamer = ”Jason Ogelthorpe” strMiddle = ”P” strState = ”WI”
String Variables Dim strSocSoc As String * 11 Dim strZipCode As String * 10 strSocSoc = ” ” strZipCode = ”53211” (strZipCode = ”53211 ”) (note | |)
Concatenation of Strings strSamp = ”Hi” & ” There” (strSamp = ”Hi There”) strSamp = ”Value” & 27 (strSamp = ”Value27”) strSamp = ”Value” & str(27) (strSamp = ”Value 27”)
Long Strings strSamp = ”We can build ” _ & ”a very, very, very, ” _ & ”long string.” (a concatenated string can be split over several lines, note underscore characters and note spaces contained within the quoted areas.)
Naming VB Variables u Programmer defined u Don’t use reserved words Type names, control names, keywords (DIM or end) u Make the name meaningful intNum vs intNumberOfGroceries u Capitalize first character after prefix If multiple words, capitalize the 1 st character of each u use standard prefixes
Naming VB Variables u Are these valid names? int Number Sub MinimumRate Caption CarCount intNumberofcars
VB Constants u Types of Constants Literals sngTaxRate =.075 txtName = “Smith” Symbolic programmer defined with Const keyword const as = Const sngTaxRate as Single =.075 Some are defined by VB vbRed vbCenter u What are benefits of symbolic constants? u Why avoid literals in code?
Working with Variables u Declaring Variables Dim statement, short for Dimension, Sets aside memory Labels the memory Initializes variable based upon type u Dim intPhone as Integer Creates variable that can store an integer number u Dim strLastName as String Creates variable that can store a string (of variable length) u Dim strLastName as String * 5 Creates variable that can store a string of 5 characters.
Working with Variables u Assignment Statement Each statement in Experiment 3 was an assignment statements u Basic format = Use an = (equals sign – read “is assigned”) VB evaluates the expression to the right of the equal sign If necessary, that value is converted so that it has the same type as the variable The value is copied in to the variable – old data is overwritten u For Numeric Data Types A = B + 8*C (Variable A is assigned the value of the resolved expression) u For String Data Types strFull = strFirst & strLast (The right side is concatenated and assigned into strFull)
Working with Variables u Control Properties are Variables lblName.Caption = “My label” u Type Mismatch intNumber = strLastName u Misspellings Use OPTION EXPLICIT statement to make the computer find errors If a variable used in an assignment is not in a DIM statement, then VB does not allow the program to compile
Using Functions u Some activities are common in programming tasks Converting a string to a number Pop up a warning message for the user Extracting a substring from a string u Rather than forcing programmers to re-write the code which handles these activities each time they are needed, we can write one reusable function u Functions have names, like variables, and parameter lists
The form of a function call u The general form of a function call is (,, … ) u Functions take input values, called parameters, and produce an output value which can be assigned to a variable dblValue = squareRoot(intCount) u Visual Basic includes many functions we can use u We will learn how to create our own functions Chapter 6
The VAL Function u This function allows conversion between string filled variables and numeric variables. u It works by “scanning” the characters of the string filled variable and builds a numeric value until the end-of-string or a non numeric is found.
A Simple Program Private Sub cmdComnd_Click() Label1.Caption = Val(Text1.Text) End Sub We can enter character strings into the box “Text1”, press the command button, and look at what appears in the box “Label1”.
Some Examples
The Message Box u VB allows the user to generate message boxes as a part of a user program. When invoked they look something like this:
Format of MsgBox u In its simplest form the MsgBox is called by this command: Dim intX As Integer intX = MsgBox("Read the Password")
The Details Dim intX As Integer intX = MsgBox("Do this now", _ vbCritical, "Prompting Issue")
Response Choices The value of “intZ” above depends on which response is chosen. “Yes” - intZ = 6 “No” -intZ = 7 (the numerical values are defined by Visual Basic.) Dim intZ As Integer intZ = MsgBox(“Should I Do This”, _ vbYesNo,”Prompting Issue”)
Icon Choices