VISUAL BASIC - Vijaya College, Bangalore

Transcription

VISUAL BASICLesson1: Introduction to Visual Basic 6Before we begin Visual Basic 6 programming, let us understand somebasic concepts of programming. According to Webopedia, a computerprogram is an organized list of instructions that, when executed,causes the computer to behave in a predetermined manner. Withoutprograms, computers are useless. Therefore, programming meansdesigning or creating a set of instructions to ask the computer to carryout certain jobs which normally are very much faster than humanbeings can do.Most people think that computer CPU is a very intelligent thing, whichin actual fact it is a dumb and inanimate object that can do nothingwithout human assistant. The microchips of a CPU can onlyunderstand two distinct electrical states, namely, the on and off states,or 0 and 1 codes in the binary system. So, the CPU only understandscombinations of 0 and 1 code, a language which we called machinelanguage. Machine language is extremely difficult to learn and it is notfor us laymen to master it easily. Fortunately, we have many smartprogrammers who wrote interpreters and compilers that can translatehuman language-like programs such as BASIC into machine languageso that the computer can carry out the instructions entered by theusers. Machine language is known as the primitive language whileInterpreters and compilers like Visual Basic are called high-levellanguage. Some of the high level programming languages besideVisual Basic are Fortran, Cobol, Java, C, C , Turbo Pascal, and more. Among the aforementioned programming languages, Visual Basic isthe most popular. Not only it is easily to learn because of its Englishlike syntaxes, it can also be incorporated into all the Microsoft officeapplications such as Microsoft words, Microsoft Excel, MicrosoftPowerPoint and more. Visual Basic for applications is known as VBA.What programs can you create with Visual Basic 6?With VB 6, you can create any program depending on your objective.For example, you can create educational programs to teach science ,mathematics, language, history , geography and so on. You can alsocreate financial and accounting programs to make you a more efficientaccountant or financial controller. For those of you who like games,you can create those programs as well. Indeed, there is no limit towhat program you can create!VIJAYA COLLEGEPage 1

VISUAL BASICThe Visual Basic 6 Integrated Development EnvironmentOn start up, Visual Basic 6.0 will display the following dialog box asshown in Figure 1.1. You can choose to start a new project, open anexisting project or select a list of recently opened programs. A projectis a collection of files that make up your application. There are varioustypes of applications that we could create, however, we shallconcentrate on creating Standard EXE programs (EXE meansexecutable program). Now, click on the Standard EXE icon to go intothe actual Visual Basic 6 programming environment.VIJAYA COLLEGEPage 2

VISUAL BASICBuilding Visual Basic ApplicationsFirst of all, you have to launch Microsoft Visual Basic 6. Normally, adefault form with the name Form1 will be available for you to startyour new project. Now, double click on Form1, the source code windowfor Form1 as shown in figure 2.1 will appear. The top of the sourcecode window consists of a list of objects and their associated events orprocedures. In figure 2.1, the object displayed is Form and theassociated procedure is Load.When you click on the object box, the drop-down list will display a listof objects you have inserted into your form as shown in figure 2.2.Here, you can see a form with the name Form1, a command buttonwith the name Command1, a Label with the name Label1 and a PictureBox with the name Picture1. Similarly, when you click on theprocedure box, a list of procedures associated with the object will beVIJAYA COLLEGEPage 3

VISUAL BASICdisplayed as shown in figure 2.3. Some of the procedures associatedwith the object Form1 are Activate, Click, DblClick (which meansDouble-Click) , DragDrop, keyPress and more. Each object has itsown set of procedures. You can always select an object and writecodes for any of its procedure in order to perform certain tasks.Figure 2.2: List of ObjectsFigure 2.3: List of ProceduresYou do not have to worry about the beginning and the end statements(i.e. Private Sub Form Load.End Sub.); Just key in the lines inbetween the above two statements exactly as are shown here. Whenyou press F5 to run the program, you will be surprise that nothingshown up .In order to display the output of the program, you have toadd the Form1.show statement like in Example 2.1.1 or you can justuse Form Activate ( ) event procedure as shown in example 2.1.2.The command Print does not mean printing using a printer but itmeans displaying the output on the computer screen. Now, press F5 orclick on the run button to run the program and you will get the outputas shown in figure 2.4.VIJAYA COLLEGEPage 4

