unit 4 vb
TRANSCRIPT
-
7/29/2019 Unit 4 VB
1/15
Visual Basic Modules and Procedures
Visual Basic Code Modules
Visual Basic application source code is structured into module files with a .vb suffix. By default,
Visual Studio creates a separate module file for each form in an application containing the code
to construct the form. For example, the code to create a form called Form1 will be placed in a
module file named Form1.Designer.vb. Similarly, any code that has been defined by the
developer to handle events from controls in the form will be placed by Visual Studio into a module
file called Form1.vb.
When writing additional Visual Basic for an application, the code should ideally be logically
grouped to together with other source code in a module file. When we say logically groupedwe
mean that the code should be grouped with other code of a similar nature. For example, code to
work with files might be placed in a module called FileIO.vb, while mathematical procedures
might all reside in a file named Math.vb. The idea is to ensure Visual Basic code is placed in a file
where it makes sense for it to be located. This will differ between applications, but it is worth
investing the time to ensure code is well structured as doing so makes subsequent maintenance
of the code by you or other developers much easier.
We mentioned previously that Visual Studio places the code to construct each form in separate
module files. We now need to learn how to create a new module in a project to contain our own
Visual Basic code. Begin by creating a new WindowsApplication project in Visual Studio
called vbModules. Add two TextBoxcontrols (named value1TextBox and value2TextBox) and a
button (labeled Calculate) to the Form so that appears as follows:
http://www.techotopia.com/index.php/Visual_Basic_Modules_and_Procedureshttp://www.techotopia.com/index.php/Visual_Basic_Modules_and_Procedureshttp://www.techotopia.com/index.php/Visual_Basic_Modules_and_Procedureshttp://www.techotopia.com/index.php/Visual_Basic_Modules_and_Procedureshttp://www.techotopia.com/index.php/Image:Visual_basic_procedures_form.jpghttp://www.techotopia.com/index.php/Visual_Basic_Modules_and_Procedureshttp://www.techotopia.com/index.php/Visual_Basic_Modules_and_Procedures -
7/29/2019 Unit 4 VB
2/15
Once the new project has been opened and the first form is visible, selectAdd Module... from
the Projectmenu. TheAdd Item window will appear with the Module item pre-selected:
Name the new module Math.vb and click theAddbutton. The new module will be added to the
project and a new tab labeled Math.vb for accessing the module code appears in the design area:
http://www.techotopia.com/index.php/Image:Visual_studio_add_module.jpg -
7/29/2019 Unit 4 VB
3/15
Now that we have added a new module to our project the next step is to add Visual Basic code to
that module. Before we can do that, however, we need to learn about Visual Basicprocedures.
Visual Basic Code Procedures
Visual Basic procedures provide a way to break up code into logical and re-usable sections that
can be called from other sections of Visual Basic code. For example, you might have a section of
Visual Basic code that calculates the interest due on a loan. It is also possible that you need to
perform this calculation from a number of different places in yourapplication code. Rather than
duplicating the code to perform this task at each code location where it is needed, it is more
efficient to place the calculation code in a procedure, and then callthat procedure each time it is
needed.
Visual Basic provides two types of procedures:
functions - Functions are procedures which perform a task and return a value when
completed.
subroutines - Subroutines are procedures which perform a task but return no value
when completed.
It is especially useful to be able to return values from functions. For example, the function may
need to return the result of the task it performed (perhaps the result of a calculation). A function
might also return a True orFalse value to indicate when the task was performed successfully.
The Visual Basic code which called the function then acts based on the returned value.
In the case of both subroutines and functions, values (known asparameters) may optionally be
passed into the procedure.
http://www.techotopia.com/index.php/Visual_Basic_Modules_and_Procedureshttp://www.techotopia.com/index.php/Visual_Basic_Modules_and_Procedureshttp://www.techotopia.com/index.php/Visual_Basic_Modules_and_Procedureshttp://www.techotopia.com/index.php/Image:Visual_basic_new_module.jpghttp://www.techotopia.com/index.php/Visual_Basic_Modules_and_Procedureshttp://www.techotopia.com/index.php/Visual_Basic_Modules_and_Procedures -
7/29/2019 Unit 4 VB
4/15
Defining Visual Basic Subroutines
Subroutines are declared inside Visual Basic Modules. Our newly created module in Visual
Studio contains the following:
Module Math
End Module
We are now going to add a subroutine called DisplayResultto this module. The syntax for a
Visual Basic subroutine is as follows:
scopeSubsubroutineName(parameters)
End Sub
The scope value is eitherPrivate orPublicdepending on whether the Subroutine is to be
accessible from Visual Basic code outside of the current module. Sub is the Visual Basic keyword
which indicates this is a Subroutine rather than a Function. subroutineName is the name of the
Subroutine and is used when this specific procedure is to be called. Theparameters value allows
the parameters accepted by this Subroutine to be declared (see below).
The Publickeyword indicates the scope. This defines whether this subroutine is accessible from
Visual Basic code residing in other modules. Setting the scope to Private would make the
Subroutine inaccessible to Visual Basic code outside the current module.
The Sub keyword indicates that this is a Subroutine (as opposed to a Function) and as such,
does not return a value on completion. Finally, the name of the Subroutine is provided. The
parentheses are used to hold any parameters which may be passed through to the Subroutine
when it is called. The End Sub code marks the end of the Subroutine. The Visual Basic code that
constitutes the Subroutine is placed after the Subroutine declaration and the End Sub.
We can write code in the Subroutine to display a message window as follows:
Module Math
Public Sub DisplayResult()
MessageBox.Show("Test message")
End Sub
End Module
Next, the Clickevent procedure of the button in our form needs to call
the DisplayResult() Subroutine. Double click on the button in the form to display the event
procedure code and add the call toDisplayResult() as follows:
-
7/29/2019 Unit 4 VB
5/15
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs)
Handles Button1.Click
DisplayResult()
End Sub
Once the above change has been made, press F5 to build and run the application. When the
application is running, pressing the button should cause a message window to appear displaying
the text "Test Message".
Sub Procedures (Visual
Basic)A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End
Sub statements. The Sub procedure performs a task and then returns control to the
calling code, but it does not return a value to the calling code.
Each time the procedure is called, its statements are executed, starting with the first
executable statement after the Sub statement and ending with the first End
Sub, Exit Sub, or Return statement encountered.
You can define a Sub procedure in modules, classes, and structures. By default, it
isPublic
, which means you can call it from anywhere in your application that hasaccess to the module, class, or structure in which you defined it. The term, method,
describes a Sub or Function procedure that is accessed from outside its defining
module, class, or structure. For more information, see Procedures in Visual Basic.
A Sub procedure can take arguments, such as constants, variables, or expressions,
which are passed to it by the calling code.
Declaration Syntax
A Sub procedure is a block of code that is executed in response to anevent. By breaking the code in a module into Sub procedures, it
becomes much easier to find or modify the code in your application.
The syntax for a Sub procedure is: ( we will postpone the discussionon Private/Public/Static to later)
[Private|Public][Static]Sub procedurename(arguments)
http://msdn.microsoft.com/en-us/library/y6yz79c3.aspxhttp://void%280%29/http://msdn.microsoft.com/en-us/library/y6yz79c3.aspxhttp://void%280%29/ -
7/29/2019 Unit 4 VB
6/15
statements
End Sub
Each time the Sub procedure is called, the statements
between Sub and End Sub are executed. Sub procedures can beplaced in standard modules, class modules, and form modules. Subprocedures are by default Public in all modules, which means they canbe called from anywhere in the application.
The arguments for a procedure are like a variable declaration, declaringvalues that are passed in from the calling procedure. We will explorethis after we have defined variables
In VB, it's useful to distinguish between two types ofSub
procedures, event procedures and general procedures.
Event Procedures
When an object in VB recognizes that an event has occurred, itautomatically invokes the event procedure using
the name corresponding to the event. Because the name
establishes an association between the object and the code, event
procedures are said to be attached to forms and controls.
Syntax for a control event
Private Sub controlname_eventname (arguments )
statementsEnd
Syntax for a form event
Sub Private Sub Form_eventname (arguments)
statementsEnd Sub
An event procedure for a control combines the control'sactual name (specified in the Name property), an underscore (_), andthe event name. For instance, if you want a command
-
7/29/2019 Unit 4 VB
7/15
button named cmdPlay to invoke an event procedure when it is clicked,use the procedure cmdPlay_Click.
An event procedure for a form combines the word "Form"an underscore, and the event name. If you want a form to invoke an
event procedure when it is clicked, use the procedureForm_Click. (Likecontrols, forms do have unique names, but they are not used in thenames of event procedures.) If you are using the MDI form, the eventprocedure combines the word "MDIForm," an underscore, and the eventname, as in MDIForm_Load.
All event procedures use the same general syntax.
Although you can write event procedures from scratch, it's easier to usethe code procedures provided by VB, which automatically include the
correct procedure names. You can select a template in the Code Editorwindow by selecting an object from the Object box and then selecting aprocedure from the Procedure box.
We will now examine event procedures and how to program them
Run the program we have created so far by clicking the blue forward
filled triangle on the toolbar
The program compiles and executes. You should see the image of
the form with the controls we created.
Click on any of the command button. Note that nothing happens !
While the command button by default can recognize the mouse click we
have not instructed the program to respond to this event.
Exit/terminate the program by clicking the " X " sign in the title bar of
the application window
This should put us back in VB.
For the following I have retained default names for thevarious objects on the form. You should work with the changes you hadmade earlier because this increases the effectiveness of what you learntoday.
Select Object View
Select the second Command Button you created in the Properties
-
7/29/2019 Unit 4 VB
8/15
WindowChange the caption to read "Exit"
Double click on the second Command Button you created
This should place the code view screen in the center area and provide a
template for the click event procedure. This is the mouse click event.We are now ready to write ourfirst event procedure
Private Sub Command2_Click()End ' exits application - this is a comment -
anything right of the single quote is ignored by
compilerEnd Sub
Run the application
Click the command buttonThe application should terminate and put us back into VB design
environment
We have successfully executed an event procedure.
Function Procedures
A Function procedure is another kind of procedure, similar toa Sub procedure for it can take arguments, perform a series ofstatements, and change the value of its arguments. However, unlikea Sub procedure, a Function procedure can return a value to the callingprocedure.
There are three differencesbetween Sub and Function procedures:(books on line)
Generally, you call a function by including the function procedurename and arguments on the right side of a larger statement orexpression
returnvalue = function()
-
7/29/2019 Unit 4 VB
9/15
Function procedures have data types, just as variables do. Thisdetermines the type of the return value. (In the absence of an As clause,the type is the default Variant type.)
You return a value by assigning it to the procedurename itself. When
the Function procedure returns a value, this value can then become partof a larger expression.
Visual Basic includes built-in, or intrinsic functions, like Sqr, Cos or Chr.In addition, you can use the Function statement to write your ownFunction procedures.
The syntax for a Function procedure is:
[Private|Public][Static]Function procedurename (arguments) [As type]
statements
End Function
Scope of variables (SUMMARY)
Depending on how it is declared, a variable is scoped as either aprocedure-level (local) or module-level variable.Variables declared with the Dim statement within a procedure exist onlyas long as the procedure is executing. When the procedure finishes, thevalue of the variable disappears. In addition, the value of a variable in aprocedure is local to that procedure that is, you can't access a
variable in one procedure from another procedure. Thesecharacteristics allow you to use the same variable names in differentprocedures without worrying about conflicts or accidental changes.
It is a good practice to explicitly declare all variables used in the program. To
enforce this you can use the following line in the declaration sections of
-
7/29/2019 Unit 4 VB
10/15
all modules in theproject
Option Explicit
Additional Scope : Static/Private/Public Variables
Static Variables :A variable declared with Static keyword like
Static I As Integer ( contrast with Dim I As Integer)
exists the entire time the application is running - whilethe variables defined with Dim keyword exists only as long asthe procedure is executing
Public Variables: Can only be used in the (general) section
Public I As Integer
This makes I available to all procedures in all other modules too.
Private Variables: Can only be used in the (general) section
Private I As Integer
This makes I available to all the procedures in the current module.Same as using Dim at the module level
If public variables in different modules share the same name, it'spossible to differentiate between them in code by referring to both themodule and variable names. For example, if there is a public Integervariable intX declared in both Form1 and in Module1, you can refer tothem as Module1.intX and Form1.intX to get the correct values.The names of your private module-level and public module-levelvariables can also conflict with the names of your procedures. Avariable in the module cannot have the same name as any proceduresor types defined in the module. It can, however, have the same name aspublic procedures, types, or variables defined in other modules. In thiscase, when the variable is accessed from another module, it must bequalified with the module name.
-
7/29/2019 Unit 4 VB
11/15
Using Optional Arguments
You can specify arguments to a procedure as optional by placingthe Optional keyword in the argument list. If you specify an optionalargument, all subsequent arguments in the argument list must alsobe optional and declared with the Optional keyword. The two pieces ofsample code below assume there is a form with a command buttonand list box.
For example, this code provides all optional arguments: Addcommand button 4 and a list box to your project
Dim strName As StringDim varAddress As Variant---------------
Sub ListText(Optional x As String, Optional y _
As Variant)
List1.AddItem xList1.AddItem y
End Sub
PrivateSub Command4_Click()strName = "yourname"varAddress = 12345 ' Both arguments are provided.
Call ListText(strName, varAddress)End Sub
The above code provides all the required arguments- the optionalkeyword did not take effectAnother ExampleDim strName As String
Dim varAddress As Variant--------------------
Sub ListText(x As String, Optional y As Variant)
List1.AddItem xIf Not IsMissing(y) Then ' This is a VB built in
function
-
7/29/2019 Unit 4 VB
12/15
List1.AddItem y ' This is an If
statement - next topic
End IfEnd Sub
PrivateSub Command4_Click()
strName = "yourname" ' Second argument is not _' provided.
Call ListText(strName)End Sub
In the case where an optional argument is not provided, the argument isactually assigned as a variant with the value ofEmpty. The exampleabove shows how to test for missing optional arguments usingthe IsMissing function.
Top
Providing a Default for an Optional Argument
It's also possible to specify a default value for an optional argument. Thefollowing example returns a default value if the optional argument isn'tpassed to the function procedure:
Sub ListText(x As String, Optional y As _Variant = 12345)
List1.AddItem x
List1.AddItem yEnd Sub
PrivateSub Command4_Click()strName = "yourname" ' Second argument is not
provided.Call ListText(strName) ' Adds "yourname" and
"12345".
End Sub
http://people.rit.edu/pnveme/Visual_Basic/Argument_Passing.html#Tophttp://people.rit.edu/pnveme/Visual_Basic/Argument_Passing.html#Top -
7/29/2019 Unit 4 VB
13/15
Arrays in Visual Basic
An array is a set of valuesthat are logically relatedto each other,
such as the numberof studentsin each gradein a grammarschool.
By using an array, you can refer to these relatedvalues by the same
name, and use a numberthats called an index or subscript to tell
themapart. The individual valuesare called the elementsof the
array. Theyre contiguousfrom index 0 throughthe highest index
value.
In contrast to an array, a variable that containa single value is called
ascalarvariable.
Characteristics of array
>>
-
7/29/2019 Unit 4 VB
14/15
After you declarethe array, you can defineits size by usingtheReDimStatement(Visual Basic).
The followingexampledeclaresa one-dimensionalarray variableby addinga pair of parenthesesafter
the type. The examplealso specifiesthe dimensionsof the array by usingtheReDimStatement(Visual
Basic).
VB
' Declare a one-dimensional array.
DimcargoWeightsAsDouble()
' Dimension the array.
ReDimcargoWeights(15)
The followingexampledeclaresa multidimensionalarray variableby addinga pair of parenthesesafter
the type and by placingcommasinsidethe parenthesesto separatethe dimensions.The examplealso
specifiesthe dimensionsof the array by usingtheReDimStatement(Visual Basic).
VB' Declare a multidimensional array.
DimatmospherePressuresAsShort(,,,)
' Dimension the array.
ReDimatmosphere Pressures(1, 2, 3, 4)
To declarea jaggedarray variable, add a pair of parenthesesafter the variablenamefor each level of
nestedarray.
VB
Diminquiries By Year Month Day()()()AsByte
The precedingexamplesdeclarearray variablesbut dont assignarraysto them.You must still createanarray, initialize it, and assignit to the variable.
http://msdn.microsoft.com/en-us/library/vstudio/w8k3cys2.aspxhttp://msdn.microsoft.com/en-us/library/vstudio/w8k3cys2.aspxhttp://msdn.microsoft.com/en-us/library/vstudio/w8k3cys2.aspxhttp://msdn.microsoft.com/en-us/library/vstudio/w8k3cys2.aspxhttp://msdn.microsoft.com/en-us/library/vstudio/w8k3cys2.aspxhttp://msdn.microsoft.com/en-us/library/vstudio/w8k3cys2.aspxhttp://msdn.microsoft.com/en-us/library/vstudio/w8k3cys2.aspxhttp://msdn.microsoft.com/en-us/library/vstudio/w8k3cys2.aspxhttp://msdn.microsoft.com/en-us/library/vstudio/w8k3cys2.aspxhttp://msdn.microsoft.com/en-us/library/vstudio/w8k3cys2.aspxhttp://msdn.microsoft.com/en-us/library/vstudio/w8k3cys2.aspx -
7/29/2019 Unit 4 VB
15/15