VISUAL BASIC
Variables-Operations
 May 2002
Variable
 Memory location whose value can change as the
 program is running.
 Used to hold temporary information
 Used to control the type of data used in
 calculations
 Can Store only one piece of data at any time
 Data is processed faster
Data Types
 Integer - Whole numbers - 2 bytes - +/- 32,767
 Long - Whole numbers - 4 bytes - +/- 2 billion
 Single - Decimal - 4 bytes - +/- 1E-45 to 2E38
 Double - Decimal - 8 bytes - +/- 5E-324 to 1.8E308
 Currency - 15 left, 4 right of decimal - 8 bytes - +/- 9E14
 String - Text - 1 byte per character - 65,400 chars for fixed strings, 2
 billion for dynamic strings
 Byte - Whole numbers - 1 byte – 0 to 255
 Boolean - Logical values - 2 bytes - True or false
 Date - Date and time - 8 bytes - 1/1/100 to 12/31/9999
 Object - OLE objects - 4 bytes - N/A
 Variant - Any preceding type - 16 bytes+1 byte per character - N/A
Use of Appropriate Data Type
  Integer or Long - Used to store whole numbers
  Single, Double, Currency - Used to store numbers
 with a decimal fraction
  String - Used to store strings
  Boolean - Used to store Boolean values (True and
 False)
  Date - Used to store date and time information
  Object - Used to store a reference to an object
  Byte - Used to store binary data
  Variant - Flexible, but not efficient
Variable Names
  Can be no longer than 255 characters
  Can not be a reserved word
  Should be meaningful
  First three characters should represent the
 data type or should start with a letter
  Remainder of name should represent the
 variable’s purpose. No spaces, periods, or
 other punctuation characters are allowed
Three-Character Ids
 Byte byt  Long lng
 Boolean bln  Object obj
 Currency cur
  Single sng
  String str
 Date/Time dtm
  Variant vnt
 Double dbl
 Integer int
Variable Declaration
  Dim variablename [As datatype] [,
 variablename2 [As datatype2]]
  Public variablename [As datatype]
  Private variablename [As datatype]
  Static variablename [As datatype]
Assigning Values to Variables
  Assignment statement
  variablename = value
  Examples:
  sngHours = 38.5
  curBonus = curSales * .1
  strName = “Susan”
Scope of a Variable
  Indicates which procedures can use the
 variable
  Determined by where the Dim or Public
 statement is entered
  Can be either global, form-level, or local
Local Variables
  Created with the Dim statement
  The Dim statement is entered in an
 object’s event procedure
  Only the procedure in which it is
 declared can use the variable
  Removed from memory when the
 procedure ends
Form Level Variables
  Created with the Dim/Private statement
  The Dim statement is entered in a form’s
 General declarations section
  Can be used by any of the procedures in
 the form
  Removed from memory when the
 application ends
Global Variables
  Created with the Public statement
  The Public statement is entered in a code
 module’s General declarations section
  Used in multi-form projects and can be used
 by any of the procedures in any of the project’s
 forms
  Removed from memory when the application
 ends
Static Variables
  Can be used to preserve the variable value for
 the procedures to be called multiple times
 Static Sub Test()
 Dim x As Integer
 Debug.Print x
 x = 1234
 Debug.Print x
 End Sub
 (1st run: 0 and 1234; 2nd run: 1234 and 1234)
Variable Arrays
  Group of variables of same type
 Dim x1 As Currency, x2 As Currency
 Dim x3 As Currency, x4 As Currency
 Dim xtotal As Currency
 xtotal=x1+x2+x3+x4
 Dim x (1 to 4) As Currency
 Dim xtotal As Currency
 xtotal=0
 For xcounter = 1 to 4
 xtotal=xtotal+x(xcounter)
 Next xcounter
Option Explicit Statement
  Doesn’t allow you to create variables “on the fly”
  Enter in every form’s, and every code module’s,
 General declarations section
  Use Tools, Options, Editor tab, Require
 Variable Declaration to have Visual Basic
 include Option Explicit in every new form and
 module
  If you fail to define a variable you will receive an
 error message “Variable not defined”
Constants
  Literal constant
  an item of data whose value cannot change
 while the program is running
  7
  “Janet”
  Symbolic constant
  a memory location whose contents cannot
 be changed while the program is running
  conPi
  conRate
Creating a Symbolic Constant
  A memory location whose value cannot
 change during run time
  Syntax: [Public] Const constname [As
 datatype] = expression
  Examples:
  Const conPi As Single = 3.141593
  Public Const conMaxAge as Integer = 65