VISUAL ninexample 2.1.2. VB uses * to denote the multiplication operator and /to denote the division operator. The output is shown in figure 2.3,where the results are arranged vertically.VIJAYA COLLEGEPage 5

VISUAL BASICFigure 2.4 : The output of example2.1.1Example 2.1.1Private Sub Form Load ( )Form1.showPrint “Welcome to VisualBasic tutorial”End SubExample 2.1.2Private Sub Form Activate ( )Figure 2.5: The output of example 2.1.2Print20 10Print20-10Print20*10Print 20 / 10End SubVIJAYA COLLEGEPage 6

VISUAL BASICLesson 3-Working With ControlsBefore writing an event procedure for the control to response to auser's input, you have to set certain properties for the control todetermine its appearance and how it will work with the eventprocedure. You can set the properties of the controls in the propertieswindow or at runtime.VIJAYA COLLEGEPage 7

VISUAL BASICFigure 3.1 onthe right is atypicalpropertieswindow for aform. You canrenametheform captionto any namethat you likebest. In thepropertieswindow,theitem appearsat the top partis the objectcurrentlyselected(inFigure 3.1, theobjectselectedisForm1). At thebottompart,theitemslisted in theleftcolumnrepresent edobjectwhiletheitemslisted in therightcolumnrepresent thestates of theproperties.Properties canbesetbyhighlightingthe items intherightcolumnthenchange themby typing orselecting theoptionsVIJAYA COLLEGEPage 8

VISUAL BASICavailable.For example, in order to change the caption, just highlight Form1under the name Caption and change it to other names. You may alsotry to alter the appearance of the form by setting it to 3D or flat. Otherthings you can do are to change its foreground and background color,change the font type and font size, enable or disable minimize andmaximize buttons and etc.You can also change the properties at runtime to give special effectssuch as change of color, shape, animation effect and so on. Forexample the following code will change the form color to red everytime the form is loaded. VB uses hexadecimal system to represent thecolor. You can check the color codes in the properties windows whichare showed up under ForeColor and BackColor .Private Sub Form Load()Form1.ShowForm1.BackColor &H000000FF&End SubAnother example is to change the control Shape to a particular shapeat runtime by writing the following code. This code will change theshape to a circle at runtime. Later you will learn how to change theshapes randomly by using the RND function.Private Sub Form Load()Shape1.Shape 3End Sub3.2 Handling some of the common controls in VB6When we launched Visual Basic 6 standard project, the default controlsare displayed in the Toolbox as shown in Figure 3.2 below. Later , ogramming.VIJAYA COLLEGEPage 9

VISUAL BASIC3.2.1 The Text BoxThe text box is the standard control for accepting input from the useras well as to display the output. It can handle string (text) andnumeric data but not images or pictures. String in a text box can beconverted to a numeric data by using the function Val(text). Thefollowing example illustrates a simple program that processes theinput from the user.Example 3.1In this program, two text boxes are inserted into the form togetherwith a few labels. The two text boxes are used to accept inputs fromthe user and one of the labels will be used to display the sum of twonumbers that are entered into the two text boxes. Besides, acommand button is also programmed to calculate the sum of the twonumbers using the plus operator. The program use creates a variablesum to accept the summation of values from text box 1 and text boxVIJAYA COLLEGEPage 10

VISUAL BASIC2.The procedure to calculate and to display the output on the label isshown below. The output is shown in Figure 3.3Private Sub Command1 Click()‘To add the values in text box 1 and text box 2Sum Val(Text1.Text) Val(Text2.Text)‘To display the answer on label 1Label1.Caption SumEnd SubFigure 3.33.2.2 The LabelThe label is a very useful control for Visual Basic, as it is not only usedto provide instructions and guides to the users, it can also be used toVIJAYA COLLEGEPage 11

