Sie sind auf Seite 1von 25

3 Cube Computer Institute VB 6 Notes

CHAPTER 1 Introduction to Visual Basic 6.0 Visual basic is a high level programming language (HLL) developed from the BASIC programming language. 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 user elements. The Window GUI defines how the various elements such as FORMS and CONTROLS look and function. Visual Basic is an event-driven programming language. Procedural vs. OOP vs. event-driven programming language In the Procedural languages such as Basic, C, COBOL, etc the program specifies exact sequence of all operations. Program logic determines the next instruction to execute in response to conditions and user 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 a mouse button on any object then the Click event occurs. If a user moves the mouse then the mouse move event occurs Any programming language, which uses these events to run a specific portion of the program, will be called event driver programming. The GUI based programs are all developed using event driver programming. 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 an event 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 windows and dialog boxes you place on the screen; Controls are the elements you place inside a form, such as text coxes, command button, etc. Properties: Properties tell something about the Object, such as its name, color, size, etc or how it will behave. To refer 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.Text Methods: 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-

3 Cube Computer Institute VB 6 Notes

VB6 Environment / IDE (Integrated Development Environment) The VB6 environment is where you create and test your projects. Fig 2 shows various windows in VB6 environment. Each window can be moved, resized, opened, or closed. Various windows in VB6 environment are: Main VB Window The main VB Window holds the VB Menu bar, the toolbar, and the form location and size information FORM WINDOW The form window is where you design the forms that makes up your user interface. When you begin a new project, VB gives your form name the default name Form1. The Project Explorer Window This window holds the filenames for the files included in your project.

Fig 3: Project Explorer Window The Properties Window We use the properties window to set the properties for the objects in the project. The Form Layout Window The position of the form in this window determines the position of the form on the desktop when execution of the project begins. The Toolbox Toolbox window contains a set of controls which are used to customize forms. Using this controls user can create an interface between user and the application Figure 4 Toolbox windows with its controls available commonly.

Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -2-

3 Cube Computer Institute VB 6 Notes

Control Pointer PictureBox TextBox Frame CommandButton CheckBox OptionButton ListBox ComboBox HScrollBar VScrollBar Timer DriveListBox DirListBox FileListBox Shape Line Image Data OLE

Description used to interact with the controls on the form used to display images used to accept user input which can display only editable text used to group other controls used to initiate an action by pressing on the button used to do a choice for user (checked or unchecked) used in groups where one at a time can be true used to provide a list of items used to provide a short list of items a horizontal scrollbar a vertical scrollbar used to perform tasks in specified intervals. used to access to the system drives used to access to the directories on the system used to access to the files in the directory used to draw circles, rectangles, squares, ellipses used to draw lines used to display images. But less capability than the PictureBox used to connect a database used to interact with other windows applications

Label used to display texts which cannot be edited The Toolbar We 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-

3 Cube Computer Institute VB 6 Notes


WORKING MODES IN VISUAL BASIC VB has 3 distinct modes: Design mode While you are designing the user interface and writing code, you are in design mode. Runtime mode When you are testing and running your project, you are in runtime mode. Break Mode If you get a run-time error or pause project execution, you are in break time mode.

VISUAL BASIC CODE STATEMENTS The basic program in VB requires 3 statements: 1.The Remark Statements Remark 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 of remarks 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 Statements The 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 = 12 3. The END statement The END statement stops execution of the project. Example, Include an END statement in the sub procedure for an EXIT button

FIRST VB PROJECT Getting started To open the Visual Basic environment and to work with it select and click on Microsoft Visual Basic 6.0 in the start menu. When Visual Basic is loaded the New Project dialog shown in figure 1.1 will be displayed with the types available in Visual Basic. You can notice that Standard Exe is highlighted by default. Standard Exe allows the user to create standard executable. Standard executable is a type which has most of the common features of Visual basic

Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -4-

3 Cube Computer Institute VB 6 Notes

Design the FORM

Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -5-

3 Cube Computer Institute VB 6 Notes


Setting the Property Object Form1 Command1 Command2 Text1 Code

Property Name Caption Name Caption Name Caption Name Text

Value Form1 Form1 cmdOK OK cmdExit Exit txtName

Private Sub cmdExit_Click() txtName.Text = "Welcome to VB 6" End Sub Private Sub cmdOK_Click() End End Sub Run The Project Press F5 or Start button on the toolbar to run the project. Save the project While 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 .ocx Naming 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 -frm Label -lbl TextBox -txt CommandButton -cmd CheckBox -chk OptionButton -opt ComboBox -cbo ListBox -lst Frame -fme PictureBox -pic Image -img Shape -shp Line -lin

Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -6-