Scope of a Symbolic Constant
  Indicates which procedures can use the
 symbolic constant
  Global: Public Const statement in a code
 module’s General declarations section
  Form-level: Const statement in the form’s
 General declarations section
  Local: Const statement in an event procedure
Assignment Statements
  IntNumStudents=25
 numeric literal
  StrTopStudent=“June”
 string literal
  IntAvgScore=TotScore/NumStudents
 mathematical expression
  StrSpouseName=“Mrs. ” & “Tina Fortner”
 string expression
  StrCapitalName=Ucase$(“Chris”)
 return value of a function
Operator Order of Precedence
  ^ exponentiation
  - negation
  *, / multiplication and division
  \ integer division
  Mod modulus arithmetic
  +, - addition and subtraction
  Order is from left to right for same order or
 precedence. Parentheses can be used to
 override the order or precedence.
Function
  A predefined Visual Basic procedure
  A function returns a value
  Val and Format are two examples of
 Visual Basic’s intrinsic functions
Val Function
  Val function - returns the numeric equivalent of a
 string
  Syntax: Val(string)
  This Val function: Would be converted to:
  Val(“456”) 456
  Val(“24,500”) 24
  Val(“24.500”) 24.5
  Val(“$56.8”) 0
  Val(“A”) 0
  Val(“”) 0
String Concatenation
  Ampersand - &
  Examples: (Assume strFirstName contains “Mary”
 and sngSales contains 1000)
  “Hello “ & strFirstName
  strFirstName & “ sold $“ & sngSales & “.”
  Results:
  Hello Mary
  Mary sold $1000.
Newline Character
  Chr(13) & Chr(10) - issues a carriage return
 followed by a line feed
  vbNewLine - one of Visual Basic’s intrinsic
 constant
  An intrinsic constant is one that is built into the
 Visual Basic language
Len Function
  You can use the Len function to
 determine the number of characters
 contained in a text box or a variable
  Syntax: Len(textbox.Text)
SelStart Property of a Text Box
  Tells Visual Basic where to position the
 insertion point
  Syntax: object.SelStart [ = index]
  The first position is position (index) 0
SelLength Property of a Text Box
  Tells Visual Basic how many characters
 to select
  Syntax: object.SelLength [ = number]
Highlighting Existing Text
  Use the following two lines of code:
  textbox.SelStart = 0
  textbox.SelLength = Len(textbox.Text)
  Enter the lines of code in the text box’s
 GotFocus event, which occurs when an object
 receives the focus
Change Case
 All upper case letters: Ucase
 All lower case letters: Lcase
 Dim str1 As String, str2 As String
 Dim str3 As String, str4 As String
 s1 = "çğıiöşü"
 s2 = "ÇĞIİÖŞÜ"
 s3 = UCase(s1) ‘ÇĞıIÖŞÜ
 s4 = LCase(s3) ‘çğiİöşü
 MsgBox (s1 & vbNewLine & s3)
 MsgBox (s2 & vbNewLine & s4)
Searching a String –
Insrt - First Occurrence
  InStr(StartPos, sourcestr, searchstr)
  StrChrPos = InStr(1,“I’ll see you next Tuesday.”, “you”)
  Result is 10
  StrChrPos = InStr(9, “I’ll see you next Tuesday.”, “e”)
  Result is 15
Searching a String –
InStrRev - Last Occurrence
  InStr(StartPos, sourcestr, searchstr)
  StrChrPos = InStrRev(“I’ll see you next Tuesday.”, “e”)
  Result is 21
  StrChrPos = InStrRev(“I’ll see you next Tuesday.”, “l”)
  Result is 4
Extracting Pieces of a String
  Left(string, length) : Retrieves a specified number of
 characters from the left end of a string
  Right(string, length) : Retrieves a specified number of
 characters from the right end of a string
  Mid(string, start [, length]) : Retrieves characters from
 the middle of a string
 Dim AnyString, MyStr
 AnyString = "Hello World" ' Define string.
 MyStr = Left(AnyString, 7) ' Returns "Hello W".
 MyStr = Right(AnyString, 7) ' Returns “o World".
 MyStr = Mid(AnyString, 2, 3) ' Returns “ell".
Replacing Characters in a String
  Mid can be used to replace part of a string.
 Dim AnyString, MyStr
 AnyString = "Hello World" ' Define string.
 Mid(AnyString, 2) = “aaa” ' Returns “Haaao World".
  Mid statement preserves the original length of the
 string. If the space remaining between the starting
 position and the end of the string is less than the
 length of the replacement string, only the leftmost
 characters are used from the replacement string.
