Fundamentals of Programming in Visual Basic - PowerPoint PPT Presentation

1 / 93
About This Presentation
Title:

Fundamentals of Programming in Visual Basic

Description:

2. Set properties for the controls and the form ... An apostrophe (') is used to indicate that the remainder of the line is a comment. ... – PowerPoint PPT presentation

Number of Views:50
Avg rating:3.0/5.0
Slides: 94
Provided by: fay75
Category:

less

Transcript and Presenter's Notes

Title: Fundamentals of Programming in Visual Basic


1
Chapter 3
  • Fundamentals of Programming in Visual Basic

2
Outline and Objectives
  • Visual Basic Objects
  • Visual Basic Events
  • Numbers
  • Strings
  • Input/Output
  • Built-In Functions

3
The Initial Visual Basic Screen
Menu bar
Project Explorer window
Toolbar
Toolbox
Properties window
Description pane
Form
Form Layout window
Project Container window
4
Steps to Create a Visual Basic Program
  • 1. Create the interface by placing controls on
    the form
  • 2. Set properties for the controls and the form
  • 3. Write code for event procedures associated
    with the controls and the form

5
Four Useful Visual Basic Controls
  • Text Boxes
  • Labels
  • Command Buttons
  • Picture Boxes

6
Placing a Text Box on a Form
  • Double-click on the text box icon in the toolbox
    to add a text box to your form
  • Activate the properties window (Press F4)
  • Set values of properties for text box

7
Placing a Text Box on a Form
Text box
8
Some Useful Properties of Objects
  • Name
  • Caption
  • Text (for Text Boxes)
  • BorderStyle
  • Visible
  • BackColor
  • Alignment
  • Font

9
Example
10
Naming Objects
  • Use the Property window to change the Name
    property of an object
  • Good programming practice dictates that each
    object name begins with a three letter prefix
    that identifies the type of object.

11
Naming Objects
12
Naming Objects
  • An Object Name
  • Must Start with a letter
  • Can include numbers and underscore (_)
  • Cannot include punctuation or spaces
  • Can be a maximum of 40 characters

13
Visual Basic Events
  • Code is a set of statements that instruct the
    computer to carry out a task.
  • Code can be associated with events
  • When an event occurs, the code associated with
    that event (called an Event Procedure) is
    executed.

14
Creating An Event Procedure
  • Double-click on an object to open a Code window.
    (The empty default event procedure will appear.
    Click on the Procedure box if you want to display
    a different event procedure.)
  • Write the code for that event procedure.

15
Example of An Event Procedure
  • Private Sub objectName_event ( )
  • statements
  • End Sub
  • Private Sub txtOne_GotFocus( )
  • txtOne.Font.Size 12
  • txtOne.Font.Bold False
  • End Sub

16
More Examples
  • Private Sub cmdButton_Click( )
  • txtBox.ForeColor vbRed
  • txtBox.Font.Size 24
  • txtBox.Text Hello
  • End Sub

17
Exercises
11. Private Sub cmdButton_Click( ) frmHi
Hello End Sub 12. Private Sub
cmdButton_Click( ) txtOne.ForeColor red
End Sub
18
Exercises
13. Private Sub cmdButton_Click( )
txtBox.Caption Hello End Sub 16.
Private Sub cmdButton_Click( )
txtOne.MultiLine True End Sub

19
Tips
  • Most Properties can be set or altered at run time
    with code.
  • cmdButton.visible False
  • The BorderStyle and MultiLine properties of a
    text box can only be set from the properties
    window
  • surrounds Caption, Name, Font.Name or strings
    not True, vars or numeric constants

20
Color Constants
  • At design time colors are selected from a palette
  • At run time the eight most common colors can be
    assigned with the color constants

21
Components of Visual Basic Statements
  • Constants
  • Variables
  • Keywords (reserved words)

22
Constant
  • Can NOT change during the execution of a program.
  • Types of Constants
  • numeric constants
  • string constants

23
Valid Numeric Constants
  • Integer Real
    number
  • -2987
    -1900.05
  • 16
    0.0185
  • 5
    10.56

24
Invalid Numeric Constants
  • 14,005.5
    6.8
  • 33-
    190.04
  • 15 78
    3.5

25
Arithmetic Operations
  • Operator Operation Basic expression
  • Exponentiation A
    B
  • Multiplication A
    B
  • / Division
    A / B
  • Addition
    A B
  • - Subtraction
    A - B

26
Scientific Notation
  • Largest/Smallest number a Single can handle

27
Variables
  • A storage location in main memory whose value can
    be changed during program execution.
  • These storage locations can be referred to by
    their names.
  • Every variable has three properties a Name, a
    Value, and a Data Type.
  • Types of variables Numeric and String

28
Rules for Naming Variables
  • Must begin with a letter
  • Must contain only letters, numeric digits, and
    underscores ( _ )
  • Can have up to 255 characters
  • Cannot be a Visual Basic language keyword (for
    example, Sub, End, False)

29
Keywords
  • Words that have predefined meaning to Visual
    Basic .
  • Can Not be used as variable names.
  • Examples
  • End - Print
  • Sub - Let
  • If -Select
  • While -Call

30
Numeric Variables
  • Used to store numbers
  • Value is assigned by a statement of the form
    numVar expression
  • The variable must be on the left and the
    expression on the right.

31
Assignment Statement
  • The statement var expr assigns the value of the
    expression to the variable
  • tax 0.02 (income - 500 dependents)
  • sum 2 x 4.6 y

32
Valid Numeric Variable Names
  • timeElapsed
  • taxRate
  • speed
  • n
  • celsius

33
Invalid Numeric Variable Names
  • maximum/average
  • 1stChoice
  • square yard

34
Valid Assignment Statements
  • count count 1
  • num 5
  • count count num /2

35
Invalid Assignment Statements
  • 10 count
  • count 1 count

36
Visual Basic Print Statement
  • Print is a method used to display data on the
    screen or printer.
  • Can be used to display values of variables or
    expressions

37
Examples of Print Statements
  • Private Sub cmdCompute_Click()
  • picResults.Print 3 2
  • picResults.Print 3 - 2
  • picResults.Print 3 2
  • picResults.Print 3 / 2
  • picResults.Print 3 2
  • picResults.Print 2 (3 4)
  • End Sub

38
Examples of Print Statements
  • picOutput.Print speed
  • picOutput.Print taxRate
  • picOutput.Print Class average is total / 3

39
Examples of Print Statements
  • x 15
  • y 5
  • picOutput.Print (x y) / 2, x / y
  • Output
  • 10 3

40
String Constants
  • A sequence of characters treated as a single item
  • The characters in a string must be surrounded by
    double quotes ( )

41
Valid String Constants
  • A rose by any other name
  • 9W
  • 134.23
  • She said, stop , thief!

42
Invalid String Constants
  • Down by the Seashore
  • 134.24
  • She said, Stop, thief!

43
String Variables
  • A string variable stores a string.
  • The rules for naming string variables are
    identical to those for naming numeric variables.
  • When a string variable is first declared, its
    value is the empty string.

44
String Variable Example
  • Private Sub cmdShow_Click()
  • picOutput.Cls
  • phrase "win or lose that counts."
  • picOutput.Print "It's not whether you "
    phrase
  • picOutput.Print "It's whether I " phrase
  • End Sub

45
Concatenation
  • Two strings can be combined by using the
    concatenation operation.
  • The concatenation operator is the ampersand ()
    sign.

46
Examples of Concatenation
  • strVar1 HellostrVar2 WorldpicOutput.Prin
    t strVar1 strVar2
  • txtBox.Text 32 Chr(176) Fahrenheit

47
Declaring Variable Types
  • Use the Dim statement to declare the type of a
    variable.
  • Examples
  • Dim number As Integer
  • Dim flower As String
  • Dim interestRate As Single

48
Data Types
  • Single a numeric variable that stores real
    numbers
  • Integer a numeric variable that stores integer
    numbers (from -32768 to 32767)
  • String a variable that stores a sequence of
    characters

49
Using Text Boxes for Input/Output
  • The contents of a text box are always a string.
  • Numbers can be stored in text boxes as strings.

50
Using Text Boxes for Input/Output
  • The contents of a text box should be converted
    to a number before being assigned to a numeric
    variable.
  • Val(txtBox.Text) gives the value of a numeric
    string as a number
  • Example Dim numVar as Single numVar
    Val(txtBox.Text)

51
Example (convert miles to furlongs and vice versa)
  • Example 1
  • xString528
  • xValueVal(xString) ? xValue528
  • Example 2
  • yValue428
  • yStringStr(yValue) ? yString428

52
Example (convert miles to furlongs and vice versa)
  • Private Sub txtFurlong_LostFocus()
  • txtMile.Text Str(Val(txtFurlong.Text / 8))
  • End Sub
  • Private Sub txtMile_LostFocus()
  • txtFurlong.Text Str(8 Val(txtMile.Text))
  • End Sub

53
Program Documentation
  • An apostrophe (') is used to indicate that the
    remainder of the line is a comment. (Comments are
    ignored by Visual Basic.)
  • Remarks can appear on a separate line or
    following a Visual Basic statement.

54
The KeyPress Event Procedure
  • Private Sub txtCharacter_KeyPress(KeyAscii As
    Integer)
  • txtCharacter.Text ""
  • picOutput.Cls
  • picOutput.Print Chr(KeyAscii) " has ANSI
    value" KeyAscii
  • End Sub

55
Reading Data from Files
  • 1. Choose a number to be the reference number for
    the file
  • 2. Execute an Open statement
  • 3. Read the data sequentially using Input
    statements
  • 4. Close the file

56
Example of Reading from a File
Open the file
  • Open DATA.TXT For Input As 1
  • Input 1, num1
  • Input 1, num2
  • picOutput.Print num1num2
  • Close 1

Reference number
Read the data and assign it to num1
Close the file
57
Example of Reading from a File
  • Open DATA.TXT For Input As 1
  • Input 1, num1, num2
  • picOutput.Print num1num2
  • Close 1

58
Reading Data from Files
  • Files can be also used for output rather than
    input. More about files will be discussed in
    chapter 8 and 9.

59
Input Dialog Box
  • An input dialog box can be used to obtain a
    single item of input from the user
  • Presents a window (dialog box) requesting input
  • Syntax stringVar InputBox(prompt, title)

60
Example of an Input Dialog Box
  • Private Sub cmdDisplay_Click()
  • Dim fileName As String, prompt As String,
    title As String
  • Dim houseNumber As Single, street As String
  • prompt "Enter the name of the file
    containing the information."
  • title "Name of File"
  • fileName InputBox(prompt, title)
  • Open fileName For Input As 1
  • Input 1, houseNumber
  • Input 1, street
  • picAddress.Print "The White House is at"
    houseNumber street
  • Close 1
  • End Sub

After executing, an input dialog box will pop up
61
Using Message Dialog Box for Output
  • The message dialog box is used to present a
    pop-up window containing information for the user
  • Syntax MsgBox prompt, , title

62
Example of a Message Dialog Box
  • MsgBox Nice try, but no cigar, , Consolation

Stays on the screen until the user presses OK
63
Formatting the Output
  • Create easily readable output
  • In the Print method, the spacing of the output is
    controlled by the following devices
  • semicolon
  • comma
  • Tab function

64
Semicolons
  • The next value output is placed in the next
    column position.
  • Example
  • picOutput.Print Patrick Jon
  • Output
  • PatrickJon

65
Example of Semicolon
  • picOutput.Print Patrick Jon
  • Output Screen
  • Patrick Jon

Space here
Space here
66
Example of Semicolon
  • picOutput.Print 100 -200 300
  • Output Screen
  • 100 -200 300

Two spaces
One space
67
Commas
  • A comma in a Print method causes the next value
    output to be placed in the next available print
    zone.
  • Each print zone is 14 positions wide.

68
Using Commas
  • Example
  • picOutput.Print SEE, YOU, SOON
  • Output Screen
  • SEE YOU SOON

Column 29
Column 15
Column 1
69
Using Commas
  • Example
  • picOutput.Print abc123def456ghi, whatever
  • Output Screen
  • abc123def456ghi whatever

Column 29
Column 15
Column 1
70
Using Commas
  • A print zone can be skipped by typing consecutive
    commas
  • Example
  • picOutput.Print HOURLY, , PAY
  • Output Screen
  • HOURLY PAY

Column 29
71
Tab Function
  • Specifies the column where output will start
  • Use only semicolons with the Tab function
  • Can only be used to advance the print position
    (cannot move backwards)

72
Example of Tab Function
  • Example
  • picOutput.Print Tab(3) Hi there! Tab(25)
    Bye!
  • Output Screen
  • Hi there! Bye!

Column 25
Column 3
73
Example of Tab Function
  • Example
  • picOutput.Print Tab(3) Hi there! Tab(5)
    Bye!
  • Because column 5 is already occupied by the
    previous string, the output will be at the next
    line
  • Output Screen
  • Hi there!
  • Bye!

Column 3
Column 5
74
Built-In Functions
  • Take one or more input values and return an
    output value
  • A means provided by Visual Basic for carrying out
    small, common tasks
  • Types of Built-In functions
  • Numeric functions (manipulate numbers)
  • String functions (manipulate strings)

75
Numeric Functions
76
Example of Numeric Functions
  • Private Sub cmdEvaluate_Click()
  • Dim n As Single, root As Single
  • n 6.76
  • root Sqr(n)
  • picResults.Print root Int(n) Round(n,1)
  • End Sub
  • Output 2.6 6 6.8

77
Commonly-Used String Functions
  • Function Left(Penguin, 4)
  • Purpose Returns the number of characters
    specified, starting at the beginning of the
    string

78
Commonly-Used String Functions
  • Function Right(Gotham City, 4)
  • Purpose Returns the number of characters
    specified from the end of the string

79
Commonly-Used String Functions
  • Function Mid(Commissioner, 4, 3)
  • Purpose Returns the substring starting at the
    position indicated by the first number and
    continuing for the length specified by the second
    number

80
Commonly-Used String Functions
  • Function UCase(Yes)
  • Purpose Converts any lowercase letters in a
    string to uppercase

81
String-Related Numeric Functions
  • Function InStr(John Smith, m)
  • Purpose Searches for the first occurrence of
    one string in another and gives the position at
    which the string is found

82
String-Related Numeric Function
  • Function Len(John Smith)
  • Purpose Returns the number of characters in the
    string.

83
Strings and string Functions examples
  • picBoard.print len(left(welcome,3))
  • picBoard.print UCase(left(welcome,3))

84
Format Functions
  • The format functions provide detailed control of
    how numbers, dates, and strings are displayed.
  • Examples
  • FormatNumber (12345.678, 1)
    12,345.7
  • FormatCurrency (12345.678, 2) 12,345.68
  • FormatPercent (.185, 2)
    18.50
  • FormatNumber (1 Sqr(2), 3)
    2.414

85
Format Function
  • Format (expr, _at_.._at_)
  • Purpose The value of this function is the value
    of expr right justified in a field of n spaces,
    where n is the number of _at_ symbols.

86
Format Examples
  • Format(12345, _at__at__at__at__at_) 12345
  • Format(123, _at__at__at__at__at_) 123
  • Format(123.4, _at__at__at__at__at_) 123.4

87
Examples
88
Examples
89
Examples
90
FormatDateTime Example
  • FormatDateTime (9-15-04, vbLongDate)
  • Output Monday, September 15, 2004

91
Rnd Function
  • Returns a random number from 0 to 1.
  • (excluding 1).
  • Example
  • picBox.Print Rnd
  • Output Displays a random number from 0 to 1 (0
    included and 1 excluded).
  • Example
  • picBox.Print Rnd 5
  • Output Displays a random number from 5 to 6 (5
    included and 6 excluded).

92
Rnd Function
  • Example
  • picBox.Print Int(Rnd)
  • Output Displays 0.
  • Example
  • picBox.Print Int(Rnd 5)
  • Output Displays 5.
  • Example
  • picBox.Print Int(Rnd) 5
  • Output Displays 5.

93
Rnd Function
  • Example
  • picBox.Print Int(5Rnd)
  • Output Displays a random Integer from 0 to 4 (0
    and 4 included).
  • OR
  • Output Displays a random Integer from 0 to 5 (0
    included and 5 excluded)
  • Example
  • picBox.Print Int(5Rnd) 2
  • Output Displays a random Integer from 2 to 6 (2
    and 6 included).
Write a Comment
User Comments (0)
About PowerShow.com