3 Cube Computer Institute VB 6 Notes


HScrollBar VScrollBar -hsb -vsb

TYPES OF ERRORS 1. COMPILE ERRORS The VB attempts to convert your program code to machine language (called compiling the code) ,it finds any compile errors .You get the compile errors when you break the syntax rules of Visual 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 ERRORS If your projects halts during execution, thats run time errors. VB displays a dialog box and goes into break mode and highlights the statement causing the error. Statements that cannot be executed correctly causes runtime errors. Such statements are compiled correctly but fail too execute. Examples: calculation with non-numeric value, divide by zero, square of negative number. 3. LOGICAL ERRORS With logic errors, a project run but produces incorrect results. Example, result of a calculation is incorrect or the wrong text appears or the text is OK but appears in the wrong location. CONTEXT SENSITIVE HELP VB 6 provides a great HELP section, if MSDN Library is installed in your machine. For Context Sensitive Help, select a VB object, such as Text Boxes, or place the insertion point in a word in the editor and Press F1. The MSDN Library viewer will open on the correct page, if possible, saving you a search.

Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -7-

3 Cube Computer Institute VB 6 Notes


CHAPTER 2 More Controls In 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 own Caption property. Example: lblName.Caption=ABC The actual text displayed in a label is controlled by the Caption property, which can be set at design time in the Properties window or at run time by assigning it in code. To clear a Labels caption: lblMessage.Caption= TEXT CONTROL: Text boxes are versatile controls that can be used to get input from the user or to display text. Text boxes should not be used to display text that you don't want the user to change, unless you've set the Locked 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 Wrap By default, a text box displays a single line of text and does not display scroll bars. If the text is longer than the available space, only part of the text will be visible. The look and behavior of a text box can be changed by setting two properties, MultiLine and ScrollBars, which are available only at design time. Note The ScrollBars property should not be confused with scroll bar controls, which are not attached 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 Box You 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 Center To clear a text box at runtime: txtMessage.Text= FRAMES Frame controls are used to provide an identifiable grouping for other controls. For example, you can use 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 no need to respond to its events. You will, however, most likely change its Name, Caption, or Font properties. Adding a Frame Control to a Form When using the frame control to group other controls, first draw the frame control, and then draw the 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-

3 Cube Computer Institute VB 6 Notes


Drawing Controls inside the Frame To add other controls to the frame, draw them inside the frame. If you draw a control outside the frame, or use the double-click method to add a control to a form, and then try to move it inside the frame control, the control will be on top of the frame and you'll have to move the frame and controls separately. 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 BOX Checkboxes 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=unchecked OPTION 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 one option 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 choose one and only one. Creating Option Button Groups All of the option buttons placed directly on a form (that is, not in a frame or picture box) constitute one group. If you want to create additional option button groups, you must place some of them inside frames or picture boxes. All the option buttons inside any given frame constitute a separate group. Selecting or Disabling Option Buttons An 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 within the group. Assigning its Value property to True in code: optChoice.Value = True or optChoice.Value = False To make a button the default in an option button group, set its Value property to True at design time. 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 the Picture 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 AutoSize property to True causes a picture box to resize to the dimensions of the picture; setting it to False causes 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=False SHAPE CONTROL The shape control is used to create the following predefined shapes on forms, frames, or picture boxes: rectangle, square, oval, circle, rounded rectangle, or rounded square.

Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh -9-

3 Cube Computer Institute VB 6 Notes


Predefined Shapes The Shape property of the shape control provides you with six predefined shapes. The following table lists all the predefined shapes, their values and equivalent Visual Basic constants: Shape Rectangle Square Oval Circle Rounded Rectangle Rounded Square Style 0 1 2 3 4 5 Constant vbShapeRectangle vbShapeSquare vbShapeOval vbShapeCircle vbShapeRoundedRectangle vbShapeRoundedSquare

LINE CONTROL The 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 of applications. CHANGING FONT PROPERTIES OF CONTROLS At 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=12 CHANGING COLOR PROPERTIES OF CONTROLS At 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, vbWhite Example: txtName.ForeColor=vbRed lblMessage.ForeColor=vbGreen

Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 10 -

3 Cube Computer Institute VB 6 Notes


CHECK 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 -

3 Cube Computer Institute VB 6 Notes


SHAPE 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 Sub DEFINING KEYBOARD ACCESS KEYS Many 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 -

3 Cube Computer Institute VB 6 Notes


