Your SlideShare is downloading. ×
visual basic for the beginner
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

visual basic for the beginner

3,273
views

Published on

introduction to vb

introduction to vb

Published in: Education, Technology

2 Comments
1 Like
Statistics
Notes
No Downloads
Views
Total Views
3,273
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
361
Comments
2
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. VISUAL PROGRAMMING VISUAL BASIC 6
  • 2. BASICmeans Beginners All-purpose Symbolic Instruction CodeProcedural fashionBut 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 applicationDHTML Application : This project creates a Web/HTML based application that can be executed only in a web browser.
  • 8. Different Components of a Project1. 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 Tools1. 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 Tools2. 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 Tools3. 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.)
  • 18. Toolbox Controls
  • 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.
  • 20. Form Window
  • 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.
  • 23. Properties Window
  • 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.
  • 26. Project Window
  • 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.
  • 30. Form Layout 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 FUNCTIONSRules Unique name Not same as VB keywords or Built-in VBprocedures. A procedure cant contain other procedures within it.But can cal another procedure at any time
  • 33. Understanding SubroutinesA subroutine (SUB) is a set of programming statements that isexecuted 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. 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).
  • 38. 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.
  • 39. 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.
  • 40. 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 :
  • 41. Private Sub Form_Load ( ) Form1.show Print “Welcome to Visual Basic tutorial”End Sub
  • 42. 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
  • 43. 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.
  • 44. 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.
  • 45. 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.
  • 46. 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 fromUnderstanding Editor Options Auto Indent : it causes code to be indented to the current depth in all successive lines of code.
  • 47. 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.
  • 48. 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.
  • 49. 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.
  • 50. Understanding the Editor Format Tab in the OptionsDialog 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.
  • 51. 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.
  • 52. 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
  • 53. Statement 1 Then IfExpression Optional Statement(s) Statement 2
  • 54. 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.
  • 55. 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.
  • 56. If . . . then . . . Else If (expression/condition) then Statement(s) if expressions is true Else Statement(s) if expressions is false End If
  • 57. Statement 1 Else If Statement(s) if Expressio Expression is false n Then Statement(s) ifExpression is true End If Statement 2
  • 58. 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.
  • 59. Example:Public Function VerifyUser(UName As String) As Boolean If UName = "Bob Smith" Then VerifyUser = True Else VerifyUser = False End If End Function
  • 60. 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
  • 61. Statement 1 Else Else If If If Expressio Expressio Expressio n1 n2 nNThen Then Then Statement(s) if Statement(s) if Statement(s) ifExpression 1 is true Expression 2 is true Expression N is true End If Statement 2
  • 62. 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
  • 63. 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.
  • 64. Statement case Expression Statement Block 1 Case Value 1 Statement Block 2 Case Value 2 Statement Block N Case ValueN End Select
  • 65. Example:Sub SelectCase(sPet As String) Select Case sPet Case "Dog“ MsgBox "Its a dog“ Case "Cat“ MsgBox "Its a cat“ Case "Bird“ MsgBox "Its a bird“ Case Else MsgBox "Unknown pet“ End SelectEnd Sub
  • 66. 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.
  • 67. For counter = start To end statementsNext1) The counter is set to the value of start.2) Counter is checked to see if it is greater than end; if yes, controlpasses to the statement after the Next; if not the statements areexecuted.3)At Next, counter is incremented and goes back to step 2).
  • 68. Establish upper limitand increment Value Statement Block Increment counter No Counter at upper limit?YESContinue processing ie. Next statement
  • 69. 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
  • 70. 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
  • 71. Statement 1Process Statement Block No Has condition been Met?YES Statement 2
  • 72. 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.
  • 73. Another do … loop form is instead of Until we use While keywordSyntax Do Statement 1 Statement 2 . . . Statement n Loop while Expression – Is- False
  • 74. ExampleSum = 1Do Print Sum Sum = Sum + 3Loop While Sum <= 50• This loop repeats While the Variable Sum is less thanor equal to 50.• Note, since the While check is at the end of the loop, aDo/Loop While structure is always executed at leastonce.
  • 75. An alternate Do…Loop logic is that expression is evaluated at the topof the loop and statement block is never executed if the expression istrue. Do Until Expression – Is- True Statement 1 Statement 2 . . . Statement n Loop
  • 76. Statement 1 YES Has Statement 2 condition been Met? NoProcess statement Block
  • 77. Example:Counter = 1Do Until Counter > 1000 Print Counter Counter = Counter + 1Loop•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.
  • 78. Do While condition statementsLoopFirst, the condition is tested; if condition is True, then the statementsare executed. When it gets to the Loop it goes back to the Do andtests condition again. If condition is False on the first pass, thestatements are never executed Counter = 1 Do While Counter <= 1000 Print Counter Counter = Counter + 1 Loop
  • 79. Data type Storage Range sizeByte 1 byte 0 to 255Boolean 2 bytes True or FalseInteger 2 bytes -32,768 to 32,767Long (long integer) 4 bytes -2,147,483,648 to 2,147,483,647Single (single- 4 bytesprecision floating- -3.402823E38 to -1.401298E-45 for negative values;point) 1.401298E-45 to 3.402823E38 for positive valuesDouble (double- 8 bytesprecision floating- -1.79769313486232E308 to -4.94065645841247E-324point) for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive valuesCurrency -922,337,203,685,477.5808 to 8 bytes 922,337,203,685,477.5807Date 8 bytes January 1, 100 to December 31, 9999Object 4 bytes Any Object referenceString various 0 to approximately 2 billionVariant various Same range as any numeric or string data type
  • 80. 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 ByteByte 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.
  • 81. 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 notDouble 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.
  • 82. 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.
  • 83. DateIt contain only date and time data. It occupies 8 bytes andstored internally as a floating-point number.It hold all date and time values from January 1, 100 throughDecember 31, 9999 and time from 00:00:00 to 23:59:59 onesecond increment.If we convert numeric value to date, the portion of the number tothe left of the decimal point become the date and the decimalpoint become time.
  • 84. 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.
  • 85. Dim sVariable As String ‘ a variable length string.In fixed width string, the strings are fit the width defined forthe string. If we enter the word “Bcollege” to the sFixedvariable 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 trimfunctions. Ltrim which removes leading spaces, Rtrim-removestrailing spaces and Trim – removes both leading and trailingspaces.
  • 86. 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.
  • 87. 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
  • 88. 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.
  • 89. 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
  • 90. 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
  • 91. Example Private Sub cmdCombine_Click() Dim FirstName As String Dim LastName As String FirstName = txtFN.Text LastName = txtLN.Text txtFullName = FN & " " & LN End SubCompare Implicit and Explicit Variable performance
  • 92. 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.
  • 93. Forcing Explicit DeclarationNaming Convention Example : boolActive or factive, txtLSUnder standing Variables Scope and Lifetime
  • 94. 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.
  • 95. ExamplePublic 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 SubThis process of automatic conversion is called coercionbecause Visual Basic forces the string value to a numericvalue.
  • 96. Built-in conversion functions proved by the VBA language are When passed the string 12345.67890Function 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
  • 97. 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
  • 98. 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
  • 99. Objects
  • 100. Objects
  • 101. Objects
  • 102. Objects
  • 103. Objects
  • 104. Objects
  • 105. Objects
  • 106. Objects
  • 107. Objects
  • 108. Objects
  • 109. Objects

×