VISUAL BASICdisplay outputs. One of its most important properties is Caption.Using the syntax label.Caption, it can display text and numeric data .You can change its caption in the properties window and also atruntime. Please refer to Example 3.1 and Figure 3.1 for the usage oflabel.3.2.3 The Command ButtonThe command button is one of the most important controls as it isused to execute commands. It displays an illusion that the button ispressed when the user click on it. The most common event associatedwith the command button is the Click event, and the syntax for theprocedure isPrivate Sub Command1 Click ()StatementsEnd Sub3.2.4 The Picture BoxThe Picture Box is one of the controls that is used to handle graphics.You can load a picture at design phase by clicking on the picture itemin the properties window and select the picture from the selectedfolder. You can also load the picture at runtime using the LoadPicturemethod. For example, the statement will load the picture grape.gif intothe picture box.Picture1.Picture LoadPicture ("C:\VB program\Images\grape.gif")You will learn more about the picture box in future lessons. The imagein the picture box is not resizable.3.2.5 The Image BoxVIJAYA COLLEGEPage 12

VISUAL BASICThe Image Box is another control that handles images and pictures. Itfunctions almost identically to the picture box. However, there is onemajor difference, the image in an Image Box is stretchable, whichmeans it can be resized. This feature is not available in the PictureBox. Similar to the Picture Box, it can also use the LoadPicture methodto load the picture. For example, the statement loads the picturegrape.gif into the image box.Image1.Picture LoadPicture ("C:\VB program\Images\grape.gif")3.2.6 The List BoxThe function of the List Box is to present a list of items where the usercan click and select the items from the list. In order to add items tothe list, we can use the AddItem method. For example, if you wishto add a number of items to list box 1, you can key in the followingstatementsExample 3.2Private Sub Form Load ( )List1.AddItem “Lesson1”List1.AddItem “Lesson2”List1.AddItem “Lesson3”List1.AddItem “Lesson4”End SubThe items in the list box can be identified by the ListIndex property,the value of the ListIndex for the first item is 0, the second item has aListIndex 1, and the second item has a ListIndex 2 and so on3.2.7 The Combo BoxVIJAYA COLLEGEPage 13

VISUAL BASICThe function of the Combo Box is also to present a list of items wherethe user can click and select the items from the list. However, the userneeds to click on the small arrowhead on the right of the combo box tosee the items which are presented in a drop-down list. In order to additems to the list, you can also use the AddItem method. Forexample, if you wish to add a number of items to Combo box 1, youcan key in the following statementsExample 3.3Private Sub Form Load ( )Combo1.AddItem “Item1”Combo1.AddItem “Item2”Combo1.AddItem “Item3”Combo1.AddItem “Item4”End Sub3.2.8 The Check BoxThe Check Box control lets the user selects or unselects an option.When the Check Box is checked, its value is set to 1 and when it isunchecked, the value is set to 0. You can include the statementsCheck1.Value 1 to mark the Check Box and Check1.Value 0 tounmark the Check Box, as well as use them to initiate certain actions.For example, the program will change the background color of theform to red when the check box is unchecked and it will change to bluewhen the check box is checked. You will learn about the conditionalstatement If .Then .Elesif in later lesson. VbRed and vbBlue are colorconstants and BackColor is the background color property of the form.Example 3.4VIJAYA COLLEGEPage 14

