VISUAL BASIC PROGRAM PRACTICE TASKS.
Table of Contents
Open up Visual Basic Applications (VBA) by: 1. Customising the Quick Access toolbar
Now choose “More Commands”
Michael Elsner 2014
Page 1
Then Choose All Commands, then scroll through the list and select Visual Basic and ADD it the Menu list on the right. Then click OK.
To open up Visual Basic double click on the Visual Basic icon on the Quick Access toolbar
To start to design your Form click on Insert, UserForm Michael Elsner 2014
Page 2
Your screen will now look like this: This is your form design screen.
If you cannot see the TWO Menus on the side (PROJECT EXPLORER and PROPERTIES WINDOW) you can add them by using the View Menu and selecting them from there or by Pressing ctrl+R for the Project Explorer and pressing F4 for the Properties Window (see below)
Michael Elsner 2014
Page 3
To start creating your program you can add objects to your Form by choosing objects from the Tool Box.
Common Tools used are: Label - to give basic information about other tools especially for to indicate the purpose and type of data to be entered in a text box or other type of box. (List box, Check box, Combo box, radio/option button). Command button - commonly used to get a mouse click (note. Is visual basic .net just referred to as button) Frame to group similar objects/topics together.
Object Name
Prefix
Eg. Name
Label
lbl
lblName
Textbox
txt
txtPath
Listbox
lst
lstDictionary
Checkbox
chk
chkInterest
Option button
opt
optMale
Command button
cmd or btn
btnSave
Form
frm
frmUserName
Image
img
imgProfilePic
Frame
fra
fraDetails
Once you have chosen the required tool, you can then move your mouse over to the form and then draw the tool on the form by using the mouse. You can then change the size by dragging the corners. More examples see end Michael Elsner 2014
Page 4
To add code to each object you need to double click on the object you would like to add the code to. It will then open a new window as seen below with the same name of the object you added. Visual basic is and Event driven language meaning that when a particular event occurs, it triggers a particular piece of code. Eg. When you Click on the CommandButton1 is runs the code in that procedure. Some common events are Click, Change, Load eg.(see below) you can add code to any of these events.
Each object you add, you can change its properties : Name, Caption, Text, Size, Color, Visible, Enabled etc. These are common ones for most objects but will vary slightly depending on the object chosen. Note: if you change the name of a object after you have added code to it you will then also have to go to the code window and change the name of it there. *Default Name for command button Private Sub CommandButton1_Click() End Sub *Name changed to btnSave Private Sub btnSave_Click() End Sub To change the text displayed on the button change the text in the Caption property. Note: this does NOT change the name of the object and the way it is referenced in the code window.
Activity 1: Add a Command button then double click on the button to see the code window. Then click on the UserForm1 icon in the Project Explorer window. Now change the caption of the command button in the properties window to be Close and change the Name to be btnClose.
Michael Elsner 2014
Page 5
Double click on the button and then type the following code in the correct procedure. This will close the form when the button is clicked. Private Sub btnClose_Click() End End Sub
RUN To run your program click on the green arrow button at the top of the screen.
Activity 2: Create a form that has 2 Labels, 2 Textboxes and a command button. Change the following details. Label1 Name
lblHeight
Caption
Please enter height
Label 2 Name
lblLength
Caption
Please enter length
Textbox 1 Name
txtHeight
Textbox 2 Name
txtLength
Command button 1 Name
btnCalculateArea
Caption
Calculate Area
Michael Elsner 2014
Page 6
Add the following code: (when you click on the calculate area button.) MsgBox (TextBox1.Text * TextBox2.Text) ‘this multiplies the entered numbers and shows the answer in a message box.
Additional task 1. Change the caption of the UserForm from UserForm1 to your name.
Additional task 2. Instead of using the text box.text as variables create a variable called intHeight and a variable called intLength and assign them their values from the relevant textbox. (The int prefix is used to indicate the variable is a integer data type). The following code creates a intHeight variable, use it as a reference to create the intLength variable. Also create a variable to hold the calculated area called intArea Eg. Make sure you fill in the missing parts. Dim intHeight As Integer Dim As integer Dim
‘declares variable as integer data type
intHeight = txtHeight.text = txtLength.text
‘assigns value of textbox to variable
intArea = intHeight * intLength MsgBox ("Area: " & intArea) ‘display a message of the total area (Comments explained click here)
RUN To run your program click on the green arrow button at the top of the screen. Michael Elsner 2014
Page 7
To SAVE your work, first Click On the ThisDocument Icon on the Project Explorer window.
Then go to the File menu, Choose save. To save this document properly you will need to change the type from .docx to .docm. Then click SAVE.
Indexes and Arrays Indexes Used to store and retrieve information efficiently. (house number, page numbers, library cards) ListIndex property of a control In programming index refers to the position of a particular item in a list or collection of items. Indexes usually start at 0 ZERO in programming. So the highest number in the index is usually one less than the total number of items
Arrays A variable is a piece of memory that has a name(reference) to which the computer can assign a value Arrays are a special type of variable that can hold a number of different/multiple values of the same type. Array has a name and each value in the array has an index number. Each item in an array is called an element and is referenced by its index number or sequence in the array.
Michael Elsner 2014
Page 8
Identify the name of the array? How many elements are in this array? What are some other common examples of arrays? Filing system, library books. Why? If doing calculations for students in a class or staff in a company you would not create 20+ variables for each person. Makes code to long and complicated.
Create an Array Define it. Dim MonthName(11) As String You can add data to the elements of an array by the following Dim MonthName(11) As String MonthName(0) = "Jan" MonthName(1) = "Feb" MonthName(2) = "Mar" MonthName(3) = "Apr" MonthName(4) = "May" MonthName(5) = "Jun" MonthName(6) = "Jul" MonthName(7) = "Aug" MonthName(8) = "Sep" MonthName(9) = "Oct" MonthName(10) = "Nov"
Michael Elsner 2014
Page 9
MonthName(11) = "Dec" To choose a starting index number other than zero the To keyword can be used. Dim MonthName(1 To 12) As String Other examples STUDENT(29), Score(29), Team_Name(9). To retain the info stored in an array between call to a procedure use the Static keyword. Static itemNumber(29) Referring to Elements When referring to an array you must include the index number of the element you want to refer to. The index(element) number is usually enclosed in parentheses immediately after the array name. The number inside the parentheses is called the subscript. For example to refer to the month April in the array called MonthName() MonthName(3) This displays the fourth element (April), as the numbering starts at zero. You can also use a numeric variable as below. For intPos = 0 To 11 MsgBox MonthName(intPos) Next intPos The above would display all elements in the array.
Challenge 1. Use the code from Create an Array to create an array called MonthName() and use the For Next loop to display all the elements/months of the year.
2. Use a For loop to create the following pyramid X XX XXX XXXX XXXXX
Michael Elsner 2014
Page 10
While Loop or Do loop ‘the below code uses a loop to count and repeat an action a set number of times This will be useful for your final task. counter = 0 myNum = intX Do myNum = myNum + 1 counter = counter + 1 Loop While myNum < 10 MsgBox "The loop made " & counter & " repetitions."
Comments Comments are used to provide information about the program such as the author, purpose and date of creations and modifications. Additionally, comments are used to provide information about specific code line/s of code and what they actually do. Comments are indicated by placing a ‘ at the front of the text. Any text after the ‘ is ignored by the computer when the program is running. Is it good practice to include comments in your code as you may forget what certain sections of the code do if you need to modify the program at a later time. ‘’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’ ‘Program created by Mr Elsner 20.6.2014 ‘Modified 26.6.2014 by adding Print functionality ‘’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’’ MsgBox ("Area: " & intArea) ‘display a message of the total area Return to Activity
Visual Basic Prefixes Objects
Object
Michael Elsner 2014
ID
Object
ID
Check Box
chk
Label
lbl
Combo Box
cbo
Line
lin
Command Button
cmd
List Box
lst
Data
dat
OLE
ole
Directory List dir Box
Option Button
opt
Drive List Box drv
Picture Box pic
Page 11
File List Box
fil
Shape
shp
Form
frm
Text Box
txt
Frame
fra
Timer
tmr
Horizontal Scroll Bar
hsb
Vertical Scroll Bar
vsb
Image
img eg. cmdLeft, txtAnswer Back to Activities
Variables Type ID
Byte
byt
Boolean
bln
Currency
cur
Date (Time) dtm Double
dbl
Integer
int
Long Integer lng Object
obj
Single
sng
String
str
Variant
vnt
eg. strFirst_Name, intAge, sngSalary Back to Activities Sourced from http://gcctech.org/csc/VB/VB_3letterObjectID.htm Michael Elsner 2014
Page 12
25.6.2014
Randomise Randomise numbers can be done by using the following code intX = Int((9 * Rnd) + 1) â&#x20AC;&#x2DC;creates a random number between 1 to 10 and assign it to a variable intX Note: generally numbers when programming start from 0 , so ((9*Rnd)+1) uses a range from 0-9 but the +1 changes the range from 1 â&#x20AC;&#x201C; 10. The int() converts the characters/string to an integer number. Private Sub UserForm_Initialize() intX = Int((9 * Rnd) + 1) intFileNumber = FreeFile End Sub
Michael Elsner 2014
Page 13