VISUAL BASIC - Vijaya College, Bangalore

3y ago
54 Views
2 Downloads
3.34 MB
115 Pages
Last View : 18d ago
Last Download : 3m ago
Upload by : Julia Hutchens
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 ha

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 the computer to behave in a predetermined manner. Without

Related Documents:

2 Acharya Bangalore B School, Bangalore India 5 3 60 0.19 3 Acharya College of Nursing, Rajiv Gandhi University of Health Sciences, Bangalore India 1 0 0 0 4 Acharya Institute of Graduate Studies, Bangalore India 4 0 0 0 5 Acharya Institute of Technology, Bangalore University India 1 1 100 0.06 6 Alpine

Gopalan Urban Woods Mahadevapura, Bangalore Sai Krupa Harmony Mahadevapura, Bangalore Livability Rating* 7.6/10 7.4/10 7.2/10 Safety Rating* N.A. N.A. N.A. Builder Bren Gopalan Sai Krupa Locality Doddanekundi, Bangalore Mahadevapura, Bangalore Mahadevapura, Bangalore Numbe

Visual Basic - Chapter 2 Mohammad Shokoohi * Adopted from An Introduction to Programming Using Visual Basic 2010, Schneider. 2 Chapter 2 –Visual Basic, Controls, and Events 2.1 An Introduction to Visual Basic 2.2 Visual Basic Controls 2.3 Visual Basic Events. 3 2.1 An Introduction to

Visual Basic 6.0 versus Other Versions of Visual Basic The original Visual Basic for DOS and Visual Basic F or Windows were introduced in 1991. Visual Basic 3.0 (a vast improvement over previous versions) was released in 1993. Visual Basic 4.0 released in late 1995 (added 32 bit application support).

Visual Basic is a third-generation event-driven programming language first released by Microsoft in 1991. The versions of visual basic in shown below: The final version of the classic Visual Basic was Visual Basic 6. Visual Basic 6 is a user-friendly programming language designed for beginners. In 2002, Microsoft released Visual Basic.NET (VB .

Interpreters and compilers like Visual Basic are called high-level language. Some of the high level programming languages beside Visual Basic are Fortran, Cobol, Java, C, C , Turbo Pascal, and more . Among the aforementioned programming languages, Visual Basic is the most popular. Not only it is easily to learn because of its English-

Bangalore, India bhagyalaxmi.arch@bmsce.ac.in Ar. Sindhu Srikanth Department of Architecture BMS College of Engineering Bangalore, India sindhusrikanth.arch@bmsce.ac.in Ar. Arjun K S Sekos Architects Bangalore, India arjunks91@gmail.com Abstract - Urban design has the greatest impac

TASC Reading Test Practice Items Read the text. Then answer the questions. Excerpt from Main Street by Sinclair Lewis Main Street is a novel about a girl who grew up in the big city. She has married a physician who moves them to the small town in the Midwest in which he grew up. She is reluctant to move from the city she knows, but goes along with her husband thinking that perhaps she can .