SlideShare a Scribd company logo
1 of 113
VISUAL PROGRAMMING


   VISUAL BASIC 6
BASIC
means Beginners' All-purpose Symbolic Instruction Code


Procedural fashion

But VB is event-driven
  It uses the VB IDE      (Integrated Development Environment)

  VBA        - Visual Basic for Applications
  VBScript
Defining basic terms
  Application
    An application is a collection of objects that work together to accomplish
    something useful. In VB the application is called a Project.

  Object
    An object is a piece of software that has properties and functions that can
    be manipulated. A window is an object.

  Event-driven
    An event is something that happens - the user clicks on a button, a form
    is opened, and the result of a calculation is too large.
Advantages of VB

   1. VB applications are event-driven

   2. VB supports the principals of objected-oriented design


   3. VB is a complete windows application development
          system


   4. VB uses ActiveX controls, dynamically linked libraries
         (DDL) and add-ins.
Different type of projects
   Standard           ActiveX Document EXE

   ActiveX EXE        DHTML Application

   ActiveX DLL

   ActiveX Control
   Data Project

   IIS Application

   ActiveX Document DLL
Standard : this project contains the standard set of controls and is used
   to create a basic windows application or to start a large application
   project.

ActiveX EXE : This project helps you create an ActiveX executable
   component that can be executed from other applications.

ActiveX DLL : An ActiveX DLL is used to contain controls and class
   code that can be used in other projects.

ActiveX Control : This enables you to create a custom ActiveX control.

Data Project : This project starts with database components already
  added to project file.
IIS Application : This project is used to create an Internet Application.

ActiveX Document DLL : This is used to by VB applications that will be
   installed and executed from the Internet.

ActiveX Document EXE : This project is used to create an Internet-
   based VB application

DHTML Application : This project creates a Web/HTML based
  application that can be executed only in a web browser.
Different Components of a
           Project
1. Form (.frm)         7. ActiveX Controls (.ocx)

2. Class (.cls)       8. ActiveX Designers(.dsr)

3. Standard(.bas)

4. Resource(.res)

5. ActiveX documents(.doc)

6. User controls(.ctl) and Property Pages(.pag)
From (.frm): form file contains the textual descriptions of the form
   and its controls, including their property settings. These files also
   have form level declarations for constants, variables and
   procedures.


Class (.cls) : it is similar to a form file, except they have no visible
   user interface. You can create your own objects.


Standard (.bas) : These files contain public or module-level
   declarations of types, constants, variables and procedures.


Resource (.res) : A resource file can be contain bitmaps, text
   string and other data that you can change without having to re-edit
   and then recompile your program code.
ActiveX documents (.doc) : These are similar to form files but
  are displayable only in an internet browser.


User controls(.ctl) and Property Pages(.pag) : These are
  similar to form files but are used to create custom ActiveX controls
  and their associated properties.


ActiveX Controls (.ocx) : These are optional controls that you
  can add to the toolbox and then use on the program’s forms.


ActiveX Designers (.dsr) : These files are any of the new
  designer components available in VB (such as Data Environment
  Designer or Data Report Designer).
ActiveX documents (.doc) : These are similar to form files but
  are displayable only in an internet browser.


User controls(.ctl) and Property Pages(.pag) : These are
  similar to form files but are used to create custom ActiveX controls
  and their associated properties.


ActiveX Controls (.ocx) : These are optional controls that you
  can add to the toolbox and then use on the program’s forms.


ActiveX Designers (.dsr) : These files are any of the new
  designer components available in VB (such as Data Environment
  Designer or Data Report Designer).
ActiveX documents (.doc) : These are similar to form files but
  are displayable only in an internet browser.


User controls(.ctl) and Property Pages(.pag) : These are
  similar to form files but are used to create custom ActiveX controls
  and their associated properties.


ActiveX Controls (.ocx) : These are optional controls that you
  can add to the toolbox and then use on the program’s forms.


ActiveX Designers (.dsr) : These files are any of the new
  designer components available in VB (such as Data Environment
  Designer or Data Report Designer).
IDE
   The Visual Basic development environment contains
    these programming tools and windows, with which
    you construct your Visual Basic programs:
    Menu bar
    Toolbars
    Visual Basic toolbox
    Form window
    Properties window
    Project Explorer
    Immediate window
    Form Layout window
Programming Tools
1. Menu bar
 Located at the top of the screen, the menu bar
  provides access to the commands that control the
  Visual Basic programming environment.
 Menus and commands work according to standard
  conventions used in all Windows-based programs.
Programming Tools
2. Toolbars
•   Located below the menu bar, toolbars are collections
    of buttons that serve as shortcuts for executing
    commands and controlling the Visual Basic
    development environment.
•    You can open special-purpose toolbars by using the
    View menu Toolbars command.
Programming Tools
3. Windows taskbar
 This taskbar is located along the bottom of the screen.
 You can use the taskbar to switch between Visual
  Basic forms as your program runs and to activate
  other Windowsbased programs.
Toolbox Controls
 You use special tools, called controls, to add
  elements of a program user interface to a form.
 These resources in the toolbox, which is
  typically located along the left side of the
  screen.
 (If the toolbox is not open, display it by using
  the Toolbox command on the View menu.)
Toolbox Controls
Form Window
 When you start Visual Basic, a default form
  (Form1) with a standard grid (a window
  consisting of regularly spaced dots) appears in
  a pane called the Form window.
 You can use the Form window grid to create
  the user interface and to line up interface
  elements.
Form Window
Form Window
• Building Interface Elements
• To build the interface elements, you click an interface
  control in the Visual Basic toolbox, and then you draw
  the user interface element on your form by using the
  mouse.
• This process is usually a simple matter of clicking to
  position one corner of the element and then dragging to
  create a rectangle the size you want.
• After you create the element — say, a text box — you
  can refine it by setting properties for the element.
• In a text box, for example, you can set properties to
  make the text boldface, italic, or underlined.
Properties Window
 With the Properties window, you change the
  characteristics (property settings) of the user interface
  elements on a form.
 A property setting is a characteristic of a user
  interface object.
 For example, you can change the text displayed by a
  text box control to a different font, point size, or
  alignment.
Properties Window
Properties Window
 Properties Window Elements
 The Properties window contains the following
  elements:
 A drop-down list box at the top of the window, from
  which you select the object whose properties you
  want to view or set.
 Two tabs, which list the properties either
  alphabetically or by category.
 A description pane that shows the name of the
  selected property and a short description of it.
Project Window
 A Visual Basic program consists of several files that
  are linked together to make the program run.
 The Visual Basic 6.0 development environment
  includes a Project window to help you switch back
  and forth between these components as you work on
  a project.
Project Window
Project Window
 Project Window Components
 The Project window lists all the files used in the
  programming process and provides access to them
  with two special buttons: View Code and View
  Object.
Code Window
 This computing logic is created using program
  statements      —     keywords,identifiers,  and
  arguments — that clearly spell out what the
  program should do each step of the way.
 You enter program statements in the Code
  window, a special text editing window designed
  specifically for Visual Basic program code.
 You can display the Code window in either of two
  ways:
 By clicking View Code in the Project window.
 By clicking the View menu Code command.
Form Layout Window
 The Form Layout window is a visual design tool.
 With it, you can control the placement of the forms in
  the Windows environment when they are executed.
 When you have more than one form in your program,
  the Form Layout window is especially useful — you
  can arrange the forms onscreen exactly the way you
  want.
 To position a form in the Form Layout window,
  simply drag the miniature form to the desired location
  in the window.
