Visual Basic 6 Variables

44
VISUAL BASIC Variables-Operations May 2002

Transcript of Visual Basic 6 Variables

Page 1: Visual Basic 6 Variables

VISUAL BASIC Variables-Operations

May 2002

Page 2: Visual Basic 6 Variables

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

Page 3: Visual Basic 6 Variables

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

Page 4: Visual Basic 6 Variables

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

Page 5: Visual Basic 6 Variables

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

Page 6: Visual Basic 6 Variables

Three-Character Ids

Byte byt Boolean bln Currency cur Date/Time dtm Double dbl Integer int

Long lng Object obj Single sng String str Variant vnt

Page 7: Visual Basic 6 Variables

Variable Declaration

Dim variablename [As datatype] [, variablename2 [As datatype2]]

Public variablename [As datatype] Private variablename [As datatype] Static variablename [As datatype]

Page 8: Visual Basic 6 Variables

Assigning Values to Variables

Assignment statement variablename = value

Examples: sngHours = 38.5 curBonus = curSales * .1 strName = “Susan”

Page 9: Visual Basic 6 Variables

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

Page 10: Visual Basic 6 Variables

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

Page 11: Visual Basic 6 Variables

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

Page 12: Visual Basic 6 Variables

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

Page 13: Visual Basic 6 Variables

Static Variables

Can be used to preserve the variable value for the procedures to be called multiple timesStatic 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)

Page 14: Visual Basic 6 Variables

Variable Arrays

Group of variables of same typeDim x1 As Currency, x2 As CurrencyDim x3 As Currency, x4 As CurrencyDim xtotal As Currencyxtotal=x1+x2+x3+x4

Dim x (1 to 4) As CurrencyDim xtotal As Currencyxtotal=0For xcounter = 1 to 4

xtotal=xtotal+x(xcounter)Next xcounter

Page 15: Visual Basic 6 Variables

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”

Page 16: Visual Basic 6 Variables

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

Page 17: Visual Basic 6 Variables

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

Page 18: Visual Basic 6 Variables

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

Page 19: Visual Basic 6 Variables

Assignment Statements

IntNumStudents=25numeric literal

StrTopStudent=“June”string literal

IntAvgScore=TotScore/NumStudentsmathematical expression

StrSpouseName=“Mrs. ” & “Tina Fortner”string expression

StrCapitalName=Ucase$(“Chris”)return value of a function

Page 20: Visual Basic 6 Variables

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.

Page 21: Visual Basic 6 Variables

Function

A predefined Visual Basic procedure

A function returns a value

Val and Format are two examples of Visual Basic’s intrinsic functions

Page 22: Visual Basic 6 Variables

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

Page 23: Visual Basic 6 Variables

String Concatenation

Ampersand - & Examples: (Assume strFirstName contains “Mary”

and sngSales contains 1000) “Hello “ & strFirstName strFirstName & “ sold $“ & sngSales & “.”

Results: Hello Mary Mary sold $1000.

Page 24: Visual Basic 6 Variables

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

Page 25: Visual Basic 6 Variables

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)

Page 26: Visual Basic 6 Variables

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

Page 27: Visual Basic 6 Variables

SelLength Property of a Text Box

Tells Visual Basic how many characters

to select

Syntax: object.SelLength [ = number]

Page 28: Visual Basic 6 Variables

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

Page 29: Visual Basic 6 Variables

Change Case

All upper case letters: Ucase All lower case letters: Lcase

Dim str1 As String, str2 As StringDim str3 As String, str4 As Strings1 = "çğıiöşü"s2 = "ÇĞIİÖŞÜ"s3 = UCase(s1) ‘ÇĞıIÖŞÜs4 = LCase(s3) ‘çğiİöşüMsgBox (s1 & vbNewLine & s3)MsgBox (s2 & vbNewLine & s4)

Page 30: Visual Basic 6 Variables

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

Page 31: Visual Basic 6 Variables

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

Page 32: Visual Basic 6 Variables

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".

Page 33: Visual Basic 6 Variables

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.

Page 34: Visual Basic 6 Variables

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".

Page 35: Visual Basic 6 Variables

Format Function

Format function - returns a formatted expression

Syntax: Format(expression, format)

Some of Visual Basic’s predefined formats:

Currency

Fixed

Standard

Percent

Page 36: Visual Basic 6 Variables

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

Page 37: Visual Basic 6 Variables

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.

Page 38: Visual Basic 6 Variables

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.

Page 39: Visual Basic 6 Variables

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.

Page 40: Visual Basic 6 Variables

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

Page 41: Visual Basic 6 Variables

Credit Payment Example

Page 42: Visual Basic 6 Variables

Credit Payment ExampleUse object names as:

lblPrincipal, txtPrincipal

lblInterest, txtInterest

lblPeriod, txtPeriod

lblPayment, txtPayment

cmdCalcul

cmdExit

Result will be: 50.388

Page 43: Visual Basic 6 Variables

Credit Payment ExamplePrivate 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

Page 44: Visual Basic 6 Variables

Credit Payment ExamplePrivate Sub cmdExit_Click()

End

End Sub

 

Private Sub Form_Load()

txtPrincipal.Text = "100000"

txtinterest.Text = 50

txtPeriode.Text = 1

End Sub