VISUAL BASICPrivate Sub Command1 Click()IfCheck1.ValueMsgBoxElseIf 1AndCheck2.Value"AppleCheck2.ValueMsgBox is1AndCheck1.Value"Orangeis0Thenselected" 0Thenselected"ElseMsgBox"Allareselected"End IfEndSub3.2.9 The Option BoxThe Option Box control also lets the user selects one of the choices.However, two or more Option Boxes must work together because asone of the Option Boxes is selected, the other Option Boxes will beunselected. In fact, only one Option Box can be selected at one time.When an option box is selected, its value is set to “True” and when it isunselected; its value is set to “False”. In the following example, theshape control is placed in the form together with six Option Boxes.When the user clicks on different option boxes, different shapes willappear. The values of the shape control are 0, 1, and 2,3,4,5 whichwill make it appear as a rectangle, a square, an oval shape, a roundedrectangle and a rounded square respectively.Example 3.5Private Sub Option1 Click ( )Shape1.Shape 0End SubPrivate Sub Option2 Click()VIJAYA COLLEGEPage 15

VISUAL BASICShape1.Shape 1End SubPrivate Sub Option3 Click()Shape1.Shape 2End SubPrivate Sub Option4 Click()Shape1.Shape 3End SubPrivate Sub Option5 Click()Shape1.Shape 4End SubPrivate Sub Option6 Click()Shape1.Shape 5End Sub3.2.10 The Drive List BoxThe Drive ListBox is for displaying a list of drives available in yourcomputer. When you place this control into the form and run theprogram, you will be able to select different drives from your computeras shown in Figure 3.4VIJAYA COLLEGEPage 16

VISUAL BASIC3.2.11 The Directory List BoxThe Directory List Box is for displaying the list of directories or foldersin a selected drive. When you place this control into the form and runthe program, you will be able to select different directories from aselected drive in your computer as shown in Figure 3.5VIJAYA COLLEGEPage 17

VISUAL BASIC3.2.12 The File List BoxThe File List Box is for displaying the list of files in a selected directoryor folder. When you place this control into the form and run theprogram, you will be able to shown the list of files in a selecteddirectory as shown in Figure 3.5VIJAYA COLLEGEPage 18

VISUAL BASICLesson 4 : Writing the CodeIn lesson 2, you have learned how to enter the program code and runthe sample VB programs but without much understanding about thelogics of VB programming. Now, let’s get down to learning some basicrules about writing the VB program code.Each control or object in VB can usually run many kinds of events orprocedures; these events are listed in the dropdown list in the codewindow that is displayed when you double-click on an object and clickon the procedures’ box(refer to Figure 2.3). Among the events areloading a form, clicking of a command button, pressing a key on thekeyboard or dragging an object and more. For each event, you need towrite an event procedure so that it can perform an action or a seriesof actionsTo start writing an event procedure, you need to double-click anobject. For example, if you want to write an event procedure when auser clicksa command button, you double-click on the commandbutton and an event procedure will appear as shown in Figure 2.1. Ittakes the following format:Private Sub Command1 Click(Key in your program code here)End SubYou then need to key-in the procedure in the space between PrivateSub Command1 Click. End Sub. Sub actually stands for subprocedure that made up a part of all the procedures in a program. Theprogram code is made up of a number of statements that set certainVIJAYA COLLEGEPage 19

VISUAL BASICproperties or trigger some actions. The syntax of Visual Basic’sprogram code is almost like the normal English language though notexactly the same, so it is very easy to learn.The syntax to set the property of an object or to pass certain value toit is :Object.Propertywhere Object and Property is separated by a period (or dot). Forexample, the statement Form1.Show means to show the form withthe name Form1, Iabel1.Visible true means label1 is set to bevisible, Text1.text ”VB” is to assign the text VB to the text box withthe name Text1, Text2.text 100 is to pass a value of 100 to the textbox with the name text2, Timer1.Enabled False is to disable thetimer with the name Timer1 and so on. Let’s examine a few examplesbelow:Example 4.1Private Sub Command1 clickLabel1.Visible falseLabel2.Visible TrueText1.Text ”You are correct!”End subExample 4.2Private Sub Command1 clickLabel1.Caption ” Welcome”Image1.visible trueEnd subExample 4.3Private Sub Command1 clickPictuire1.Show trueVIJAYA COLLEGEPage 20

VISUAL BASICTimer1.Enabled TrueLable1.Caption ”Start CountingEnd subVIJAYA COLLEGEPage 21