Form Layout Window
Understanding the project explorer window

  It displays all the project’s components in a hierarchical list. There are three

  display options. View code, View object and Toggle folders.


Setting Project options

  In VB we can set different properties associated with the project. It has

  three to five tabbed pages, depending on the type of project. These are

  general, make, compile, component and debugging tabs.
VB Procedures


    Two types of procedures in VB are SUBROUTINES and FUNCTIONS




Rules
        Unique name
        Not same as VB keywords or Built-in VBprocedures.
        A procedure can't contain other procedures within it.But can cal
                another procedure at any time
Understanding Subroutines
A subroutine (SUB) is a set of programming statements that is
executed as a unit by VBA engine.
Example:

 Private Sub Form_Load()               subroutine declaration


 Dim sSQL As String                    Declarations
        .
 .
 .
 .
 .
 .

 Call fillcontros                      call another subroutine

 End Sub                               Subroutine terminator
Components of VB Sub or Functions are

     Declaration

          Declarations area

          Statements

          Call to another procedure


     Terminator : END key word followed by the
                  type of procedure
Understanding functions
 It is similar to subroutine. The main difference is that a function returns a

 value. That means it returns the value through its name.

 Example:
Public Function VerifyUser( ÙName as string) as Boolean

                 If UName=” mes college” then

                           VerifyUser = True

                             Else

                           VerifyUser = False

                             Endif

                     End Function
Understanding Comments
 A comment is a plain text message you embed in the midst
 of your VBA code. A comment can include any printable
 character but must begin with a single quote (‘) or the key
 word Rem (Shorthand for remark).
Using the Visual Basic Editor
                ie is Visual Basic Code window. Its parts are

 Project name      :   it appears in the code window’s title bar.



 Module name       :   it also appears in the code window’s title bar.



                       it has direct access to the form and all the
 Object list      :    controls on them. It contains the names of all
                       controls on the form, stored alphabetically.
Procedure list     :   it contains all the corresponding event procedures
                       for that control.


Declaration area   :   at the top of every module is an area reserved for
                       declaring variables and constant used within the
                       module.


Indicator bar      :   it is a vertical gray area along the left side of
                       the code window.
Procedure and full module view buttons :
                        it shows procedure wise ie. only one procedure and
                        all procedure view.



Procedure separator:   this is a thin horizontal gray line drawn between
                       procedure in the code window.



                       this module can contain any number of procedures.
Procedure          :
Private Sub Form_Load ( )
       Form1.show
       Print “Welcome to Visual Basic tutorial”
End Sub
Opening the Code Window
   First and easiest method is double-click any control on the design view
   An alternative path to the Code window is press F7
   Right-click on the object and select the view code

   Right-click the name of a form in the projects window and select view code


   Click the view code button at the project window’s toolbar to open the module

   Crtl+F4 to close the code window and Alt+F4 shuts down VB
Understanding Code Window Features
  Line continuation character – underscore character, it is shown that
  any line of code ending in an underscore character preceded by a
  space is recognized as a statement that is continued on the next
  line.
       Concatenation character “&”
    sSQL = "SELECT FirstName, LastName, " _
             & "Title, HireDate, Extension " _
                    & "FROM Employees " _
                    & "ORDER BY LastName"



  VBA code window color cueing to set aside comments, keywords etc

  Global find and replace – you can search entire project ie all
  standard modules, form modules, class modules etc.
Setting bookmarks in code

 This is useful for quickly jump between different locations in your
 VBA code.


 Toggle Bookmark          :

   this add a bookmark to the current line of code window. If a
   bookmark previously set on that line will be removed.

 Next bookmark            :

        it moves the editing cursor to the next available bookmark.
Previous bookmark:

           it moves the editing cursor to the previous available
           bookmark.

  Clear all bookmark:

           removes all bookmark in all modules in the projects.


Using automatic word completion
     VB can help you by completing long keywords as you type. As
     soon as you have typed enough of keywords for VB to
     determine which word you are typing, press Ctrl+Spacebar.
It does not recognize the names of procedures or variables you are
 created in VB program.

 If you are not entering enough characters for VB to fill in the rest
 of the word, you will see a pop-up list of words to select from

Understanding Editor Options

 Auto Indent             :

       it causes code to be indented to the current depth in all successive
       lines of code.
Auto Syntax Check:

    if selected VB checks each lines of code for syntax errors as you enter
    it in the code window. It checks spelling errors, missing commas and
    so no.

Require Variable Declaration:

    if selected, this setting automatically inserts the option explicit directive
    into all VBA modules.

Auto List Members :
     this timesaving option displays a list box that contains the members
     of an object’s object hierarchy in the code window.
Auto Quick Info        :

       if it is selected VB displays syntax help when you enter
       the name of a procedure( function,subroutine or method)
       followed by a period, space or opening parenthesis.

Auto Data Tips         :
        this option displays the value of variables when you hold the
        mouse cursor over a variable with the module in break mode.

Drag-and-Drop Text Editing:

         this setting toggles drag and drop editing.
Default to Full Module View:

         by default code window shows more than one procedure if the
         procedures are small enough to be seen in their entirely.

Procedure separator :

            this the thin gray line that separates procedures in code
            window.

Tab width        :

            it specifies how many spaces will be inserted each time the
            tab key is pressed.
Understanding the Editor Format Tab in the Options
Dialog Box

    It contains settings that determine the overall appearance of
    the code window.

    Code Colors : the code window displays a variety of different
                    types of code statements.
           Eg. Executable commands, comments beak point etc. There are
           three color settings for each of the 10 different code structures in
           the code window: foreground, background and indicator.
           Foreground and background are self-explanatory.
Font and Size: this setting specify the font and font size used in code
               window.




Margin Indicator Bar: it is the vertical, gray bar along the left side of the
                      code window.
Controlling Program Flow
  Using Conditional Branching

       A conditional branch executes blocks of statements depending on
       the value of an expression.

  Using if. . . then

          If (condition) Then

                Optional statement(s)


           End If
Statement 1



                Then
    If
Expression             Optional Statement(s)




 Statement 2
Example:
• If/Then/End If blocks to allow multiple statements:
      If Balance - Check < 0 Then
              Print "You are overdrawn"
              Print "Authorities have been notified"
      End If
• In this case, if Balance - Check is less than zero, two
  lines of information are printed.
The following is an alternative way to write an if statement

                If Balance - Check < 0 Then Print "You are overdrawn"

         Here the optional statement appears on the same line as
         the if , the end if statement isn’t needed.
If . . . then . . . Else

        If (expression/condition) then

               Statement(s) if expressions is true

        Else

             Statement(s) if expressions is false


        End If
Statement 1


                       Else

       If                      Statement(s) if
   Expressio                  Expression is false
       n


                Then

 Statement(s) if
Expression is true




       End If




  Statement 2
Example:
• If/Then/Else/End If blocks:
      If Balance - Check < 0 Then
             Print "You are overdrawn"
             Print "Authorities have been notified"
      Else
             Balance = Balance - Check
      End If
• Here, the same two lines are printed if you are
  overdrawn (Balance - Check < 0),
• but, if you are not overdrawn (Else), your new
  Balance is computed.
Example:

Public Function VerifyUser(UName As String) As Boolean

       If UName = "Bob Smith" Then

                 VerifyUser = True

       Else

                VerifyUser = False

       End If

 End Function