We can set access keys for command button, option buttons and check boxes. When you define their Caption property. Type an ampersand (&) in front of the character you want for the access key; VB underlines the character. For example: &OK for OK E&xit for Exit Specifying the Default and Cancel Properties On 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 other control on the form has the focus. To specify a command button as default set the Default property to True. 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 the form has the focus. Setting the Tab Order The tab order is the order in which a user moves from one control to another by pressing the TAB key. Each form has its own tab order. Usually, the tab order is the same as the order in which you created 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 between controls in the order they were created To change the tab order for a control, set the TabIndex property. The TabIndex property of a control determines where it is positioned in the tab order. By default, the first control drawn has a TabIndex value of 0, the second has a TabIndex of 1, and so on. When you change a control's tab order position, Visual Basic automatically renumbers the tab order positions of the other controls to reflect insertions and deletions. For example, if you make Command1 first in the tab order, the TabIndex values for the other controls are automatically adjusted upward, as shown in the following table. TabIndex before it is changed Control Text1 Text2 Command1 0 1 2 1 2 0 TabIndex after it is changed

The 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 the number 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, don't have a TabIndex property and are not included in the tab order. As a user presses the TAB key, these controls are skipped. Removing a Control from the Tab Order Usually, pressing TAB at run time selects each control in the tab order. You can remove a control from 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 tab order, even though the control is skipped when you cycle through the controls with the TAB key. CREATING TOOLTIPS The word or short phrase that describes the function of a toolbar button or other tool. The ToolTip appears when you pause the mouse pointer over an object.

Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 13 -

3 Cube Computer Institute VB 6 Notes

ToolTipText Property Returns or sets a ToolTip. At design time you can set the ToolTipText property string in the control's properties dialog box. At Run-time: object.ToolTipText [= string] The ToolTipText property syntax has these parts: Part object string Description An object expression that evaluates to an object in the Applies To list. A string associated with an object in the Applies To list. that appears in a small rectangle below the object when the user's cursor hovers over the object at run time for about one second.

With Statement Executes a series of statements on a single object or a user-defined type. Syntax With object [statements] End With The With statement syntax has these parts: Part object statements Description Required. Name of an object or a user-defined type. Optional. One or more statements to be executed on object.

Remarks The With statement allows you to perform a series of statements on a specified object without requalifying the name of the object. For example, to change a number of different properties on a single object, place the property assignment statements within the With control structure, referring to the object once instead of referring to it with each property assignment. The following example illustrates 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 With Note Once a With block is entered, object can't be changed. As a result, you can't use a single With statement 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 -

3 Cube Computer Institute VB 6 Notes


result = expression1 & expression2 The & operator syntax has these parts: Part result expression1 expression2 Description Required; any String or Variant variable. Required; any expression. Required; any expression.

Example: txtOutPut.Text= Welcome & To VB 6 txtName.Text= txtFirstName.Text & & txtLastName.Text Remarks If an expression is not a string, it is converted to a String variant. The data type of result is String if both expressions are string expressions; otherwise, result is a String variant. If both expressions are Null, result is Null. However, if only one expression is Null, that expression is treated as a zero-length string ("") when concatenated with the other expression. Any expression that is Empty is also treated as a zero-length string.

Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 15 -

3 Cube Computer Institute VB 6 Notes


CHAPTER 3 Variables, Constants and Calculations Variables and Constants Memory 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 called Variables. For example, Variable: a customers 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 a name, called an Identifier. Data types in visual basic 6.0 The data type of a variable or constant indicates what type of information will be stored in the allocated 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 Disadvantages 1.Its easy 1. Less efficient than other data types, i.e., they 2. variables and constants change their require more memory space and operate less appearance as needed for each situation. quickly than other data types. The best practice is always specify the data types. Other data types are: 1. Numeric Byte Integer Long Single Double Currency Store integer values in the range of 0 - 255 Store integer values in the range of (-32,768) - (+ 32,767) Store integer values in the range of (- 2,147,483,468) - (+ 2,147,483,468) Store floating point value in the range of (-3.4x10-38) - (+ 3.4x1038) Store large floating value which exceeding the single data type value store monetary values. It supports 4 digits to the right of decimal point and 15 digits to the left

2. String Use to store alphanumeric values. A variable length string can store approximately 4 billion characters 3. Date Use to store date and time values. A variable declared as date type can store both date and time values and it can store date values 01/01/0100 up to 12/31/9999 4. Boolean Boolean data types hold either a true or false value. These are not stored as numeric values and cannot be used as such. Values are internally stored as -1 (True) and 0 (False) and any non-zero value is considered as true. Naming rules and convention in VB 6.0 These 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 -

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 Variant Variables: Variables are the memory locations which are used to store values temporarily. A defined naming strategy has to be followed while naming a variable. A variable name must begin with an alphabet letter and should not exceed 255 characters. It must be unique within the same scope. It should not contain any special character like %, &, !, #, @ or $. Declaring variables To declare a variable, we use DIM statement. DIM statement General Form: Dim identifier [as DataType] If you omit the optional data type, the variables type defaults to variant. Example: Dim vntChanging Dim strName as String Dim intTotal as Integer The reserved word Dim is really short for Dimension, which means size. When you declare a variable, the amount of memory reserved depends on its data types. Data Type Boolean Byte Currency Date Double Integer Long Single String (Variable Length) Variant Numer of Bytes of Memory Allocated 2 1 8 8 8 2 4 4 10 bytes plus 1 byte for each character in the string 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 -