VISUAL BASICIn Example 4.1, clicking on the command button will make label1become invisible and label2 become visible; and the text” You arecorrect” will appear in TextBox1.In example 4.2, clicking on thecommand button will make the caption label1 change to “Welcome”and Image1 will become visible.In example 4.3 , clicking on thecommand button will make Picture1 show up, timer starts running andthe caption of label1 change to “Start Counting”.Syntaxes that do not involve setting of properties are also Englishlike, some of the commands are Print, If Then .Else .End If,For Next, Select Case .End Select, End and Exit Sub. Forexample, Print “ Visual Basic” is to display the text Visual Basic onscreen and End is to end the program. Other commands will beexplained in details in the coming lessons.Program code that involve calculations is very easy to write, you needto write them almost like you do in mathematics. However, in order towrite an event procedure that involves calculations, you need to knowthe basic arithmetic operators in VB as they are not exactly the sameas the normal operators we use, except for and - . Formultiplication, we use *, for division we use /, for raising a number xto the power of n, we use x n and for square root, we use Sqr(x).VB offers many more advanced mathematical functions such as Sin,Cos, Tan and Log, they will be discussed in lesson 10. There are alsotwo important functions that are related to arithmetic operations, i.e.the functions Val and Str where Val is to convert text entered into atextbox to numerical value and Str is to display a numerical value ina textbox as a string (text). While the function Str is as important asVB can display a numeric values as string implicitly, failure to use ValVIJAYA COLLEGEPage 22

VISUAL BASICwill results in wrong calculation. Let’s examine example 4.4 andexample 4.5.Example 4.5Example 4.4Private Sub Form Activate()Private Sub Form Activate()Text3.text val(text1.text) val(text2.text)Text3.text text1.text text2.textEnd SubEnd SubWhen you run the program in example 4.4 and enter 12 in textbox1 and 3 intextbox2 will give you a result of 123, which is wrong. It is because VB treat thenumbers as string and so it just joins up the two strings. On the other hand, runningexampled 4.5 will give you the correct result, i.e., 15.Lesson 5: Managing Visual Basic DataThere are many types of data that we come across in our daily life. Forexample, we need to handle data such as names, addresses, money,date, stock quotes, statistics and more everyday. Similarly in VisualBasic, we have to deal with all sorts of of data, some can bemathematically calculated while some are in the form of text or otherforms. VB divides data into different types so that it is easier tomanage when we need to write the code involving those data.5.1 Visual Basic Data TypesVisual Basic classifies the information mentioned above into two majordata types; they are the numeric data types and the non-numeric datatypes.Table 5.1: Numeric Data TypesTypeStorage Range of ValuesByte1 byte0 to 255Integer2 bytes-32,768 to 32,767VIJAYA COLLEGEPage 23

VISUAL BASICLong4 bytes-2,147,483,648 to 2,147,483,648Single4 bytes-3.402823E 38to-1.401298E-45fornegative1.401298E-45 to 3.402823E 38 for positive values.8 bytes-1.79769313486232e 308 to -4.94065645841247E-324 for negativevalues4.94065645841247E-324 to 1.79769313486232e 308 for positivevalues.DoublevaluesCurrency 8 bytes-922,337,203,685,477.5808 to 922,337,203,685,477.5807Decimal /- 79,228,162,514,264,337,593,543,950,335 if no decimal is use /- 7.9228162514264337593543950335 (28 decimal places).12 bytes5.1.2 Non-numeric Data TypesNonnumeric data types are data that cannot be manipulatedmathematically using standard arithmetic operators. The non-numericdata comprises text or string data types, the Date data types, theBoolean data types that store only two values (true or false), Objectdata type and Variant data type .They are summarized in Table 5.2Table 5.2: Nonnumeric Data TypesData TypeStorageRangeString(fixed length)Length of string1 to 65,400 charactersString(variable length) Length 10 bytes 0 to 2 billion charactersDate8 bytesJanuary 1, 100 to December 31, 9999Boolean2 bytesTrue or FalseObject4 bytesAny embedded objectVariant(numeric)16 bytesAny value as large as DoubleVIJAYA COLLEGEPage 24