If . . . then . . . ElseIf . . . End If

        If (expression 1/condition 1) then

                  Statement(s) if expressions 1 is true

        Else If (expression 2/condition 2) then

                  Statement(s) if expressions 2 is true


         Else If (expression N/condition N) then

                  Statement(s) if expressions N is true


         End If
Statement 1


                       Else                           Else

           If                            If                             If
       Expressio                     Expressio                      Expressio
          n1                            n2                            nN


Then                                                         Then
                              Then

  Statement(s) if                Statement(s) if                Statement(s) if
Expression 1 is true           Expression 2 is true           Expression N is true




          End If




       Statement 2
Example:
• the ElseIf statement:
• If Balance - Check < 0 Then
      Print "You are overdrawn"
      Print "Authorities have been notified"
• ElseIf Balance - Check = 0 Then
      Print "Whew! You barely made it"
      Balance = 0
• Else
      Balance = Balance - Check
• End If
Using Select Case
 The expression is evaluated at the top of the select
  case statement and compared with each of the
  candidate values in the body of the select case.
 If none of the values match the expression, the select
  case simply ends.
 An option Case Else can be added to the Select Case
  body to trap in the body to trap those instances where
  none of the candidate values match.

Statement case
  Expression




                 Statement Block 1
   Case
  Value 1




                 Statement Block 2
   Case
  Value 2




                  Statement Block N
    Case
   ValueN




  End Select
Example:

Sub SelectCase(sPet As String)

  Select Case sPet

   Case "Dog“

           MsgBox "It's a dog“

   Case "Cat“

           MsgBox "It's a cat“

   Case "Bird“

           MsgBox "It's a bird“

   Case Else

           MsgBox "Unknown pet“

  End Select

End Sub
Loops
 For . . . Next
 Syntax
 For initialize the counter variable to upper limit
                                      [increment value]
      Statement(s)
 Next counter variable
 Here increment value is optional and by defaults to 1.
For counter = start To end

   statements

Next

1) The counter is set to the value of start.

2) Counter is checked to see if it is greater than end; if yes, control
passes to the statement after the Next; if not the statements are
executed.

3)At Next, counter is incremented and goes back to step 2).
Establish upper limit
and increment Value




 Statement Block




 Increment counter

                        No




    Counter at
    upper
    limit?


YES


Continue processing
 ie. Next statement
Example:
           Public Function ValidatePassword2() As Boolean
            Dim i As Integer
            Dim sPWD As String
            For i = 1 To 3
                    sPWD = InputBox("Enter the password")
                    If sPWD = "xyzzy" Then
                           Exit For
                    End If
             Next i

             If i <= 3 Then
                    ValidatePassword2 = True
             Else
                    ValidatePassword2 = False
             End If
           End Function
Do. . . Loop
   Here the statement block is preceded before the expression
   is evaluated.

   Syntax

      Do
                      Statement 1
                      Statement 2
                               .
                               .
                      Statement n
               Loop Until Expression – Is- True
Statement 1




Process Statement
      Block




                    No


      Has
    condition
   been Met?

YES



      Statement 2
Example:

           Sum = 1
           Do
                  Print Sum
                  Sum = Sum + 3
           Loop Until Sum > 50


           This loop repeats Until Sum is greater than 50.
           • And, like the previous example , a
           Do/Loop Until structure always executes at least once.
Another do … loop form is instead of Until we use While keyword
Syntax

       Do
                       Statement 1

                      Statement 2
                              .
                              .
                              .
                      Statement n
               Loop while Expression – Is- False
Example


Sum = 1
Do
       Print Sum
       Sum = Sum + 3
Loop While Sum <= 50

• This loop repeats While the Variable Sum is less than
or equal to 50.
• Note, since the While check is at the end of the loop, a
Do/Loop While structure is always executed at least
once.
An alternate Do…Loop logic is that expression is evaluated at the top
of the loop and statement block is never executed if the expression is
true.

               Do Until Expression – Is- True

                               Statement 1

                               Statement 2
                                      .
                                      .
                                      .
                               Statement n

                       Loop
Statement 1




                     YES


     Has                   Statement 2
   condition
  been Met?

                No



Process statement
      Block
Example:

Counter = 1
Do Until Counter > 1000
        Print Counter
        Counter = Counter + 1
Loop


•This loop repeats Until the Counter variable exceeds 1000.
•Note a Do Until/Loop structure will not be entered if the Until
• condition is already True on the first encounter.
Do While condition

   statements

Loop

First, the condition is tested; if condition is True, then the statements

are executed. When it gets to the Loop it goes back to the Do and

tests condition again. If condition is False on the first pass, the

statements are never executed

        Counter = 1
        Do While Counter <= 1000
               Print Counter
               Counter = Counter + 1
        Loop
Data type
                        Storage
                                  Range
                        size

Byte                    1 byte    0 to 255

Boolean                 2 bytes   True or False

Integer                 2 bytes   -32,768 to 32,767

Long (long integer)     4 bytes   -2,147,483,648 to 2,147,483,647

Single       (single-   4 bytes
precision   floating-             -3.402823E38 to -1.401298E-45 for negative values;
point)                            1.401298E-45 to 3.402823E38 for positive values


Double      (double-    8 bytes
precision   floating-             -1.79769313486232E308 to -4.94065645841247E-324
point)                            for  negative  values;  4.94065645841247E-324 to
                                  1.79769313486232E308 for positive values

Currency
                                  -922,337,203,685,477.5808                       to
                        8 bytes
                                  922,337,203,685,477.5807

Date                    8 bytes   January 1, 100 to December 31, 9999

Object                  4 bytes   Any Object reference

String                  various   0 to approximately 2 billion

Variant                 various   Same range as any numeric or string data type
Byte

    A byte variable occupies only 8 bits. It can contain unsigned
    whole number values from 0 through 255. Negative numbers
    and numbers larger than 255 are not allowed. If do so it will
    return overflow error.

Example
              Dim bByte As Byte
Byte


       Integer

       It is similar to byte, except that it’s larger and can store
       negative numbers. It occupies 16 bits. And can hold whole
       numbers between -32768 to 32,767.
Long
    It behaves exactly as integer values, except that it can assigned
    much larger and much smaller values than integer. Because long
    integer are 32 bits in size, they can hold positive and negative
    numbers range between -2,147,483,648 to 2,147,483,647


   Single
    It contains floating point numbers. It can hold 32 bits. It is not
Double
    suitable for financial and scientific calculations.

    Double

     It occupies 8 bytes of memory and can hold large and small
    floating point numbers. It is used for calculation requiring
    extreme precision.
Currency

 It is reserved for storing numeric values such as bank account
 balance, prices and payroll information.

Boolean

  It accept only True or False values. It stores internally as
  integer number. True is stored as -1 and false is 0.
Date

It contain only date and time data. It occupies 8 bytes and
stored internally as a floating-point number.

It hold all date and time values from January 1, 100 through
December 31, 9999 and time from 00:00:00 to 23:59:59 one
second increment.

If we convert numeric value to date, the portion of the number to
the left of the decimal point become the date and the decimal
point become time.
String
  It can holds data made up of letters, numbers and symbols you
  see on a keyboard. Visual Basic provides two type of string
  variables.


   Fixed length string and variable length string

   Fixed length – contains at most 65000 characters.

   Variable length – can be as long as 2 billion characters.

Example

   Dim sFixed As String *10     ‘ a 10 character fixed width string.
