Vb 6ch123


Published on

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Vb 6ch123

  1. 1. 3 Cube Computer Institute – VB 6 Notes CHAPTER 1 Introduction to Visual Basic 6.0Visual basic is a high level programming language (HLL) developed from the BASIC programminglanguage.VB programming is done in a graphical environment, also known as GUI (Graphical User Interface).Visual Basic enables the user to design the user interface quickly by drawing and arranging the userelements. The Window GUI defines how the various elements such as FORMS and CONTROLS lookand function.Visual Basic is an event-driven programming language.Procedural vs. OOP vs. event-driven programming languageIn the Procedural languages such as Basic, C, COBOL, etc the program specifies exact sequence of alloperations. Program logic determines the next instruction to execute in response to conditions anduser request.OOPs define software as a collection of discrete oblects that specify both data structure and behavior.OOPs Identify following aspects: Data abstraction, Inheritence, Polymorphism, Encapsulation(information hiding)etc.Event Driven Programming:Events are the actions that are performed by the user during the application usage. If a user clicks amouse button on any object then the Click event occurs. If a user moves the mouse then the mousemove event occursAny programming language, which uses these events to run a specific portion of the program, will becalled event driver programming. The GUI based programs are all developed using event driverprogramming.In the event driven model programs are no longer procedural; the do not follow a sequential logic.The programmers do not take control and determine the sequence of execution of program. Instead,the user can press and click on various button and boxes in a window. Each user action can cause anevent to occur, which triggers a Basic procedure (code) that you have written.The Object model in VB 6:In VB you will work with Objects, which have Properties and methods.OBJECTS:Think of an Object as a thing. Examples of Objects are Forms and Controls. Forms are the windowsand dialog boxes you place on the screen; Controls are the elements you place inside a form, such astext coxes, command button, etc.Properties:Properties tell something about the Object, such as its name, color, size, etc or how it will behave. Torefer to a property of an Object, VB syntax is: Object.Property For example, to refer to text property of Text Box named text1, we use text1.TextMethods:Actions associated with the objects are called Methods. Example: Move, Print, Resize, Clear. Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -1-
  2. 2. 3 Cube Computer Institute – VB 6 NotesVB6 Environment / IDE (Integrated Development Environment)The VB6 environment is where you create and test your projects. Fig 2 shows various windows inVB6 environment. Each window can be moved, resized, opened, or closed.Various windows in VB6 environment are:Main VB WindowThe main VB Window holds the VB Menu bar, the toolbar, and the form location and size informationFORM WINDOWThe form window is where you design the forms that makes up your user interface. When you begina new project, VB gives your form name the default name Form1.The Project Explorer WindowThis window holds the filenames for the files included in your project.Fig 3: Project Explorer WindowThe Properties WindowWe use the properties window to set the properties for the objects in the project.The Form Layout WindowThe position of the form in this window determines the position of the form on the desktop whenexecution of the project begins.The ToolboxToolbox window contains a set of controls which are used to customize forms. Using this controlsuser can create an interface between user and the applicationFigure 4 Toolbox windows with its controls available commonly. Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -2-
  3. 3. 3 Cube Computer Institute – VB 6 NotesControl DescriptionPointer used to interact with the controls on the formPictureBox used to display imagesTextBox used to accept user input which can display only editable textFrame used to group other controlsCommandButton used to initiate an action by pressing on the buttonCheckBox used to do a choice for user (checked or unchecked)OptionButton used in groups where one at a time can be trueListBox used to provide a list of itemsComboBox used to provide a short list of itemsHScrollBar a horizontal scrollbarVScrollBar a vertical scrollbarTimer used to perform tasks in specified intervals.DriveListBox used to access to the system drivesDirListBox used to access to the directories on the systemFileListBox used to access to the files in the directoryShape used to draw circles, rectangles, squares, ellipsesLine used to draw linesImage used to display images. But less capability than the PictureBoxData used to connect a databaseOLE used to interact with other windows applicationsLabel used to display texts which cannot be editedThe ToolbarWe can use the buttons on the toolbar for frequently used operations. Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -3-
  4. 4. 3 Cube Computer Institute – VB 6 NotesWORKING MODES IN VISUAL BASICVB has 3 distinct modes:Design modeWhile you are designing the user interface and writing code, you are in design mode.Runtime modeWhen you are testing and running your project, you are in runtime mode.Break ModeIf you get a run-time error or pause project execution, you are in break time mode.VISUAL BASIC CODE STATEMENTSThe basic program in VB requires 3 statements:1.The Remark StatementsRemark statements are sometimes called as COMMENTS, are used for project documentation only.They are not considered “executable” and have no effect when the project runs. The purpose ofremarks is to make the project more readable and understandable by the person who reads it.VB remarks begin with an apostrophe. Example: ‘this project is made in VB6 ‘Exit the project Text1.Text=”Welcome” ‘set the text property of text1 to welcome.2. The Assignment StatementsThe assignments statement assigns a value to a property or variable. Syntax: [Let] Object.Property = value The LET is optional and may be included if you wish. Example: Text1.Text=”welcome” Let lblName = ”ABC” Lblname.FontSize = 123. The END statementThe END statement stops execution of the project. Example, Include an END statement in the subprocedure for an EXIT buttonFIRST VB PROJECTGetting startedTo open the Visual Basic environment and to work with it select and click on Microsoft Visual Basic6.0 in the start menu. When Visual Basic is loaded the New Project dialog shown in figure 1.1 will bedisplayed with the types available in Visual Basic. You can notice that Standard Exe is highlighted bydefault. Standard Exe allows the user to create standard executable. Standard executable is a typewhich has most of the common features of Visual basic Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -4-
  5. 5. 3 Cube Computer Institute – VB 6 NotesDesign the FORM Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -5-
  6. 6. 3 Cube Computer Institute – VB 6 NotesSetting the PropertyObject Property ValueForm1 Name Form1 Caption Form1Command1 Name cmdOK Caption OKCommand2 Name cmdExit Caption ExitText1 Name txtName TextCode Private Sub cmdExit_Click() txtName.Text = "Welcome to VB 6" End Sub Private Sub cmdOK_Click() End End SubRun The Project Press F5 or Start button on the toolbar to run the project.Save the projectWhile saving the project, The Project file is saved with extension .vbp The form file is saved with extension .frm The module file is saved with extension .bas The custom controls is saved with extension .ocxNaming Rules and Convention for Object:Naming Rules: When you select names for object, VB requires the name to begin with a letter. The name can be up to 40 characters in length and can contain letter, digits and underscore. An object name cannot include a space or punctuation marks.The naming Convention Always begin a name with lowercase 3 letter prefix, which identifies the object type (such as label, command button, etc.) and capitalize the first character after the prefix( the real name of the object). For names with multiple words, capitalize each word in the name. All names must be meaningful and indicate the purpose of the Object. Example: lblMessage, cmdOk, cmdExit, lblDiscountRate, etc.Object naming conversions of controls (prefix)Form -frmLabel -lblTextBox -txtCommandButton -cmdCheckBox -chkOptionButton -optComboBox -cboListBox -lstFrame -fmePictureBox -picImage -imgShape -shpLine -lin Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -6-
  7. 7. 3 Cube Computer Institute – VB 6 NotesHScrollBar -hsbVScrollBar -vsbTYPES OF ERRORS1. COMPILE ERRORS The VB attempts to convert your program code to machine language (called compiling thecode) ,it finds any compile errors .You get the compile errors when you break the syntax rules ofVisual basics and sometimes when you use an illegal object or property.For example, try spelling end as ennd. txtName.Text=”ABC” is correct but txt,name=”ABC” is incorrect.2. RUN-TIME ERRORSIf your projects halts during execution, that’s run time errors. VB displays a dialog box and goes intobreak mode and highlights the statement causing the error.Statements that cannot be executed correctly causes runtime errors. Such statements are compiledcorrectly but fail too execute.Examples: calculation with non-numeric value, divide by zero, square of negative number.3. LOGICAL ERRORSWith logic errors, a project run but produces incorrect results. Example, result of a calculation isincorrect or the wrong text appears or the text is OK but appears in the wrong location.CONTEXT SENSITIVE HELPVB 6 provides a great HELP section, if MSDN Library is installed in your machine. For ContextSensitive Help, select a VB object, such as Text Boxes, or place the insertion point in a word in theeditor and Press F1. The MSDN Library viewer will open on the correct page, if possible, saving you asearch. Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -7-
  8. 8. 3 Cube Computer Institute – VB 6 Notes CHAPTER 2 More ControlsIn this chapter we will be discussing about various controls in VB6.LABEL CONTROL:A label control displays text that the user cannot directly change.You can use labels to identify controls, such as text boxes and scroll bars that do not have their ownCaption property. Example: lblName.Caption=”ABC”The actual text displayed in a label is controlled by the Caption property, which can be set at designtime in the Properties window or at run time by assigning it in code.To clear a Label’s caption: lblMessage.Caption=””TEXT CONTROL:Text boxes are versatile controls that can be used to get input from the user or to display text. Textboxes should not be used to display text that you dont want the user to change, unless youve set theLocked property to True.The actual text displayed in a text box is controlled by the Text property.It can be set in three different ways: 1. at design time in the Property window, 2. at run time by setting it in code, example: txtMessage.text=”Welcome” 3. by input from the user at run time.The current contents of a text box can be retrieved at run time by reading the Text property.Multiple-Line Text Boxes and Word WrapBy default, a text box displays a single line of text and does not display scroll bars. If the text is longerthan the available space, only part of the text will be visible. The look and behavior of a text box canbe changed by setting two properties, MultiLine and ScrollBars, which are available only at designtime.Note The ScrollBars property should not be confused with scroll bar controls, which are notattached to text boxes and have their own set of properties.Setting MultiLine to True enables a text box to accept or display multiple lines of text at run time.Alignment Property of Text BoxYou must set the Multiline property to true or VB ignores the alignment.The values of alignment property, which can be set at Design time (not at run time), are:0 – Left Justify 1 – Right Justify 2 – CenterTo clear a text box at runtime: txtMessage.Text=””FRAMESFrame controls are used to provide an identifiable grouping for other controls. For example, you canuse frame controls to subdivide a form functionally — to separate groups of option button controls.In most cases, you will use the frame control passively — to group other controls — and will have noneed to respond to its events. You will, however, most likely change its Name, Caption, or Fontproperties.Adding a Frame Control to a FormWhen using the frame control to group other controls, first draw the frame control, and then drawthe controls inside of it. This enables you to move the frame and the controls it contains together. Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -8-
  9. 9. 3 Cube Computer Institute – VB 6 NotesDrawing Controls inside the FrameTo add other controls to the frame, draw them inside the frame. If you draw a control outside theframe, or use the double-click method to add a control to a form, and then try to move it inside theframe control, the control will be on top of the frame and youll have to move the frame and controlsseparately.Note If you have existing controls that you want to group in a frame, you can select all the controls,cut them to the clipboard, select the frame control, and then paste them into the frame control.CHECK BOXCheckboxes allow the user to select (or deselect) an option.In any group of checkboxes, any number may be selected.The value property of a check box is set to 0 if Unchecked (default), 1 if Checked, and 2 if Grayed(dimmed). Example: chkDiscount.Value=0 ‘Unchecked chkDiscount.Value=1 ‘checked chkDiscount.Value=2 ‘grayed chkDiscount.Value=checked chkDiscount.Value=uncheckedOPTION BUTTONS:Option buttons present a set of two or more choices to the user.Unlike check boxes, however, option buttons should always work as part of a group; selecting oneoption button immediately clears all the other buttons in the group.Defining an option button group tells the user, "Here is a set of choices from which you can chooseone and only one.”Creating Option Button GroupsAll of the option buttons placed directly on a form (that is, not in a frame or picture box) constituteone group. If you want to create additional option button groups, you must place some of them insideframes or picture boxes.All the option buttons inside any given frame constitute a separate group.Selecting or Disabling Option ButtonsAn option button can be selected by:Clicking it at run time with the mouse.Tabbing to the option button group and then using the arrow keys to select an option button withinthe group.Assigning its Value property to True in code: optChoice.Value = True or optChoice.Value = FalseTo make a button the default in an option button group, set its Value property to True at designtime. It remains selected until a user selects a different option button or code changes it.Images Control:The image control is used only for displaying pictures.Pictures are loaded into the image control just as they are in the picture box: at design time, set thePicture property to a file name and path; at run time, use the LoadPicture function.It has a Stretch property while the picture box has an AutoSize property. Setting the AutoSizeproperty to True causes a picture box to resize to the dimensions of the picture; setting it to Falsecauses the picture to be cropped (only a portion of the picture is visible).You can set the Visible property to TRUE to make the image invisible.Example: imgLogo.Visible=FalseSHAPE CONTROLThe shape control is used to create the following predefined shapes on forms, frames, or pictureboxes: rectangle, square, oval, circle, rounded rectangle, or rounded square. Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -9-
  10. 10. 3 Cube Computer Institute – VB 6 NotesPredefined ShapesThe Shape property of the shape control provides you with six predefined shapes. The followingtable lists all the predefined shapes, their values and equivalent Visual Basic constants:Shape Style ConstantRectangle 0 vbShapeRectangleSquare 1 vbShapeSquareOval 2 vbShapeOvalCircle 3 vbShapeCircleRounded Rectangle 4 vbShapeRoundedRectangleRounded Square 5 vbShapeRoundedSquareLINE CONTROLThe line control is used to create simple line segments on a form, a frame, or in a picture box.You can control the position, length, color, and style of line controls to customize the look ofapplications.CHANGING FONT PROPERTIES OF CONTROLSAt design time use the Font property to open Font dialog.At runtime we use Font Object. A font object has several properties including Name, size, Bold, Italic,Underline, etc.Example: Object.Font.Bold=True Object.Font.Italic=True Object.Font.UnderLine=True Object.Font.Size=12CHANGING COLOR PROPERTIES OF CONTROLSAt designtime we can use ForeColor property to change the color of text/caption in control.At runtime we can use ForeColor property.The VB6 provides 8 color constants to use: vbBlack, vbRed, vbGreen, vbYellow, vbBlue, vbMagenta, vbCyan, vbWhiteExample: txtName.ForeColor=vbRedlblMessage.ForeColor=vbGreen Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 10 -
  11. 11. 3 Cube Computer Institute – VB 6 NotesCHECK BOX AND OPTION BUTTON EXAMPLE Private Sub chkBold_Click() Text1.Font.Bold = True End Sub Private Sub chkItalic_Click() Text1.Font.Italic = True End Sub Private Sub chkUnderline_Click() Text1.Font.Underline = True End Sub Private Sub optRed_Click() Text1.ForeColor = vbRed End Sub Private Sub optGreen_Click() Text1.ForeColor = vbGreen End Sub Private Sub optBlue_Click() Text1.ForeColor = vbBlue End Sub Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 11 -
  12. 12. 3 Cube Computer Institute – VB 6 NotesSHAPE CONTROL EXAMPLE Private Sub cmdRectangle_Click() Shape1.Shape = 0 End Sub Private Sub cmdSquare_Click() Shape1.Shape = 1 End Sub Private Sub Oval_Click() Shape1.Shape = 2 End Sub Private Sub cmdCircle_Click() Shape1.Shape = 3 End Sub Private Sub cmdRoundedRectangle_Click() Shape1.Shape = 4 End Sub Private Sub cmdRoundedSquare_Click() Shape1.Shape = 5 End SubDEFINING KEYBOARD ACCESS KEYSMany people prefer to use the keyboard, rather than a mouse, for most operations.You can make your program respond to keyboard by defining access keys. For example: In the below diagram, you can select the OK button by pressing alt+o and the exit button by pressing alt+e. Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 12 -
  13. 13. 3 Cube Computer Institute – VB 6 NotesWe can set access keys for command button, option buttons and check boxes. When you define theirCaption property. Type an ampersand (&) in front of the character you want for the access key; VBunderlines the character. For example: &OK for OK E&xit for ExitSpecifying the Default and Cancel PropertiesOn each form, you can select a command button to be the default command button — that is,whenever the user presses the ENTER key the command button is clicked regardless of which othercontrol on the form has the focus. To specify a command button as default set the Default property toTrue.You can also specify a cancel button. When the Cancel property of a command button is set to True,it will be clicked whenever the user presses the ESC key, regardless of which other control on theform has the focus.Setting the Tab OrderThe tab order is the order in which a user moves from one control to another by pressing the TABkey. Each form has its own tab order. Usually, the tab order is the same as the order in which youcreated the controls.For example, assume you create two text boxes, Text1 and Text2, and then a command button,Command1. When the application starts, Text1 has the focus. Pressing TAB moves the focus betweencontrols in the order they were createdTo change the tab order for a control, set the TabIndex property. The TabIndex property of acontrol determines where it is positioned in the tab order. By default, the first control drawn has aTabIndex value of 0, the second has a TabIndex of 1, and so on. When you change a controls taborder position, Visual Basic automatically renumbers the tab order positions of the other controls toreflect insertions and deletions. For example, if you make Command1 first in the tab order, theTabIndex values for the other controls are automatically adjusted upward, as shown in the followingtable. TabIndex before it is changed TabIndex after it is changedControlText1 0 1Text2 1 2Command1 2 0The highest TabIndex setting is always one less than the number of controls in the tab order(because numbering starts at 0). Even if you set the TabIndex property to a number higher than thenumber of controls, Visual Basic converts the value back to the number of controls minus 1.Note Controls that cannot get the focus, as well as disabled and invisible controls, dont have aTabIndex property and are not included in the tab order. As a user presses the TAB key, thesecontrols are skipped.Removing a Control from the Tab OrderUsually, pressing TAB at run time selects each control in the tab order. You can remove a controlfrom the tab order by setting its TabStop property to False (0).A control whose TabStop property has been set to False still maintains its position in the actual taborder, even though the control is skipped when you cycle through the controls with the TAB key.CREATING TOOLTIPSThe word or short phrase that describes the function of a toolbar button or other tool. The ToolTipappears when you pause the mouse pointer over an object. Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 13 -
  14. 14. 3 Cube Computer Institute – VB 6 NotesToolTipText PropertyReturns or sets a ToolTip.At design time you can set the ToolTipText property string in the controls properties dialog box.At Run-time: object.ToolTipText [= string]The ToolTipText property syntax has these parts:Part Descriptionobject An object expression that evaluates to an object in the Applies To list.string A string associated with an object in the Applies To list. that appears in a small rectangle below the object when the users cursor hovers over the object at run time for about one second.With StatementExecutes a series of statements on a single object or a user-defined type.Syntax With object [statements] End WithThe With statement syntax has these parts:Part Descriptionobject Required. Name of an object or a user-defined type.statements Optional. One or more statements to be executed on object.RemarksThe With statement allows you to perform a series of statements on a specified object withoutrequalifying the name of the object. For example, to change a number of different properties on asingle object, place the property assignment statements within the With control structure, referringto the object once instead of referring to it with each property assignment. The following exampleillustrates use of the With statement to assign values to several properties of the same object. With MyLabel .Height = 2000 .Width = 2000 .Caption = "This is MyLabel" End WithNote Once a With block is entered, object cant be changed. As a result, you cant use a single Withstatement to affect a number of different objects.Concatenating Strings:Used to force string concatenation of two expressions.Syntax Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 14 -
  15. 15. 3 Cube Computer Institute – VB 6 Notes result = expression1 & expression2The & operator syntax has these parts:Part Descriptionresult Required; any String or Variant variable.expression1 Required; any expression.expression2 Required; any expression. Example: txtOutPut.Text= “Welcome ” & “ To VB 6” txtName.Text= txtFirstName.Text & “ ” & txtLastName.TextRemarksIf an expression is not a string, it is converted to a String variant. The data type of result is String ifboth expressions are string expressions; otherwise, result is a String variant. If both expressions areNull, result is Null. However, if only one expression is Null, that expression is treated as a zero-lengthstring ("") when concatenated with the other expression. Any expression that is Empty is also treatedas a zero-length string. Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 15 -
  16. 16. 3 Cube Computer Institute – VB 6 Notes CHAPTER 3 Variables, Constants and CalculationsVariables and ConstantsMemory locations that hold data that can be changed during project execution are called Variables.Memory locations that hold data that cannot be changed during project execution are calledVariables.For example,Variable: a customer’s name will vary as the information for each individual is being processed.Constant: However the name of the company and the sales tax rate will remain the same.Identifier:When you declare a variable or named constant, VB reserves an area of memory and assigns it aname, called an Identifier.Data types in visual basic 6.0The data type of a variable or constant indicates what type of information will be stored in theallocated memory space.The default data type is Variant.If you do not specify a data type, your variables and constant will be Variants.Advantages & Disadvantages of using Variant data type:Advantages Disadvantages1.It’s easy 1. Less efficient than other data types, i.e., they2. variables and constants change their require more memory space and operate lessappearance as needed for each situation. quickly than other data types.The best practice is always specify the data types.Other data types are:1. NumericByte Store integer values in the range of 0 - 255Integer Store integer values in the range of (-32,768) - (+ 32,767)Long Store integer values in the range of (- 2,147,483,468) - (+ 2,147,483,468)Single Store floating point value in the range of (-3.4x10-38) - (+ 3.4x1038)Double Store large floating value which exceeding the single data type value store monetary values. It supports 4 digits to the right of decimal point andCurrency 15 digits to the left2. StringUse to store alphanumeric values. A variable length string can store approximately 4 billioncharacters3. DateUse to store date and time values. A variable declared as date type can store both date and timevalues and it can store date values 01/01/0100 up to 12/31/99994. BooleanBoolean data types hold either a true or false value. These are not stored as numeric values andcannot be used as such. Values are internally stored as -1 (True) and 0 (False) and any non-zerovalue is considered as true.Naming rules and convention in VB 6.0These are the rules to follow when naming elements in VB - variables, constants, controls,procedures, and so on: Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 16 -
  17. 17. 3 Cube Computer Institute – VB 6 Notes * A name must begin with a letter. * May be as much as 255 characters long * Must not contain a space or an embedded period or type-declaration characters used to ype; these are ! # % $ & @ * Must not be a reserved word (that is part of the code, like Option, for example) * The dash, although legal, should be avoided because it may be confused with the minus sign. Instead of First-name use First_name or FirstName. * use a three letter prefix to append the name while declaring it.Examples: data type and their prefixes: bln Boolean cur Currency dbl Double-precision floating point dtm Date/ time int Integer lng Long Integer sng Single str String vnt VariantVariables:Variables are the memory locations which are used to store values temporarily. A defined namingstrategy has to be followed while naming a variable. A variable name must begin with an alphabetletter and should not exceed 255 characters. It must be unique within the same scope. It should notcontain any special character like %, &, !, #, @ or $.Declaring variablesTo declare a variable, we use DIM statement.DIM statement General Form: Dim identifier [as DataType]If you omit the optional data type, the variable’s type defaults to variant.Example: Dim vntChanging Dim strName as String Dim intTotal as IntegerThe reserved word Dim is really short for Dimension, which means “size”. When you declare avariable, the amount of memory reserved depends on its data types.Data Type Numer of Bytes of Memory AllocatedBoolean 2Byte 1Currency 8Date 8Double 8Integer 2Long 4Single 4String (Variable Length) 10 bytes plus 1 byte for each character in the stringVariant Holding Numbers – 16 bytes Holding Characters – 22 bytes plus 1 byte for each character in the string Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 17 -
  18. 18. 3 Cube Computer Institute – VB 6 NotesSCOPE OF VARIABLESThe visibility of a variable is referred to as its Scope. Visibility means “this variable can be seen orused in this location”The scope is said to be global, module level or local.Global variable A global variable may be used in all procedures of a project. To indicate a global levelvariable, place a prefix of g before the identifier.Example: gintTotalSumModule level variable Module level variables are accessible from all the procedure of a form. To indicate a modulelevel variable, place a prefix of m before the identifier.We place the module level variables and constants in the General Decalaration section of the form. Example: ______________________________ Option Explicit Dim mintTotal as Integer ______________________________ Private sub cmdSum_click() mintTotal=text1.text + text2.text End sub _______________________________ Private sub cmdTotal_click() mintTotal= mintTotal * 0.10 End sub ________________________________Local variable A local variable may be used only within the procedure in which it is defined. Any variablethat you declare inside a procedure is local in scope; it is known to that procedure.Example: Private sub cmdSum_click() Dim intNum as Integer Dim curPrice as Integer Dim blnCounter as Boolean End subConstant – Named and IntrinsicConstant provide a way to use words to describe a value that doesn’t change.Constant can be Named or Intrinsic.1. Named Constant:The constant that you define for yourself are called Named Constants. We give the constant a name, adata type and a value. Once a value is decaled as a constant, its value cannot be changed duringprogram execution.The data type and the data type of the value must match for a constant.We declare named constant using the keyword Const.General Form: Const Identifier [ As DataType ] = ValueExample: Const strAddress As String = “ Malad ” Const curSalesTaxRate as Currency = 0.08Assigning Values to ConstantString LiteralsString constants are called String literals and may contain letters, digits and special characters, suchas $#@%&*.Also, to declare a constant such as Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 18 -
  19. 19. 3 Cube Computer Institute – VB 6 Notes He said, “I liked it” , it are declared asConst strName as String=””He said, “I liked it”””Numeric ConstantsNumeric constants may contain only the digits (0-9), a decimalPoint and a sign(+ or -) at the left side. We cannot include a comma, dollar sign, any other specialcharacter, or a sign at the right side.Data Type Constant value ExampleInteger 125 2170Single or Currency 101.25 -5.2String literals “VB” “103” “She said ““Hello.”””2. Intrinsic ConstantIntrinsic constant are system-defined constants. Several sets of Intrinsic constants are stored inlibrary files and available for use in VB programs.Intrinsic constants use a 2-charater prefix to indicate the source, such as Vb for Visual basic, db for Access Objects and xl for Excel. Example: vbRed, vbGreen, etc.Operators in Visual BasicArithmetical OperatorsOperators Description Example Result+ Add 5+5 10- Substract 10-5 5/ Divide 25/5 5 Integer Division 203 6* Multiply 5*4 20^ Exponent (power of) 3^3 27Mod Remainder of division 20 Mod 6 2& String concatenation "George"&" "&"Bush" "George Bush"Relational OperatorsOperators Description Example Result> Greater than 10>8 True< Less than 10>8 False>= Greater than or equal to 20>=10 True Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 19 -
  20. 20. 3 Cube Computer Institute – VB 6 Notes<= Less than or equal to 10<=20 True<> Not Equal to 5<>4 True= Equal to 5=7 FalseLogical OperatorsOperators DescriptionOR Operation will be true if either of the operands is trueAND Operation will be true only if both the operands are trueVal FunctionA function performs an action and returns a Value.The Expression to operate upon, called the arguments, must be enclosed in parenthesis.The Val function converts text data into a numeric value.General form: Val(ExpressionToConvert)The expression can be the property of a control, a variable or a constant.A function cannot stand by itself. It returns a value that can be part of a statement, such as theassignment statements.Example: intQuantity=Val(txtQuantity.Text) curPrice=Val(txtPrice.Text)Important: When the Val function converts an argument to numeric, it begins at the argument’s leftmost character. If that character is a numeric digit, decimal point, or sign, It converts the character tonumeric and moves to the next character. As soon as a nonnumeric character is found, the operationstops. Example:Argument Numeric Value Returned by the Val Function(blank) 0123.45 123.45$100 01,000 1A123 0123A 1234C5 4-123 -123+123 12312.45.2 12.45 Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 20 -
  21. 21. 3 Cube Computer Institute – VB 6 NotesCALCULATOR PROGRAMCode: Private Sub cmdAdd_Click() txtOutput.Text = Val(txtNum1.Text) + Val(txtNum2.Text) End Sub Private Sub cmdDifference_Click() txtOutput.Text = Val(txtNum1.Text) - Val(txtNum2.Text) End Sub Private Sub cmdMultiply_Click() txtOutput.Text = Val(txtNum1.Text) * Val(txtNum2.Text) End Sub Private Sub Command4_Click() txtOutput.Text = Val(txtNum1.Text) / Val(txtNum2.Text) End SubFORMATTING DATAUse the formatting functions to format the data.To format means to control the way the output look.For example, 12 is just a number but $12.00 conveys more meaning for dollar amount.VB 6 introduces 4 new formatting functions –1. FormatCurrency FormatCurrency Returns an expression formatted as a number with a leading currency symbol ($) Simple Form FormatCurrency (Expression) General Form FormatCurrency (Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])2. FormatNumber FormatNumber Returns an expression formatted as a number Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 21 -
  22. 22. 3 Cube Computer Institute – VB 6 Notes Simple Form FormatNumber(Expression) General Form FormatNumber(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])3. FormatPercent FormatPercent Returns an expression formatted as a percentage (multiplied by 100) with a trailing % character. Simple Form FormatPercent (Expression) General Form FormatPercent (Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])For the examples below, assume dblTestNumber contains the value 12345.678Expression ResultFormatNumber(dblTestNumber, 2, True, True, True) 12,345.68FormatCurrency(dblTestNumber, 2, True, True, True) $12,345.68FormatPrecent(dblTestNumber, 2, True, True, True) 1,234,567.80%"Try It" Code: Private Sub cmdTryIt_Click() Dim dblTestNumber As Double dblTestNumber = Val(InputBox("Please enter a number:")) Print "Input: "; Tab(25); dblTestNumber Print "Using FormatNumber:"; Tab(25); FormatNumber(dblTestNumber, 2, True, True, True) Print "Using FormatCurrency:"; Tab(25); FormatCurrency(dblTestNumber, 2, True, True, True) Print "Using FormatPercent:"; Tab(25); FormatPercent(dblTestNumber, 2, True, True, True) End SubOutput: Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 22 -
  23. 23. 3 Cube Computer Institute – VB 6 Notes4. FormatDateTime FormatDateTime Returns an expression formatted as a date or time. Syntax: FormatDateTime(Date[,NamedFormat]) The FormatDateTime function syntax has these parts:Part DescriptionDate Required. Date expression to be formatted.NamedFormat Optional. Numeric value that indicates the date/time format used. If omitted, vbGeneralDate is used.Settings:The NamedFormat argument has the following settings:Constant Value DescriptionvbGeneralDate 0 Display a date and/or time. If there is a date part, display it as a short date. If there is a time part, display it as a long time. If present, both parts are displayed. Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 23 -
  24. 24. 3 Cube Computer Institute – VB 6 NotesvbLongDate 1 Display a date using the long date format specified in your computers regional settings.vbShortDate 2 Display a date using the short date format specified in your computers regional settings.vbLongTime 3 Display a time using the time format specified in your computers regional settings.vbShortTime 4 Display a time using the 24-hour format (hh:mm)."Try It" Code: Private Sub cmdTryIt_Click() Print "Using vbGeneralDate:"; Tab(25); FormatDateTime(Now, vbGeneralDate) Print "Using vbLongDate:"; Tab(25); FormatDateTime(Now, vbLongDate) Print "Using vbShortDate:"; Tab(25); FormatDateTime(Now, vbShortDate) Print "Using vbLongTime:"; Tab(25); FormatDateTime(Now, vbLongTime) Print "Using vbShortTime:"; Tab(25); FormatDateTime(Now, vbShortTime) End SubOutput: Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 24 -
  25. 25. 3 Cube Computer Institute – VB 6 NotesRef: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 25 -