VISUAL BASICVariant(text)Length 22 bytesSame as variable-length string.1.3 Suffixes for LiteralsLiterals are values that you assign to data. In some cases, we need toadd a suffix behind a literal so that VB can handle the calculation moreaccurately. For example, we can use num 1.3089# for a Double typedata. Some of the suffixes are displayed in Table 5.3.Table 5.3SuffixData Type&Long!Single#Double@CurrencyIn addition, we need to enclose string literals within two quotationsand date and time literals within two # sign. Strings can contain anycharacters, including numbers. The following are few examples:memberName "Turban,TelNumber "1800-900-888-777"LastDay #31-Dec-00#ExpTime #12:00 am#John."Lesson 5: Managing Visual Basic DataThere are many types of data that we come across in our daily life.For example, we need to handle data such as names, addresses,money, date, stock quotes, statistics and more everyday. Similarlyin Visual Basic, we have to deal with all sorts of of data, some canbe mathematically calculated while some are in the form of text orother forms. VB divides data into different types so that it is easierto manage when we need to write the code involving those data.5.1 Visual Basic Data TypesVisual Basic classifies the information mentioned above into twomajor data types, they are the numeric data types and the nonnumeric data types.VIJAYA COLLEGEPage 25

VISUAL BASIC5.1.1 Numeric Data TypesNumeric datatypesaretypes of datathat consist ofnumbers,which can becomputedmathematicallywith variousstandardoperators suchas add, minus,multiply,divideandmore.Examplesofnumeric datatypesareexaminationmarks, height,weight,thenumberofstudents in aclass,sharevalues, price ofgoods,monthly bills,feesandothers.InVisualBasic,numeric dataaredividedinto 7 types,depending onthe range ofvaluestheycanstore.Calculationsthatonlyinvolve roundfigures or datathat does notneed precisioncanuseIntegerorLong integer inthecomputation.Programs thatVIJAYA COLLEGEPage 26

VISUAL BASICrequirehighprecisioncalculationneed to useSingleandDoubledecision datatypes, they arealsocalledfloating pointnumbers. Forcurrencycalculation,you can usethecurrencydatatypes.Lastly, if evenmore precisionis required toperformcalculationsthat involve amany decimalpoints, we canusethedecimaldatatypes.Thesedatatypessummarized inTable 5.1Table 5.1: Numeric Data TypesTypeStorage Range of ValuesByte1 byte0 to 255Integer2 bytes-32,768 to 32,767Long4 bytes-2,147,483,648 to 2,147,483,6484 bytes-3.402823E 38 tonegative1.401298E-45topositive values.8 bytes-1.79769313486232e 645841247E-324to1.79769313486232e 308forpositivevalues.SingleDoubleCurrency 8 bytes-1.401298E-45 forvalues3.402823E 5807toDecimal 12 bytes /-VIJAYA COLLEGEPage 27

VISUAL imalisuse /- 7.9228162514264337593543950335(28 decimal places).5.1.2 Non-numeric Data TypesNonnumeric data types are data that cannot be manipulatedmathematically using standard arithmetic operators. The nonnumeric data comprises text or string data types, the Date datatypes, the Boolean data types that store only two values (true orfalse), Object data type and Variant data type .They aresummarized in Table 5.2Table 5.2: Nonnumeric Data TypesData ing(variablelength)0 to2Length billion10 bytescharactersof1to65,400charactersDate8 bytesJanuary1, 100 toDecember31, 9999Boolean2 bytesTrueFalseObject4 bytesAnyembeddedobjectVariant(numeric) 16 bytesVariant(text)orAny valueaslargeas DoubleSame asLength 22 variablebyteslengthstring5.1.3 Suffixes for LiteralsLiterals are values that you assign to data. In some cases, we needVIJAYA COLLEGEPage 28