Dim sVariable As String     ‘ a variable length string.



In fixed width string, the strings are fit the width defined for
the string. If we enter the word “Bcollege” to the sFixed
variable in the above example, then the data actually stored is
“Bcollege “ ie. the fixed width contains unwanted spaces.


We can remove the unwanted spaces using different trim
functions. Ltrim which removes leading spaces, Rtrim-removes
trailing spaces and Trim – removes both leading and trailing
spaces.
Object

 There will be occasions when you’ll want to refer to a form on
 a form in code or establish a variable that represents a
 complex object with several different properties rather than a
 single value. In such cases, the object data type is suitable.
Example
          Private Sub Form_Load()
                   frmBuddy.Show
                   Call UpdateCaptions(Me, txtCaption1)
                   Call UpdateCaptions(frmBuddy, txtCaption2)
                   bChanged False
          End Sub
          Public Sub UpdateCaptions(frm As Object, txt As Object)
                   txt.Text = frm.Caption
          End Sub

 Specific object type references run faster than the generic object type.

            Private Sub Form_Load()
                     frmBuddy.Show
                     Call UpdateCaptions(Me, txtCaption1)
                     Call UpdateCaptions(frmBuddy, txtCaption2)
                     bChanged = False
            End Sub
            Public Sub UpdateCaptions(frm As Form, txt As TextBox)
                     txt.Text = frm.Caption
            End Sub
Variant
    The default Visual Basic data type is Variant

    It can accept any value.


     It can hold more storage space than other data types.


Declaring Variables

    There are two ways to add variables to your applications.
They are

    Implicit declaration
           – visual basic automatically create the variables for you.

             It means that Visual Basic automatically creates a variant
             for each identifier it recognizes as a variable in an
             application
              Example
                        Private Sub cmdCombine_Click()

                                  FirstName = txtFN.Text

                                  LastName = txtLN.Text

                                  txtFullName = FN & " " & LN
                        End Sub
Explicit declaration

   - here we use one of the following keywords: Dim, Static, Private and
   Public.

 Syntax

      Dim VariableName As DataType

      Static VariableName As DataType

      Private VariableName As DataType

      Public VariableName As DataType
Example
           Private Sub cmdCombine_Click()
                   Dim FirstName As String
                   Dim LastName As String
                   FirstName = txtFN.Text
                   LastName = txtLN.Text
                   txtFullName = FN & " " & LN
           End Sub


Compare Implicit and Explicit Variable performance
Providing Names for your Variable

     These are the rules to follow when naming elements in VB -
     variables, constants, controls, procedures, and so on:

       • A name must begin with a letter of the alphabet.

       • The name must consist only of letters, digits and the
       underscore character (no punctuation mark are allowed)

        • May be as much as 255 characters long

        • Variable name can’t be duplicated within the same scope.
Forcing Explicit Declaration

Naming Convention

     Example : boolActive or factive, txtLS


Under standing Variables Scope and Lifetime
Converting Between Data Types
    Visual Basic provides several ways to convert values between
    different data types.

     Visual Basic automatically converts between the data types in
     the expression.
Example

Public Sub Conversion1 ()
 Dim sSt As String
 Dim dDb As Double
  sSt = "12345.67890"
 dDb = sStr
  MsgBox "Value of dDb: " & dDb _
   & vbCrLf & vbCrLf _
   & "TypeName(dDbl): " & TypeName(dDbl)
End Sub

This process of automatic conversion is called coercion
because Visual Basic forces the string value to a numeric
value.
Built-in conversion functions proved by the VBA language are

    When passed the string 12345.67890

Function              Result                  Resulting Data type

 CByte                Overflow                Byte cannot contain a
                                                     value this large

 CCur                12345.6789               Currency


 CDate             10/18/33 4:17:36PM         Date/Time
Function     Result        Resulting Data type

 CDbl      12345.6789      Double

 CDec      12345.6789      Decimal

 CInt         12346        Integer

 CLng         12346        Long

 CSng        12345.68      Single

  CSrt     “12345.67890”   String

  CVar     “12345.6789”    String
Objects
 Characteristics
  -building blocks of Visual Basic
- Object types already created - we make new instances
- Object types ' borrowed' from Windows environment
- Individual entities that are somewhat self-contained
- Can interact with other objects
- Some behavior 'built-in'
Objects
Objects
Objects
Objects
Objects
Objects
Objects
Objects
Objects
Objects
Objects

More Related Content

What's hot (20)

String in java
String in javaString in java
String in java
 
Popup boxes
Popup boxesPopup boxes
Popup boxes
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Dot net assembly
Dot net assemblyDot net assembly
Dot net assembly
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
 
Learn html Basics
Learn html BasicsLearn html Basics
Learn html Basics
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Introduction to CSS
Introduction to CSSIntroduction to CSS
Introduction to CSS
 
ASP.NET Web form
ASP.NET Web formASP.NET Web form
ASP.NET Web form
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Angularjs PPT
Angularjs PPTAngularjs PPT
Angularjs PPT
 
Spring JDBCTemplate
Spring JDBCTemplateSpring JDBCTemplate
Spring JDBCTemplate
 
Json
JsonJson
Json
 
Html frames
Html framesHtml frames
Html frames
 
PHP-MySQL Database Connectivity Using XAMPP Server
PHP-MySQL Database Connectivity Using XAMPP ServerPHP-MySQL Database Connectivity Using XAMPP Server
PHP-MySQL Database Connectivity Using XAMPP Server
 
Javascript validating form
Javascript validating formJavascript validating form
Javascript validating form
 

Viewers also liked

Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0Salim M
 
Introduction to visual basic programming
Introduction to visual basic programmingIntroduction to visual basic programming
Introduction to visual basic programmingRoger Argarin
 
Visual basic ppt for tutorials computer
Visual basic ppt for tutorials computerVisual basic ppt for tutorials computer
Visual basic ppt for tutorials computersimran153
 
Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)pbarasia
 
Chapter 1 — Introduction to Visual Basic 2010 Programming
Chapter 1 — Introduction to Visual Basic 2010 Programming Chapter 1 — Introduction to Visual Basic 2010 Programming
Chapter 1 — Introduction to Visual Basic 2010 Programming francopw
 
VB Function and procedure
VB Function and procedureVB Function and procedure
VB Function and procedurepragya ratan
 
Visual Basic Codes And Screen Designs
Visual Basic Codes And Screen DesignsVisual Basic Codes And Screen Designs
Visual Basic Codes And Screen Designsprcastano
 
visual basic 6.0
visual basic 6.0visual basic 6.0
visual basic 6.0lesly53
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual BasicSangeetha Sg
 
Creating a quiz using visual basic 6
Creating a quiz using visual basic 6Creating a quiz using visual basic 6
Creating a quiz using visual basic 6Ella Marie Wico
 
Visual Basic Programming
Visual Basic ProgrammingVisual Basic Programming
Visual Basic ProgrammingOsama Yaseen
 

Viewers also liked (20)

Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0
 
Introduction to visual basic programming
Introduction to visual basic programmingIntroduction to visual basic programming
Introduction to visual basic programming
 
Visual basic ppt for tutorials computer
Visual basic ppt for tutorials computerVisual basic ppt for tutorials computer
Visual basic ppt for tutorials computer
 
Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)
 
Visual Basic Controls ppt
Visual Basic Controls pptVisual Basic Controls ppt
Visual Basic Controls ppt
 