3 Cube Computer Institute VB 6 Notes


SCOPE OF VARIABLES The visibility of a variable is referred to as its Scope. Visibility means this variable can be seen or used 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 level variable, place a prefix of g before the identifier. Example: gintTotalSum Module level variable Module level variables are accessible from all the procedure of a form. To indicate a module level 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 variable that 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 sub Constant Named and Intrinsic Constant provide a way to use words to describe a value that doesnt 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, a data type and a value. Once a value is decaled as a constant, its value cannot be changed during program 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 ] = Value Example: Const strAddress As String = Malad Const curSalesTaxRate as Currency = 0.08 Assigning Values to Constant String Literals String constants are called String literals and may contain letters, digits and special characters, such as $#@%&*. Also, to declare a constant such as

Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 18 -

3 Cube Computer Institute VB 6 Notes


He said, I liked it , it are declared as Const strName as String=He said, I liked it Numeric Constants Numeric constants may contain only the digits (0-9), a decimal Point and a sign(+ or -) at the left side. We cannot include a comma, dollar sign, any other special character, or a sign at the right side. Data Type Constant value Example Integer 125 2170 Single or Currency 101.25 -5.2 String literals VB 103 She said Hello. 2. Intrinsic Constant Intrinsic constant are system-defined constants. Several sets of Intrinsic constants are stored in library 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 Basic Arithmetical Operators Operators + / \ * ^ Mod & Description Add Substract Divide Integer Division Multiply Exponent (power of) Remainder of division String concatenation Example 5+5 10-5 25/5 20\3 5*4 3^3 20 Mod 6 "George"&" "&"Bush" Result 10 5 5 6 20 27 2 "George Bush"

Relational Operators Operators > < >= Description Greater than Less than Example 10>8 10>8 Result True False True

Greater than or equal to 20>=10

Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 19 -

3 Cube Computer Institute VB 6 Notes


<= <> = Less than or equal to Not Equal to Equal to 10<=20 5<>4 5=7 True True False

Logical Operators Operators OR AND Description Operation will be true if either of the operands is true Operation will be true only if both the operands are true

Val Function A 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 the assignment statements. Example: intQuantity=Val(txtQuantity.Text) curPrice=Val(txtPrice.Text) Important: When the Val function converts an argument to numeric, it begins at the arguments left most character. If that character is a numeric digit, decimal point, or sign, It converts the character to numeric and moves to the next character. As soon as a nonnumeric character is found, the operation stops. Example: Argument (blank) 123.45 $100 1,000 A123 123A 4C5 -123 +123 12.45.2 Numeric Value Returned by the Val Function 0 123.45 0 1 0 123 4 -123 123 12.45

Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 20 -

3 Cube Computer Institute VB 6 Notes


CALCULATOR PROGRAM

Code: 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 Sub

FORMATTING DATA Use 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 -

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.678 Expression FormatNumber(dblTestNumber, 2, True, True, True) FormatCurrency(dblTestNumber, 2, True, True, True) FormatPrecent(dblTestNumber, 2, True, True, True) "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 Sub Output: Result 12,345.68 $12,345.68 1,234,567.80%

Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 22 -

3 Cube Computer Institute VB 6 Notes

4. FormatDateTime FormatDateTime Returns an expression formatted as a date or time. Syntax: FormatDateTime(Date[,NamedFormat]) The FormatDateTime function syntax has these parts: Part Date NamedFormat Description Required. Date expression to be formatted. 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 Description vbGeneralDate 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 -

3 Cube Computer Institute VB 6 Notes


vbLongDate vbShortDate vbLongTime vbShortTime "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 Sub Output: 1 2 3 4 Display a date using the long date format specified in your computer's regional settings. Display a date using the short date format specified in your computer's regional settings. Display a time using the time format specified in your computer's regional settings. Display a time using the 24-hour format (hh:mm).

Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 24 -

3 Cube Computer Institute VB 6 Notes

Ref: MSDN and Programming in VB 6 by Julia C. Bradley & Anita C. Millspaugh - 25 -

Das könnte Ihnen auch gefallen