![]() |
|
||||||
Getting StartedVisual Basic is an object-oriented programming language that uses the Microsoft Windows platform. The programs that are created using Visual Basic will look and act like standard Windows programs. Visual Basic provides one the tools to create windows with elements such as menus, text boxes, command buttons, option buttons, list boxes and scroll bars. This tutorial does not completely cover all aspects of Visual Basic. This is just basically an overview to get a beginner to the language up to pace. Databases, Crystal Reports and others are not included to keep this tutorial under 500 pages and to keep carpal tunnel from occurring. Although this tutorial is aimed at beginners, it was also written assuming that the reader possibly has some programming knowledge. For instance: what an IF / THEN / ELSE statement is, For / Next loop and so on. If you have taken Basic or QBasic, that’s ideal before reading through this article. Additionally, this tutorial would not be of much help if you do not have VB 6.0 installed on your computer. I believe a trial version can be downloaded somewhere. I would try searching google to find it. If you do have it, open it and read this and follow through. Procedural vs. Non-Procedural LanguagesProcedural Languages - Programming languages that have a set plan that you follow to execute a program. In other words, you have an algorithm or step-by-step process to execute. The statements are executed in order from beginning to end and the program will terminate after the last statement is executed. Examples of Procedural Languages:
and others as well... Non-Procedural Languages - These are Object-Oriented programming languages that are event-driven. With Non-Procedural Languages, one does not have only a series of statements that are executed, but several choices of different things you can do in a program. You select the event that you want to occur and only the code for that event will be executed. Examples of Procedural Languages:
Labels, Text Boxes and Command ButtonsLabel - A control that is used to display text as a caption. Labels cannot be altered by the user. They are simply used to display headings results of processing, as well as other information on a form. Labels begin with a lbl prefix. Examples of labels:
Text Box - Control that is used to enter information onto a form. Text boxes can have focus, and are the primary means of providing input to a project in Visual Basic. Text boxes begin with the prefix of txt Examples of Text Boxes:
Command Buttons - Control that is used to activate a procedure. When a command button is clicked or activated using an access key, an event will take place (the code behind the command button is executed.) Command buttons begin with the prefix cmd Types of Errors
Special Functions and MethodsVAL - A function that will convert a string to a numeric value. It will begin with the far left character of the string. If that character is a numeric digit, decimal point or sign, VAL will convert the character to a numeric value, and continue to the next character. Once a non-numeric character is found, the VAL function will stop. PrintForm - A method that will print the current form on the printer. This is executed during run-time. FORMAT - This is used to format a variable. Variables can be formatted as fixed numbers, currency and percents. Syntax : Examples: FormatCurrency - This function will take a number and format it as currency with two decimal places and a $ sign. There is only one argument, the number you want to format. FormatNumber - This function will format a number as a decimal with a set number of decimal places. The first argument is the number you want to format. The second is the number of decimal places you want the number to have. FormatPercent - This function will take the number, and format it as a percent bymultiplying the number by 100 and adding a percent sign to the end. By default, the number will be rounded to zero decimal places unless you specify a second argument. FormatDate and Time - This function will take a string and format it as a Date, Time or both. The first argument is the date or time to be formatted. The second argument is the format of date/time you decide to use. Variables and ConstantsOption Explicit - A statement that will force you to declare all variables used in your program. If you fail to declare a variable, an error will occur when you run your program. DECLARING A VARIABLE:When you declare a variable, VB reserves space in the computers memory and assigns a name to it. When declaring variables, certain rules must be followed. Rules for Variable Names:
NOTE: The rules specified above also apply to control names placed on a form. The DIM statement is used to declare all variables in VB. Syntax: DIM < variable_name > as < datatype > Examples: DECLARING A CONSTANT:Constants are always declared using the keyword CONST. You give the constant a name, data type and value. Once a value is declared as a constant, it can never be changed again in the program. Trying to change a constant will cause an error. The rules for variables also apply to constants. Syntax: DIM < constant name > as < datatype > = <value > Examples: NAMED CONSTANTS - These are constants that you name yourself with the CONST keyword. Named constants can come in the form as numeric constants and string constants. NUMERIC CONSTANTS - Constants that can contain only the digits 0-9, a decimal point. STRING CONSTANTS - Constants that can contain letters, digits, and special characters such as @#$%^&*. String constants must be enclosed in double quotes. INSTRINCT CONSTANTS - System-Defined constants that are built into VB. Examples of Instrinct Constants:
SCOPES OF VARIABLES:Scope - Is a term used to refer to the visibility of a variable. Lifetime - The period of time that variables exist within the program. 3 LEVELS OF SCOPE:
PROPERTIESDefault Property - Automatically selects a command button when the user presses the < ENTER > key. To make a command button a default button, you set its DEFAULT property to TRUE. Only one command button per form can have its default property set to true. When the program is run, this command button will be highlighted. Cancel Property - The button that is selected when the user presses the < ESC > key. To set a command button to cancel the program, set its CANCEL property to TRUE. Only one command button per form can have its cancel button set to true. TabStop Property - Represents all controls on a form that can receive focus. If the TabStop property is TRUE, a control can receive focus. If it is FALSE, then it cannot. Some controls can receive focus, others cannot. Text Boxes, and Command Buttons can receive focus. Labels and Images cannot receive focus. TabIndex Property - Determines order of focus moves as the < TAB > key is pressed.Name - Used to assign the name of the control as it is known by the project. Caption - The label that appears next to, in or on top of the control. BackColor - The background color of the control. ForeColor - The color of the text that appears on or next to the control. Text - The text which appears in a text box. Alignment - Determines the justification of text within a label or text box.
MultiLine - Allows a string to be spread out among several lines, rather than one line. Font - Allows you to set the font and font size of a control. TabIndex - Determines the order the focus moves as the < TAB > key is pressed. Visible- Property used to make a control visible or invisible FillStyle - Primarily used with shapes, is used to fill the shape. Different options are available.
EXAMPLES : Option Buttons... FormatsOption Buttons - Group of controls where only one can be selected at a time. Check Boxes - Group of controls where more than one can be selected at a time. Frame - Control that often acts as a container for a group of option buttons or check boxes. Image - Type of control that is used to hold a graphic. Shape - Type of control used to place rectangles, squares, ovals and circles on a form. OPTION BUTTONS:The VALUE property of the option button is set TRUE if you want it to be selected, otherwise, FALSE. Set the option buttons CAPTION property to the text you want to appear next to the option button. When assigning an option button, a variable name always starts out with the prefix, opt. If you want an event to occur when you click on an option button, you can double-click on the option button from your form to enter in the code you want executed. CHECK BOXES:More than one check box can be selected at a time. The VALUE property of the option button is set to CHECKED if you want it to be selected, otherwise, set it to UNCHECKED. A second option is to set the VALUE property on check boxes to a 0, 1 or 2.
Set the CAPTION property to the text you would like to appear next to the check box When assigning a variable name, always start out with prefix chk If you want an event to occur when you click on a check box, double-click the button to place code behind. IMAGES:Click on the images PICTURE property and locate the folder or drive where the picture is located.
All controls that are images should begin with an img prefix. SHAPES:The types of shapes and codes are shown below...
All controls that are shapes should begin with the shp prefix. LINESUse the crosshair pointer to drag a line across the screen. You may rotate the line in any direction and stretch it until releasing the move button.
Determining Focus Focus - Refers to the currently selected control on the form. This can be indicated by an | - Beam, selected text, highlighted caption or dotted border. The control with focus is ready to receive input. SetFocus - A built-in function that when executed will move the cursor to the control and give that control focus. SetFocus can be used with text boxes, command buttons, option buttons and check boxes. Examples of setFocus: Working With StringsConcatenation - Refers to combining two or more smaller strings into a larger string. In VB, you can either use the & or + symbols to concatenate. Examples of Concatenation: FormatsCENTERING A FORM IN THE MIDDLE OF THE SCREEN: (This code would go in the FORM LOAD (double click any empty space on the form.)) < Name of form > .Top = (Screen.Height - < Name of form > .Height)/2 < Name of Form > .Left = (Screen.Width - < Name of form > .Width)/2 < Name of Form > - This is the actual name of the form as you have saved it in your program. If you named your form, "myForm" then you would code the statement in the following way: Input Boxes, Message and List BoxesInput Box - This is a function that will display a message, and allow the user to enter information in a text box. In the Input box, you can display a message called a prompt. The promp will help the user decide what information he or she needs to enter in the text box. The input box will have a text box with the prompt above it and two command buttons (OK and CANCEL). OK will accept any input the user enters, and place it in the variable on the left hand side of the equals sign. CANCLEL will ignore any input entered by the user, and return back to the form currently open. Input Boxes are often used when one wants to retrieve records from files. VariableName = InputBox("Prompt","Title") Examples: The prompt must be enclosed in quotes. The title must also be in quotes and will appear in the Title Bar of the Input Box. If no title is entered, the title of the project will appear in the Title Bar. Input Boxes can appear in the following places:
Form LoadForm_Load - Code executed as the project is loading. The first time a form is displayed in a project, VB generates an event knows as FORM_LOAD. Any code in Form Load is then executed. Things that are done in the FORM_LOAD section of a VB program include the following:
To get the FORM_LOAD event to enter code, double click on an empty area on the form. The FORM_LOAD event begins and ends with the following procedure headings: Private Sub Form_Load() < Place Code Here > End Sub Example of code in the FORM_LOAD event: Message Boxes and List BoxesMessage Box - A special type of VB statement/function that displays a window in which you can display a message to a user. The message box can be a statement or function and has the name, MsgBox. The following can be displayed to the user with a Message Box:
MESSAGE BOX STATEMENTThe message box statement is designed to be on a line by itself. The syntax of the MsgBox is identified below: MsgBox < "Prompt" > , < Buttons/Icons > , < "Caption" > Prompt - The message you want to appear in the message box. MESSAGE BOX FUNCTION:The message box function will appear on the right hand side of the equals sign. Also, if your message box is a function, you must enclose arguments in ( and ). VarName = MsgBox( < "Prompt" > , < Buttons/Icons > , < "Caption" > ) Sample code using Message Boxes: LIST BOXES:List Box - A type of control used to hold a list of items from which the user can select one item from the list. You should use the lst prefix when naming list boxes. Items can be added to a list box in two ways. Using the LIST property for the list control Using the AddItem method < object_name > .AddItem < Value > If your values are strings, they must be enclosed in double quotes. When items are added to the list, they are given an index. The first item added to the list will have an index of zero the 2nd of one, and so forth. Example of - ADDING ITEMS TO THE LIST: This will highlight the item "Brown". Harvard will have an index of 0, Yale of 1 and so forth. ListIndex PROPERTY :The listIndex property will highlight an item in the list when the program is run. Only one item can be set with the listIndex property. The format of List Index property is shown here: < control > .ListIndex = 3 'This will highlight the 4th item in the list. Sorted PROPERTY:This will sort the items in your list alphabetically if the SORTED property is set to TRUE. This will also re-index the items in your list. If the ListIndex property is used, the highlighted item will change. Clear METHOD:This will empty out the contents of a list box... < control > .Clear RemoveItem METHOD:This will remove one item from the list. When using RemoveItem, you must include the index of the item to remove. < control > .RemoveItem < index > This will remove the item in the lstSchools list box with the index of 3, which is the 4th item in the list. LstCount - The ListCount property is used to hold the number of items in the list. ListCount will always be one more than the highest element in the list. Sub Procedures, Random NumbersProcedure - A unit of code that performs a specific task and can be called from other locations of the program. PURPOSES OF PROCEDURES:
TYPES OF PROCEDURES:Sub Procedure - A procedure that performs a task but DOES NOT return values back to the calling module. Function Procedure - A procedure that performs a task and RETURNS a value back to the calling module. With function procedures, the value is returned back to the calling module using the function name. CREATING A NEW SUB PROCEDURE:
Example of a Sub Procedure: Example of a Sub Procedure Call: Example of a Function Procedure: Example of a Function Procedure Call: WITH STATEMENTThe WITH keyword allows you to cut down on coding when dealing with properties of controls. Syntax of WITH statement: With < control > .< property1> = < value1 > .< property2> = < value2 > .< property3> = < value3 > End With Assigning controls without the WITH KEYWORD: Assigning controls using the WITH KEYWORD: COMMON DIALOG CONTROLAllows your project to use the dialog boxes that are provided as part of the Windows environment to set properties for a control such as font, font size and color. FEATURES OF THE DIALOG CONTROL:
RETRIEVING THE COMMON DIALOG CONTROL:
CHANGING FONTS:Example Syntax for Setting Fonts: With dlgCommon (assuming that you named it that) .Flags = cdlCFScreenFonts ‘Loads different fonts into memory .ShowFont End With CHANGING COLOR:Example Syntax for Changing Color: RANDOM NUMBERSRnd - Generates a random number between 0 and 1. Randomize - Tells VB to randomly generate numbers for the rnd statement. Using randomize will allow the rnd statement to generate an entirely random set of numbers that do not follow any recognizable pattern. Generating Numbers between 1 and 10: Generating Numbers between 1 and 100: INT() FUNCTION:Converts a floating point value to an integer by truncating off any remainder that the number has. INT(4.656) will return a value of 4. Menus, Combo Boxes and QB ColorMenu - A drop-down list of items displayed below a menu name on the screen from which you selected one item. In both Windows and VB, a menu consists of a menu bar with menu names, each of which drops down to display a list of menu commands. You can use menu commands in place of or in addition to the command buttons to activate a procedure. Menu commands are actually controls and have events and properties. Each menu command has a Name property and a Click event, similar to a command button. To create a menu for your form, you will use the Visual Basic Menu Editor, which accessible by pressing < CTRL > + E or Click on Menu Editor Icon. PARTS OF THE MENU:Caption - Holds the words you want to appear on the screen. Name - Indicates the name of the menu control and what the control is referred to by the program. When naming, start out with the prefix, "mnu" . For example, if you had a menu control for "file", you would name it, "mnuFile" SUBMENU - A list of commands that appear underneath a menu command, (a menu within a menu). To create a submenu, press the right arrow key to move to the next level. Menu List Box - Shows the list of all menu items that have been created and the indication levels. You can move up, down, left and right by clicking on the name of the menu item and then clicking on one of the four arrow buttons. Separator Bars - A horizontal line that separates one menu from another. To define a separator bar, type a single hyphen ( - ) for the caption and give it a name. Even though you can never reference the separator bar in the code, you still have to give it a name. If you have more than one separator bar, each one has to have a unique name. (mnuSep1, mnuSep2, ...ect.) Shortcut Keys - You can create a keyboard shortcut key for a menu item when its created. Select a shortcut key for your menu item by selecting it from the list provided. The purpose of the shortcut is to provide an alternative to sorting through menus to perform a single task. Checked - If you want a check mark to appear next to an item in your menu, you would put a check here. Check marks are normally for options that you want to be toggled on and off. Enabled - If you want the user to be able to select a menu item, this will be checked. By default, all are enabled. If unchecked, this menu item will be dimmed out. You can also change this property in the actual code (mnuStar.Enabled = False). Visible - Determines whether a menu item is displayed on the screen or not. If there is a check in this check box, the menu item will be displayed on the screen. If the box is not checked, the menu item will not be displayed. This property can also be changed in the actual code (mnuStar.Visible = True). Insert - Click on this if you want to insert an item into the middle of a menu. The item will be inserted at the location of the current item. All items below that point will be moved down. Delete - Will delete the highlighted menu. Cancel will close the menu editor without saving changes, and OK will save changes to the menu and close the menu editor. COMBO BOXESCombo Box - A type of control used to hold a list of items from which the user selects one from a pull down menu. Differences between a List Box and a Combo Box:
Like list boxes, items can be added to a combo box in two ways...
ADDING ITEMS TO THE LIST USING THE LIST PROPERTY:
ADDING ITEMS TO THE LIST USING THE ADDITEM PROPERTY:
< object_name > .AddItem " < Value > " ADDING ITEMS INTO THE ItemData ARRAY:< object_name > .AddItem " < Value > " < object_name > .ItemData(< object_name > .NewIndex) = < Value > ADDING ITEMS TO THE LIST:The code below will add items into the list of a Combo Box: Harvard will have the index of 0, Yale of 1 and so on Entering Items into the ItemData array of a Combo Box... TEXT PROPERTY:The Text property refers to the actual item that is currently selected in the list. < label > = < control > .Text ListIndex works as the same as List Boxes. Same as NewIndex, ItemData, Sorted, Clear, RemoveItem, ListCout...ect. When naming Combo Boxes, use the prefix, "cbo". For example, if you wanted a combo box named School, you would name it, cboSchool. QB COLORQBCOLOR - is a built-in function in VB that will display 15 different colors. The QBCOLOR function has one argument, which is the index of the color to be displayed. The index can range from values 0 to 15. What the heck, here are the values for you:
Example: Control Arrays, Scroll Bars and RGB FunctionArray - A group of data items that are referred to by the same name. Control Array - A group of controls sharing the same name and event procedures. Index - A variable used to refer to each element in the control array. Control Arrays can be used with the following controls:
Control Arrays are most commonly used with text boxes and option buttons. CREATING A CONTROL ARRAY:
Example Control Array using a Select Case: This example is if you had six option buttons with names of colors and a Rounded Square shape that will fill the color of the selected option button. SUM AND AVERAGE OF TEST SCORES USING CONTROL ARRAYS:Here is another example of a control array. This will be if you wanted to figure the sum and average of test scores. Scroll Bars and RGB FunctionScroll Bar - A control that allows you to see hidden information on the screen. This information can be text, icons or controls. In VB a scroll bar is used to represent a range of values. Scroll bars are also used to control sound level, color, size and other values that can be changed in small amounts or large increments. Scroll Box - The little square, which appears inside the scroll bar. Pressing down on the scroll box changes the value property of the scroll bar. Another name for the scroll box is the thumb. PROPERTIES OF THE SCROLL BAR:
TYPES OF SCROLL BARS:
EVENTS OF THE SCROLL BAR:Change Event - Occurs when the user clicks on the gray area of the scroll bar. Scroll Event - Occurs when the user drags the scroll box. As soon as the user releases the mouse botton, the scroll event ceases and a change event occurs. When you write code for the scroll bar, you will want to write code for both Change even and the Scroll event. SAMPLE PROGRAM USING HORIZONTAL SCROLL BAR:SAMPLE PROGRAM USING VERTICAL SCROLL BAR:RGB FUNCTIONThe RGB function specifies the quantities of red, green and blue for a large variety of colors. The value for each color ranges from 0 to 255 with 0 being the least intense and 255 being the most intense. The color arguments are in the same order as their letters in the function name, red first, then green and then finally blue. You can use the RGB function to assign the color to a property or specify the color in a graphics method. Chosen_Color = RGB(RedValue, GreenValue,BlueValue) Examples: Multiple Forms, ME Keyword and ConclusionA VB project can consist of several forms. Each form has its own window, form load section, general declarations section and code window. All of the forms in a project are tied together under the project name. When you run the program, you can switch back and forth between different forms. StartUp Form - The first form a project displays when the project is loaded. Load - Loads a form into the computers memory (does not display on screen.) · Load < form_name > Unload - Unloads the form from the computers memory. Also, if you’re running an execss amount of forms, you should unload them to save on memory. · Unload < form_name > Show - Display the loaded form on the screen. · < form_name > .Show Hide - Makes the form disappear. The form will still be loaded into memory. It just will not be displayed on the screen. · < form_name > .Hide ME KEYWORD:You can refer to the current form by using the special keyword ME. Me acts like a variable and refers to the form that is currently active. You can use Me in place of the form name when coding statements and methods. Examples: Conclusion:I feel I have provided a nice strong start to learning Visual Basic 6.0. This tutorial does not cover many things and was never intended to be a highly technical detailed analysis and disection of VB. However, you can learn a lot by simply playing around with the program and becoming more familiar and comfortable with its functions. I am sure that I left a lot of things out that should have made it in, and also discussed things I could have left out- but a line has to be drawn somewhere. So by all means, check out other VB tutorials on the site and other code samples available as well. I hope you enjoyed the article and are ready to get started with Visual Basic!!! -bs0d | www.allsyntax.com
No Comments for this page. |
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||