Chapter 1 — Introduction to Visual Basic 2010 Programming
Chapter 1 — Introduction to Visual Basic 2010 Programming Chapter 1 — Introduction to Visual Basic 2010 Programming
Chapter 1 — Introduction to Visual Basic 2010 Programming
 
Visual Basic 6.0
Visual Basic 6.0Visual Basic 6.0
Visual Basic 6.0
 
VB Function and procedure
VB Function and procedureVB Function and procedure
VB Function and procedure
 
Visual Basic Codes And Screen Designs
Visual Basic Codes And Screen DesignsVisual Basic Codes And Screen Designs
Visual Basic Codes And Screen Designs
 
Microsoft visual basic 6
Microsoft visual basic 6Microsoft visual basic 6
Microsoft visual basic 6
 
Vb file
Vb fileVb file
Vb file
 
The Best Source Code VB
The Best Source Code VBThe Best Source Code VB
The Best Source Code VB
 
Visual Basic 6.0
Visual Basic 6.0Visual Basic 6.0
Visual Basic 6.0
 
Visual basic 6.0
Visual basic 6.0Visual basic 6.0
Visual basic 6.0
 
visual basic 6.0
visual basic 6.0visual basic 6.0
visual basic 6.0
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual Basic
 
VB Script
VB ScriptVB Script
VB Script
 
Visual Basic 6.0
Visual Basic 6.0Visual Basic 6.0
Visual Basic 6.0
 
Creating a quiz using visual basic 6
Creating a quiz using visual basic 6Creating a quiz using visual basic 6
Creating a quiz using visual basic 6
 
Visual Basic Programming
Visual Basic ProgrammingVisual Basic Programming
Visual Basic Programming
 

Similar to visual basic for the beginner

Visual basic concepts
Visual basic conceptsVisual basic concepts
Visual basic conceptsmelody77776
 
VB6_INTRODUCTION.ppt
VB6_INTRODUCTION.pptVB6_INTRODUCTION.ppt
VB6_INTRODUCTION.pptBhuvanaR13
 
Programming basics
Programming basicsProgramming basics
Programming basicsSenri DLN
 
control structure in visual basic
control structure in visual basic control structure in visual basic
control structure in visual basic classall
 
Visual programming basic.ppt bs cs5th class
Visual programming basic.ppt bs cs5th classVisual programming basic.ppt bs cs5th class
Visual programming basic.ppt bs cs5th classmnewg218
 
Login Project with introduction .pptx
Login Project with introduction .pptxLogin Project with introduction .pptx
Login Project with introduction .pptxkulmiyealiabdille
 
Future Scope in Application Developement of Visual Basic
Future Scope in Application Developement of Visual BasicFuture Scope in Application Developement of Visual Basic
Future Scope in Application Developement of Visual Basicijtsrd
 
hjksjdhksjhcksjhckjhskdjhcskjhckjdppt.pptx
hjksjdhksjhcksjhckjhskdjhcskjhckjdppt.pptxhjksjdhksjhcksjhckjhskdjhcskjhckjdppt.pptx
hjksjdhksjhcksjhckjhskdjhcskjhckjdppt.pptxEliasPetros
 
Introduction to visual basic 6 (1)
Introduction to visual basic 6 (1)Introduction to visual basic 6 (1)
Introduction to visual basic 6 (1)Mark Vincent Cantero
 

Similar to visual basic for the beginner (20)

Vb basics
Vb basicsVb basics
Vb basics
 
Visual basic concepts
Visual basic conceptsVisual basic concepts
Visual basic concepts
 
Vb.net ide
Vb.net ideVb.net ide
Vb.net ide
 
Vb lecture
Vb lectureVb lecture
Vb lecture
 
unit 4.docx
unit 4.docxunit 4.docx
unit 4.docx
 
VB6_INTRODUCTION.ppt
VB6_INTRODUCTION.pptVB6_INTRODUCTION.ppt
VB6_INTRODUCTION.ppt
 
Programming basics
Programming basicsProgramming basics
Programming basics
 
control structure in visual basic
control structure in visual basic control structure in visual basic
control structure in visual basic
 
Visual programming basic.ppt bs cs5th class
Visual programming basic.ppt bs cs5th classVisual programming basic.ppt bs cs5th class
Visual programming basic.ppt bs cs5th class
 
Login Project with introduction .pptx
Login Project with introduction .pptxLogin Project with introduction .pptx
Login Project with introduction .pptx
 
Visual basic
Visual basic Visual basic
Visual basic
 
Meaning Of VB
Meaning Of VBMeaning Of VB
Meaning Of VB
 
Visual Programming
Visual ProgrammingVisual Programming
Visual Programming
 
Future Scope in Application Developement of Visual Basic
Future Scope in Application Developement of Visual BasicFuture Scope in Application Developement of Visual Basic
Future Scope in Application Developement of Visual Basic
 
hjksjdhksjhcksjhckjhskdjhcskjhckjdppt.pptx
hjksjdhksjhcksjhckjhskdjhcskjhckjdppt.pptxhjksjdhksjhcksjhckjhskdjhcskjhckjdppt.pptx
hjksjdhksjhcksjhckjhskdjhcskjhckjdppt.pptx
 
As pnet
As pnetAs pnet
As pnet
 
Tutorial 1
Tutorial 1Tutorial 1
Tutorial 1
 
Introduction to visual basic 6 (1)
Introduction to visual basic 6 (1)Introduction to visual basic 6 (1)
Introduction to visual basic 6 (1)
 
Visual basic
Visual basicVisual basic
Visual basic
 
Vb unit t 1.1
Vb unit t 1.1Vb unit t 1.1
Vb unit t 1.1
 

Recently uploaded

How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 

Recently uploaded (20)

How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 