Getting Rid of Spaces
  LTrim(string) : Removes the spaces from the
 beginning of a string
  RTrim(string) : Removes the spaces from the end of a
 string
  Trim(string) : Removes the spaces from both the
 beginning and end of a string
 Dim AnyString, MyStr
 AnyString = “ Hello World" ' Define string.
 MyStr = LTrim(AnyString) ' Returns "Hello World".
Format Function
  Format function - returns a formatted expression
  Syntax: Format(expression, format)
  Some of Visual Basic’s predefined formats:
  Currency
  Fixed
  Standard
  Percent
Format
  FormatCurrency(1234) or
 Format(1234, “Currency”)
  $1,234.00 or 1.234,00 TL
  Format(1234, “$#,###.00”)
  $1,234.00 (According to OS)
  FormatNumber(1234)
  1,234.00 or 1.234,00
  FormatDateTime(“20:10”,vbLongTime)
  20:10:00
Named Format and Descriptions
  General Number: No special formatting
  Currency: Thousands separator, two digits to the right of the decimal
  Fixed: At least one digit to the left and two digits to the right of the decimal
  Standard: Thousands separator, at least one digit to the left and two digits
 to the right of the decimal
  Percent: Multiplies by 100 and follows number by % sign
  Scientific: Standard scientific notation
  Yes/No: Displays Yes for a nonzero value.
  True/False: Displays True for a nonzero value.
  On/Off: Displays On for a nonzero value.
Codes for Numeric Formats
  0 – Digit placeholder: Displays the digit or 0 if no digit.
  9 – Digit placeholder: Displays the digit or displays nothing if no
 digit. (omits leading and trailing zeros)
  . – Decimal separator: Indicates where the decimal point is
 displayed.
  , – Thousands separator: Indicates where the separators are
 displayed.
  % – Percentage indicator: Indicates where a percent sign is
 displayed. (number multiplied by 100)
  E-,E+ - Scientific notation: With E- a minus sign is displayed next
 to negative exponents, no sign for positive.
Named Date and Time Formats
 General Date: Displays date and time if expression contains both.
 Long Date: Displays the day of the week, the day of the month, the
 month and the year.
 Medium Date: Displays the day of the month, a three-letter
 abbreviation for the month and the year.
 Short Date: Displays the day, month, the month and year.
 Long Time: Displays hours, minutes, and seconds along with the
 AM/PM indicator.
 Medium Time: Displays hours and minutes along with the AM/PM
 indicator.
 Short Time: Displays hours and minutes in military time.
Other Functions
 (MonthName(Month(Now))) ‘ Returns Mart
 Change to Date
  Cdate(“November 23, 1963”)‘ Returns 11/23/63
 Add Dates
  MsgBox (DateAdd(“m”, 1, Now())) ‘ Returns 04.04.2002 10:00
 Subtract Dates
  (DateDiff(“m”, Now, “5.5.2002”)) ‘ Returns 2 (5-3)
 Round a numeric expression to a specified number of decimal places.
  Round(202.5) ‘ Returns 202
  Round(202.56) ‘ Returns 203
Credit Payment Example
Credit Payment Example
Use object names as:
 lblPrincipal, txtPrincipal
 lblInterest, txtInterest
 lblPeriod, txtPeriod
 lblPayment, txtPayment
 cmdCalcul
 cmdExit
Result will be: 50.388
Credit Payment Example
Private Sub cmdCalcul_Click()
 Dim dPrincipal As Double, dPayment As Double
 Dim dInterest As Double, dPeriod As Double, dTerm As Double
 dPrincipal = Val(Replace(Replace(txtPrincipal.Text, ",", ""), ".", ""))
 dInterest = Val(txtinterest.Text) / 100
 dPeriod = Val(txtPeriod.Text)
 dTerm = dPeriod * 12
 txtPrincipal.Text = Format(dPrincipal, "###,###,###,###")
 dPayment = dPrincipal * (dInterest / (1 - (1 + dInterest) ^ (0 - dTerm)))
 txtPayment.Text = Format(dPayment, "###,###,###,###")
End Sub
Credit Payment Example
Private Sub cmdExit_Click()
 End
End Sub 
Private Sub Form_Load()
 txtPrincipal.Text = "100000"
 txtinterest.Text = 50
 txtPeriode.Text = 1
End Sub