VISUAL BASICto add a suffix behind a literal so that VB can handle the calculationmore accurately. For example, we can use num 1.3089# for aDouble type data. Some of the suffixes are displayed in Table 5.3.Table 5.3SuffixDataType&Long!Single#Double@CurrencyIn addition, we need to enclose string literals within two quotationsand date and time literals within two # sign. Strings can containany characters, including numbers. The following are fewexamples:memberName "Turban,TelNumber "1800-900-888-777"LastDay #31-Dec-00#ExpTime #12:00 am#John."5.2 Managing VariablesVariables are like mail boxes in the post office. The contents of thevariables changes every now and then, just like the mail boxes. Interm of VB, variables are areas allocated by the computer memory tohold data. Like the mail boxes, each variable must be given a name.To name a variable in Visual Basic, you have to follow a set of rules.5.2.1 Variable NamesThe following are the rules when naming the variables in Visual Basic It must be less than 255 characters No spacing is allowed It must not begin with a number Period is not permittedVIJAYA COLLEGEPage 29

VISUAL BASICExamples of valid and invalid variable names are displayed in Table 5.4Table 5.4Valid NameInvalid NameMy CarThisYearMy.Car1NewBoyHe&HisFatherLong Name Can beUSEacceptable*&isnot5.2.2 Declaring VariablesIn Visual Basic, one needs to declare the variables before using themby assigning names and data types. They are normally declared in thegeneral section of the codes' windows using the Dim statement.The format is as follows:Dim Variable Name As Data TypeExample im doDate As DateYou may also combine them in one line , separating each variable witha comma, as numAsInteger,.If data type is not specified, VB will automatically declare the variableasaVariant.For string declaration, there are two possible formats, one for theVIJAYA COLLEGEPage 30

VISUAL BASICvariable-length string and another for the fixed-length string. For thevariable-length string, just use the same format as example 5.1above. However, for the fixed-length string, you have to use theformat as shown below:Dim VariableName as String * n, where n defines the number ofcharacters the string can hold.Example 5.2:Dim yourName as String * 10yourName can holds no more than 10 Characters.5.3 ConstantsConstants are different from variables in the sense that their values donot change during the running of the program.5.3.1 Declaring a ConstantThe format to declare a constant isConst Constant Name As Data Type ValueExample 5.3Const Pi As Single 3.142Const Temp As Single 37Const Score As Single 100Lesson 6: Working with Variables6.1 Assigning Values to VariablesVIJAYA COLLEGEPage 31

VISUAL BASICAfter declaring various variables using the Dim statements, we canassign values to those variables. The general format of an assignmentisVariable ExpressionThe variable can be a declared variable or a control property value.The expression could be a mathematical expression, a number, astring, a Boolean value (true or false) and more. The following aresome examples:firstNumber 100secondNumber firstNumber99userName "JohnLyan"userpass.Text passwordLabel1.Visible TrueCommand1.Visible falseLabel4.Caption textbox1.TextThirdNumber Val(usernum1.Text)total firstNumber secondNumber ThirdNumber6.2 Operators in Visual BasicTo compute inputs from users and to generate results, we need to usevarious mathematical operators. In Visual Basic, except for and , the symbols for the operators are different from normal mathematicaloperators, as shown in Table 6.1.Table 6.1: Arithmetic OperatorsOperator Mathematical functionExample Exponential2 4 16*Multiplication4*3 12,/Division12/4 3ModModulus(return the remainder from an integer15 Mod 4 3division)\Integer Division(discards the decimal places)19\4 4 or &String concatenation"Visual"&"Basic" "VisualBasic"Example 6.1DimfirstNameVIJAYA COLLEGE(5*6))2 60255 mod 10 5Example 6

VISUAL BASIC VIJAYA COLLEGE Page 1 Lesson1: Introduction to Visual Basic 6 Before we begin Visual Basic 6 programming, let us understand some basic concepts of programming. According to Webopedia, a computer program is an organized list of instructions that, when executed, causes