visual basic for the beginner

  • 1. VISUAL PROGRAMMING VISUAL BASIC 6
  • 2. BASIC means Beginners' All-purpose Symbolic Instruction Code Procedural fashion But VB is event-driven It uses the VB IDE (Integrated Development Environment) VBA - Visual Basic for Applications VBScript
  • 3. Defining basic terms Application An application is a collection of objects that work together to accomplish something useful. In VB the application is called a Project. Object An object is a piece of software that has properties and functions that can be manipulated. A window is an object. Event-driven An event is something that happens - the user clicks on a button, a form is opened, and the result of a calculation is too large.
  • 4. Advantages of VB 1. VB applications are event-driven 2. VB supports the principals of objected-oriented design 3. VB is a complete windows application development system 4. VB uses ActiveX controls, dynamically linked libraries (DDL) and add-ins.
  • 5. Different type of projects Standard ActiveX Document EXE ActiveX EXE DHTML Application ActiveX DLL ActiveX Control Data Project IIS Application ActiveX Document DLL
  • 6. Standard : this project contains the standard set of controls and is used to create a basic windows application or to start a large application project. ActiveX EXE : This project helps you create an ActiveX executable component that can be executed from other applications. ActiveX DLL : An ActiveX DLL is used to contain controls and class code that can be used in other projects. ActiveX Control : This enables you to create a custom ActiveX control. Data Project : This project starts with database components already added to project file.
  • 7. IIS Application : This project is used to create an Internet Application. ActiveX Document DLL : This is used to by VB applications that will be installed and executed from the Internet. ActiveX Document EXE : This project is used to create an Internet- based VB application DHTML Application : This project creates a Web/HTML based application that can be executed only in a web browser.
  • 8. Different Components of a Project 1. Form (.frm) 7. ActiveX Controls (.ocx) 2. Class (.cls) 8. ActiveX Designers(.dsr) 3. Standard(.bas) 4. Resource(.res) 5. ActiveX documents(.doc) 6. User controls(.ctl) and Property Pages(.pag)
  • 9. From (.frm): form file contains the textual descriptions of the form and its controls, including their property settings. These files also have form level declarations for constants, variables and procedures. Class (.cls) : it is similar to a form file, except they have no visible user interface. You can create your own objects. Standard (.bas) : These files contain public or module-level declarations of types, constants, variables and procedures. Resource (.res) : A resource file can be contain bitmaps, text string and other data that you can change without having to re-edit and then recompile your program code.
  • 10. ActiveX documents (.doc) : These are similar to form files but are displayable only in an internet browser. User controls(.ctl) and Property Pages(.pag) : These are similar to form files but are used to create custom ActiveX controls and their associated properties. ActiveX Controls (.ocx) : These are optional controls that you can add to the toolbox and then use on the program’s forms. ActiveX Designers (.dsr) : These files are any of the new designer components available in VB (such as Data Environment Designer or Data Report Designer).
  • 11. ActiveX documents (.doc) : These are similar to form files but are displayable only in an internet browser. User controls(.ctl) and Property Pages(.pag) : These are similar to form files but are used to create custom ActiveX controls and their associated properties. ActiveX Controls (.ocx) : These are optional controls that you can add to the toolbox and then use on the program’s forms. ActiveX Designers (.dsr) : These files are any of the new designer components available in VB (such as Data Environment Designer or Data Report Designer).
  • 12. ActiveX documents (.doc) : These are similar to form files but are displayable only in an internet browser. User controls(.ctl) and Property Pages(.pag) : These are similar to form files but are used to create custom ActiveX controls and their associated properties. ActiveX Controls (.ocx) : These are optional controls that you can add to the toolbox and then use on the program’s forms. ActiveX Designers (.dsr) : These files are any of the new designer components available in VB (such as Data Environment Designer or Data Report Designer).
  • 13. IDE  The Visual Basic development environment contains these programming tools and windows, with which you construct your Visual Basic programs:  Menu bar  Toolbars  Visual Basic toolbox  Form window  Properties window  Project Explorer  Immediate window  Form Layout window
  • 14. Programming Tools 1. Menu bar  Located at the top of the screen, the menu bar provides access to the commands that control the Visual Basic programming environment.  Menus and commands work according to standard conventions used in all Windows-based programs.
  • 15. Programming Tools 2. Toolbars • Located below the menu bar, toolbars are collections of buttons that serve as shortcuts for executing commands and controlling the Visual Basic development environment. • You can open special-purpose toolbars by using the View menu Toolbars command.
  • 16. Programming Tools 3. Windows taskbar  This taskbar is located along the bottom of the screen.  You can use the taskbar to switch between Visual Basic forms as your program runs and to activate other Windowsbased programs.
  • 17. Toolbox Controls  You use special tools, called controls, to add elements of a program user interface to a form.  These resources in the toolbox, which is typically located along the left side of the screen.  (If the toolbox is not open, display it by using the Toolbox command on the View menu.)
  • 19. Form Window  When you start Visual Basic, a default form (Form1) with a standard grid (a window consisting of regularly spaced dots) appears in a pane called the Form window.  You can use the Form window grid to create the user interface and to line up interface elements.
  • 21. Form Window • Building Interface Elements • To build the interface elements, you click an interface control in the Visual Basic toolbox, and then you draw the user interface element on your form by using the mouse. • This process is usually a simple matter of clicking to position one corner of the element and then dragging to create a rectangle the size you want. • After you create the element — say, a text box — you can refine it by setting properties for the element. • In a text box, for example, you can set properties to make the text boldface, italic, or underlined.
  • 22. Properties Window  With the Properties window, you change the characteristics (property settings) of the user interface elements on a form.  A property setting is a characteristic of a user interface object.  For example, you can change the text displayed by a text box control to a different font, point size, or alignment.
  • 24. Properties Window  Properties Window Elements  The Properties window contains the following elements:  A drop-down list box at the top of the window, from which you select the object whose properties you want to view or set.  Two tabs, which list the properties either alphabetically or by category.  A description pane that shows the name of the selected property and a short description of it.
  • 25. Project Window  A Visual Basic program consists of several files that are linked together to make the program run.  The Visual Basic 6.0 development environment includes a Project window to help you switch back and forth between these components as you work on a project.
  • 27. Project Window  Project Window Components  The Project window lists all the files used in the programming process and provides access to them with two special buttons: View Code and View Object.
  • 28. Code Window  This computing logic is created using program statements — keywords,identifiers, and arguments — that clearly spell out what the program should do each step of the way.  You enter program statements in the Code window, a special text editing window designed specifically for Visual Basic program code.  You can display the Code window in either of two ways:  By clicking View Code in the Project window.  By clicking the View menu Code command.
  • 29. Form Layout Window  The Form Layout window is a visual design tool.  With it, you can control the placement of the forms in the Windows environment when they are executed.  When you have more than one form in your program, the Form Layout window is especially useful — you can arrange the forms onscreen exactly the way you want.  To position a form in the Form Layout window, simply drag the miniature form to the desired location in the window.
  • 31. Understanding the project explorer window It displays all the project’s components in a hierarchical list. There are three display options. View code, View object and Toggle folders. Setting Project options In VB we can set different properties associated with the project. It has three to five tabbed pages, depending on the type of project. These are general, make, compile, component and debugging tabs.
  • 32. VB Procedures Two types of procedures in VB are SUBROUTINES and FUNCTIONS Rules Unique name Not same as VB keywords or Built-in VBprocedures. A procedure can't contain other procedures within it.But can cal another procedure at any time
  • 33. Understanding Subroutines A subroutine (SUB) is a set of programming statements that is executed as a unit by VBA engine. Example: Private Sub Form_Load() subroutine declaration Dim sSQL As String Declarations . . . . . . Call fillcontros call another subroutine End Sub Subroutine terminator
  • 34. Components of VB Sub or Functions are Declaration Declarations area Statements Call to another procedure Terminator : END key word followed by the type of procedure
  • 35. Understanding functions It is similar to subroutine. The main difference is that a function returns a value. That means it returns the value through its name. Example:
  • 36. Public Function VerifyUser( ÙName as string) as Boolean If UName=” mes college” then VerifyUser = True Else VerifyUser = False Endif End Function
  • 37.
  • 38.
  • 39. Understanding Comments A comment is a plain text message you embed in the midst of your VBA code. A comment can include any printable character but must begin with a single quote (‘) or the key word Rem (Shorthand for remark).
  • 40. Using the Visual Basic Editor ie is Visual Basic Code window. Its parts are Project name : it appears in the code window’s title bar. Module name : it also appears in the code window’s title bar. it has direct access to the form and all the Object list : controls on them. It contains the names of all controls on the form, stored alphabetically.
  • 41. Procedure list : it contains all the corresponding event procedures for that control. Declaration area : at the top of every module is an area reserved for declaring variables and constant used within the module. Indicator bar : it is a vertical gray area along the left side of the code window.
  • 42. Procedure and full module view buttons : it shows procedure wise ie. only one procedure and all procedure view. Procedure separator: this is a thin horizontal gray line drawn between procedure in the code window. this module can contain any number of procedures. Procedure :
  • 43.
  • 44.
  • 45. Private Sub Form_Load ( ) Form1.show Print “Welcome to Visual Basic tutorial” End Sub
  • 46. Opening the Code Window First and easiest method is double-click any control on the design view An alternative path to the Code window is press F7 Right-click on the object and select the view code Right-click the name of a form in the projects window and select view code Click the view code button at the project window’s toolbar to open the module Crtl+F4 to close the code window and Alt+F4 shuts down VB
  • 47. Understanding Code Window Features Line continuation character – underscore character, it is shown that any line of code ending in an underscore character preceded by a space is recognized as a statement that is continued on the next line. Concatenation character “&” sSQL = "SELECT FirstName, LastName, " _ & "Title, HireDate, Extension " _ & "FROM Employees " _ & "ORDER BY LastName" VBA code window color cueing to set aside comments, keywords etc Global find and replace – you can search entire project ie all standard modules, form modules, class modules etc.
  • 48. Setting bookmarks in code This is useful for quickly jump between different locations in your VBA code. Toggle Bookmark : this add a bookmark to the current line of code window. If a bookmark previously set on that line will be removed. Next bookmark : it moves the editing cursor to the next available bookmark.
  • 49. Previous bookmark: it moves the editing cursor to the previous available bookmark. Clear all bookmark: removes all bookmark in all modules in the projects. Using automatic word completion VB can help you by completing long keywords as you type. As soon as you have typed enough of keywords for VB to determine which word you are typing, press Ctrl+Spacebar.
  • 50. It does not recognize the names of procedures or variables you are created in VB program. If you are not entering enough characters for VB to fill in the rest of the word, you will see a pop-up list of words to select from Understanding Editor Options Auto Indent : it causes code to be indented to the current depth in all successive lines of code.
  • 51. Auto Syntax Check: if selected VB checks each lines of code for syntax errors as you enter it in the code window. It checks spelling errors, missing commas and so no. Require Variable Declaration: if selected, this setting automatically inserts the option explicit directive into all VBA modules. Auto List Members : this timesaving option displays a list box that contains the members of an object’s object hierarchy in the code window.
  • 52. Auto Quick Info : if it is selected VB displays syntax help when you enter the name of a procedure( function,subroutine or method) followed by a period, space or opening parenthesis. Auto Data Tips : this option displays the value of variables when you hold the mouse cursor over a variable with the module in break mode. Drag-and-Drop Text Editing: this setting toggles drag and drop editing.
  • 53. Default to Full Module View: by default code window shows more than one procedure if the procedures are small enough to be seen in their entirely. Procedure separator : this the thin gray line that separates procedures in code window. Tab width : it specifies how many spaces will be inserted each time the tab key is pressed.
  • 54. Understanding the Editor Format Tab in the Options Dialog Box It contains settings that determine the overall appearance of the code window. Code Colors : the code window displays a variety of different types of code statements. Eg. Executable commands, comments beak point etc. There are three color settings for each of the 10 different code structures in the code window: foreground, background and indicator. Foreground and background are self-explanatory.
  • 55. Font and Size: this setting specify the font and font size used in code window. Margin Indicator Bar: it is the vertical, gray bar along the left side of the code window.
  • 56. Controlling Program Flow Using Conditional Branching A conditional branch executes blocks of statements depending on the value of an expression. Using if. . . then If (condition) Then Optional statement(s) End If
  • 57. Statement 1 Then If Expression Optional Statement(s) Statement 2
  • 58. Example: • If/Then/End If blocks to allow multiple statements: If Balance - Check < 0 Then Print "You are overdrawn" Print "Authorities have been notified" End If • In this case, if Balance - Check is less than zero, two lines of information are printed.
  • 59. The following is an alternative way to write an if statement If Balance - Check < 0 Then Print "You are overdrawn" Here the optional statement appears on the same line as the if , the end if statement isn’t needed.
  • 60. If . . . then . . . Else If (expression/condition) then Statement(s) if expressions is true Else Statement(s) if expressions is false End If
  • 61. Statement 1 Else If Statement(s) if Expressio Expression is false n Then Statement(s) if Expression is true End If Statement 2
  • 62. Example: • If/Then/Else/End If blocks: If Balance - Check < 0 Then Print "You are overdrawn" Print "Authorities have been notified" Else Balance = Balance - Check End If • Here, the same two lines are printed if you are overdrawn (Balance - Check < 0), • but, if you are not overdrawn (Else), your new Balance is computed.
  • 63. Example: Public Function VerifyUser(UName As String) As Boolean If UName = "Bob Smith" Then VerifyUser = True Else VerifyUser = False End If End Function
  • 64. If . . . then . . . ElseIf . . . End If If (expression 1/condition 1) then Statement(s) if expressions 1 is true Else If (expression 2/condition 2) then Statement(s) if expressions 2 is true Else If (expression N/condition N) then Statement(s) if expressions N is true End If
  • 65. Statement 1 Else Else If If If Expressio Expressio Expressio n1 n2 nN Then Then Then Statement(s) if Statement(s) if Statement(s) if Expression 1 is true Expression 2 is true Expression N is true End If Statement 2
  • 66. Example: • the ElseIf statement: • If Balance - Check < 0 Then Print "You are overdrawn" Print "Authorities have been notified" • ElseIf Balance - Check = 0 Then Print "Whew! You barely made it" Balance = 0 • Else Balance = Balance - Check • End If
  • 67. Using Select Case  The expression is evaluated at the top of the select case statement and compared with each of the candidate values in the body of the select case.  If none of the values match the expression, the select case simply ends.  An option Case Else can be added to the Select Case body to trap in the body to trap those instances where none of the candidate values match. 
  • 68. Statement case Expression Statement Block 1 Case Value 1 Statement Block 2 Case Value 2 Statement Block N Case ValueN End Select
  • 69. Example: Sub SelectCase(sPet As String) Select Case sPet Case "Dog“ MsgBox "It's a dog“ Case "Cat“ MsgBox "It's a cat“ Case "Bird“ MsgBox "It's a bird“ Case Else MsgBox "Unknown pet“ End Select End Sub
  • 70. Loops  For . . . Next  Syntax  For initialize the counter variable to upper limit [increment value] Statement(s)  Next counter variable  Here increment value is optional and by defaults to 1.
  • 71. For counter = start To end statements Next 1) The counter is set to the value of start. 2) Counter is checked to see if it is greater than end; if yes, control passes to the statement after the Next; if not the statements are executed. 3)At Next, counter is incremented and goes back to step 2).
  • 72. Establish upper limit and increment Value Statement Block Increment counter No Counter at upper limit? YES Continue processing ie. Next statement
  • 73. Example: Public Function ValidatePassword2() As Boolean Dim i As Integer Dim sPWD As String For i = 1 To 3 sPWD = InputBox("Enter the password") If sPWD = "xyzzy" Then Exit For End If Next i If i <= 3 Then ValidatePassword2 = True Else ValidatePassword2 = False End If End Function
  • 74. Do. . . Loop Here the statement block is preceded before the expression is evaluated. Syntax Do Statement 1 Statement 2 . . Statement n Loop Until Expression – Is- True
  • 75. Statement 1 Process Statement Block No Has condition been Met? YES Statement 2
  • 76. Example: Sum = 1 Do Print Sum Sum = Sum + 3 Loop Until Sum > 50 This loop repeats Until Sum is greater than 50. • And, like the previous example , a Do/Loop Until structure always executes at least once.
  • 77. Another do … loop form is instead of Until we use While keyword Syntax Do Statement 1 Statement 2 . . . Statement n Loop while Expression – Is- False
  • 78. Example Sum = 1 Do Print Sum Sum = Sum + 3 Loop While Sum <= 50 • This loop repeats While the Variable Sum is less than or equal to 50. • Note, since the While check is at the end of the loop, a Do/Loop While structure is always executed at least once.
  • 79. An alternate Do…Loop logic is that expression is evaluated at the top of the loop and statement block is never executed if the expression is true. Do Until Expression – Is- True Statement 1 Statement 2 . . . Statement n Loop
  • 80. Statement 1 YES Has Statement 2 condition been Met? No Process statement Block
  • 81. Example: Counter = 1 Do Until Counter > 1000 Print Counter Counter = Counter + 1 Loop •This loop repeats Until the Counter variable exceeds 1000. •Note a Do Until/Loop structure will not be entered if the Until • condition is already True on the first encounter.
  • 82. Do While condition statements Loop First, the condition is tested; if condition is True, then the statements are executed. When it gets to the Loop it goes back to the Do and tests condition again. If condition is False on the first pass, the statements are never executed Counter = 1 Do While Counter <= 1000 Print Counter Counter = Counter + 1 Loop
  • 83. Data type Storage Range size Byte 1 byte 0 to 255 Boolean 2 bytes True or False Integer 2 bytes -32,768 to 32,767 Long (long integer) 4 bytes -2,147,483,648 to 2,147,483,647 Single (single- 4 bytes precision floating- -3.402823E38 to -1.401298E-45 for negative values; point) 1.401298E-45 to 3.402823E38 for positive values Double (double- 8 bytes precision floating- -1.79769313486232E308 to -4.94065645841247E-324 point) for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values Currency -922,337,203,685,477.5808 to 8 bytes 922,337,203,685,477.5807 Date 8 bytes January 1, 100 to December 31, 9999 Object 4 bytes Any Object reference String various 0 to approximately 2 billion Variant various Same range as any numeric or string data type
  • 84. Byte A byte variable occupies only 8 bits. It can contain unsigned whole number values from 0 through 255. Negative numbers and numbers larger than 255 are not allowed. If do so it will return overflow error. Example Dim bByte As Byte Byte Integer It is similar to byte, except that it’s larger and can store negative numbers. It occupies 16 bits. And can hold whole numbers between -32768 to 32,767.
  • 85. Long It behaves exactly as integer values, except that it can assigned much larger and much smaller values than integer. Because long integer are 32 bits in size, they can hold positive and negative numbers range between -2,147,483,648 to 2,147,483,647 Single It contains floating point numbers. It can hold 32 bits. It is not Double suitable for financial and scientific calculations. Double It occupies 8 bytes of memory and can hold large and small floating point numbers. It is used for calculation requiring extreme precision.
  • 86. Currency It is reserved for storing numeric values such as bank account balance, prices and payroll information. Boolean It accept only True or False values. It stores internally as integer number. True is stored as -1 and false is 0.
  • 87. Date It contain only date and time data. It occupies 8 bytes and stored internally as a floating-point number. It hold all date and time values from January 1, 100 through December 31, 9999 and time from 00:00:00 to 23:59:59 one second increment. If we convert numeric value to date, the portion of the number to the left of the decimal point become the date and the decimal point become time.
  • 88. String It can holds data made up of letters, numbers and symbols you see on a keyboard. Visual Basic provides two type of string variables. Fixed length string and variable length string Fixed length – contains at most 65000 characters. Variable length – can be as long as 2 billion characters. Example Dim sFixed As String *10 ‘ a 10 character fixed width string.
  • 89. Dim sVariable As String ‘ a variable length string. In fixed width string, the strings are fit the width defined for the string. If we enter the word “Bcollege” to the sFixed variable in the above example, then the data actually stored is “Bcollege “ ie. the fixed width contains unwanted spaces. We can remove the unwanted spaces using different trim functions. Ltrim which removes leading spaces, Rtrim-removes trailing spaces and Trim – removes both leading and trailing spaces.
  • 90. Object There will be occasions when you’ll want to refer to a form on a form in code or establish a variable that represents a complex object with several different properties rather than a single value. In such cases, the object data type is suitable.
  • 91. Example Private Sub Form_Load() frmBuddy.Show Call UpdateCaptions(Me, txtCaption1) Call UpdateCaptions(frmBuddy, txtCaption2) bChanged False End Sub Public Sub UpdateCaptions(frm As Object, txt As Object) txt.Text = frm.Caption End Sub Specific object type references run faster than the generic object type. Private Sub Form_Load() frmBuddy.Show Call UpdateCaptions(Me, txtCaption1) Call UpdateCaptions(frmBuddy, txtCaption2) bChanged = False End Sub Public Sub UpdateCaptions(frm As Form, txt As TextBox) txt.Text = frm.Caption End Sub
  • 92. Variant The default Visual Basic data type is Variant It can accept any value. It can hold more storage space than other data types. Declaring Variables There are two ways to add variables to your applications.
  • 93. They are Implicit declaration – visual basic automatically create the variables for you. It means that Visual Basic automatically creates a variant for each identifier it recognizes as a variable in an application Example Private Sub cmdCombine_Click() FirstName = txtFN.Text LastName = txtLN.Text txtFullName = FN & " " & LN End Sub
  • 94. Explicit declaration - here we use one of the following keywords: Dim, Static, Private and Public. Syntax Dim VariableName As DataType Static VariableName As DataType Private VariableName As DataType Public VariableName As DataType
  • 95. Example Private Sub cmdCombine_Click() Dim FirstName As String Dim LastName As String FirstName = txtFN.Text LastName = txtLN.Text txtFullName = FN & " " & LN End Sub Compare Implicit and Explicit Variable performance
  • 96. Providing Names for your Variable These are the rules to follow when naming elements in VB - variables, constants, controls, procedures, and so on: • A name must begin with a letter of the alphabet. • The name must consist only of letters, digits and the underscore character (no punctuation mark are allowed) • May be as much as 255 characters long • Variable name can’t be duplicated within the same scope.
  • 97. Forcing Explicit Declaration Naming Convention Example : boolActive or factive, txtLS Under standing Variables Scope and Lifetime
  • 98. Converting Between Data Types Visual Basic provides several ways to convert values between different data types. Visual Basic automatically converts between the data types in the expression.
  • 99. Example Public Sub Conversion1 () Dim sSt As String Dim dDb As Double sSt = "12345.67890" dDb = sStr MsgBox "Value of dDb: " & dDb _ & vbCrLf & vbCrLf _ & "TypeName(dDbl): " & TypeName(dDbl) End Sub This process of automatic conversion is called coercion because Visual Basic forces the string value to a numeric value.
  • 100. Built-in conversion functions proved by the VBA language are When passed the string 12345.67890 Function Result Resulting Data type CByte Overflow Byte cannot contain a value this large CCur 12345.6789 Currency CDate 10/18/33 4:17:36PM Date/Time
  • 101. Function Result Resulting Data type CDbl 12345.6789 Double CDec 12345.6789 Decimal CInt 12346 Integer CLng 12346 Long CSng 12345.68 Single CSrt “12345.67890” String CVar “12345.6789” String
  • 102. Objects  Characteristics -building blocks of Visual Basic - Object types already created - we make new instances - Object types ' borrowed' from Windows environment - Individual entities that are somewhat self-contained - Can interact with other objects - Some behavior 'built-in'