Anda di halaman 1dari 16

Accessories for Programming Introduction When using a database, you are in fact using two applications to create a final

product. Microsoft Access is used to design the necessary objects for your product. This means that Microsoft Access is used for its visual display of objects. n the other hand, Microsoft !isual "asic is used to handle code that enhances the functionality of your application. The #ompiler The code you write is made of small instructions written in !isual "asic. These instructions are written in $nglish, a language that the computer, that is the operating system, doesn%t understand. !isual "asic, as its own language among other computer languages, is internally e&uipped with a low level program called a compiler. This program ta'es your $nglish language instructions and translates them in a language the computer can understand. The language the computer spea's is 'nown as the machine language. (ou usually don%t need to 'now anything about this language. After writing your code, at one time it is transmitted to the compiler. The compiler analy)es it first, chec's its synta*, the words used in the program, the variables are chec'ed for their declaration and use. The events and procedures are chec'ed for their behavior. The e*pressions are chec'ed for their accuracy. If something is wrong with the code, that is, if the compiler does not understand something in your code, it would display an error and stop. (ou must correct the mista'e or else... As long as the compiler cannot figure out a piece of code in a module, it would not validate it. If the code is +admissible+, the compiler would perform the assignments that are part of the code and give you a result based on its interpretation of the code. This means that the code can be accurate but produce an unreliable or false result. This is because the compiler is just another program, it does not thin' and does not correct mista'es although it can sometimes point them out. -or this reason, you should 'now what you are doing. Writing Procedures With Arguments To carry out an assignment, sometimes a procedure needs one or more values to wor' on. If a procedure needs a value, such a value is called an argument. While a certain procedure might need one argument, another procedure might need many arguments. The number and types of arguments of a procedure depend on your goal. If you are writing your own procedure, then you will decide how many arguments your procedure would need. (ou also decide on the type of the argument.s/. -or a procedure that is ta'ing one argument, inside of the parentheses of the procedure, write the name of the argument followed by the As 'eyword followed by the type of data of the argument. 0ere is an e*ample,
Sub CalculateArea(Radius As Double) End Sub

A procedure can ta'e more than one argument. If you are creating such a procedure, between the parentheses of the procedure, write the name of the first argument followed by As followed by the data type, followed by a comma. Add the second argument and subse&uent arguments and close the parentheses. There is no implied relationship between the arguments1 for e*ample, they can be of the

same type,
Sub CalculatePerimeter(Length As Double, Height As Double) End Sub

The arguments of your procedure can also be as varied as you need them to be. 0ere is an e*ample,
Sub DisplayGreetings(strFullName As String, intAge As Integer, dblDistance As Double) End Sub

Practical 2earning, Writing Procedures With Arguments 3. 4witch to the #ode $ditor. #lic' an empty area at the end of the e*isting code and create the following procedure,
Sub SolveEllipse(SmallRadius As Double, LargeRadius As Double) Dim dblCircum As Double Dim dblArea As Double dblCircum (SmallRadius ! LargeRadius) " # dblArea SmallRadius " LargeRadius " $%&'&() t*tEllipseCircum+erence t*tEllipseArea dblArea End Sub dblCircum

5. To create an e*ample of function that ta'es an argument, add the following function at the end of the e*isting code,
,unction CubeArea(Side As Double) As Double CubeArea Side " Side " End ,unction

6. To use different e*amples of functions that ta'e one or two arguments, type the following functions,
,unction Cube.olume(Side As Double) As Double Cube.olume Side " Side " Side End ,unction ,unction /o*Area(dblLengt0 As Double, 1 dbl2eig0t As Double, 1 dbl3idt0 As Double) As Double Dim Area As Double # " ((dblLengt0 " dbl2eig0t) ! 1 (dbl2eig0t " dbl3idt0) ! 1 (dblLengt0 " dbl3idt0) 1 ) /o*Area Area End ,unction ,unction /o*.olume(dblLengt0 As Double, 1 dbl2eig0t As Double, 1 dbl3idt0 As Double) As Double Area

Dim .olume As Double .olume dblLengt0 " dbl2eig0t " dbl2eig0t /o*.olume .olume End ,unction

#alling Procedures That 0ave Arguments We saw already how to call a procedure that does not ta'e any argument. Actually, there are various ways you can call a sub procedure. As we saw already, if a sub procedure does not ta'e an argument, to call it, you can just write its name. If a sub procedure is ta'ing an argument, to call it, type the name of the sub procedure, followed by space, followed by the name of the argument. If the sub procedure is ta'ing more than one argument, to call it, type the name of the procedure followed by the name of the arguments, in the e*act order they are passed to the sub procedure, separated by a comma. 0ere is an e*ample,
Private Sub t*tResult1Got,ocus() Dim dbl2ours As Double Dim dblSalary As Double dbl2ours dblSalary t*t2ours t*tSalary

CalcAndS0o4Salary dbl2ours, dblSalary End Sub Sub CalcAndS0o4Salary(2ours As Double, Salary As Double) Dim dblResult As Double dblResult t*tResult End Sub 2ours " Salary dblResult

Alternatively, you can use the 'eyword Call to call a sub procedure. In this case, when calling a procedure using Call, you must include the argument.s/ between the parentheses. using Call, the above GotFocus event could call the CalcAndShowSalary as follows,
Private Sub t*tResult1Got,ocus() Dim dbl2ours As Double Dim dblSalary As Double dbl2ours dblSalary t*t2ours t*tSalary

Call CalcAndS0o4Salary(dbl2ours, dblSalary) End Sub

Practical 2earning, #alling Procedures With Arguments 3. To call the above procedures that ta'e arguments, on the bject combo bo*, select cmdECalculate and implement its OnClick event as follows,
Private Sub cmdECalculate1Clic5() Dim Radius& As Double Dim Radius# As Double Radius& t*tEllipseRadius& Radius# t*tEllipseRadius#

SolveEllipse Radius&, Radius# End Sub

5.

n the bject combo bo*, select cmdCubeCalculate and implement its #lic' event as follows,
Private Dim Dim Dim Sub cmdCubeCalculate1Clic5() dblSide As Double dblArea As Double dbl.olume As Double

dblSide t*tCubeSide dblArea CubeArea(dblSide) dbl.olume Cube.olume(dblSide) t*tCubeArea dblArea t*tCube.olume dbl.olume End Sub

6.

n the bject combo bo*, select cmdBoxCalculate and implement its #lic' event as follows,
Private Dim Dim Dim Dim dLen d2gt d3dt Area .ol Sub cmd/o*Calculate1Clic5() dLen As Double d2gt As Double d3dt As Double Area, .ol As Double t*t/o*Lengt0 t*t/o*2eig0t t*t/o*3idt0 /o*Area(dLen, d2gt, d3dt) /o*.olume(dLen, d2gt, d3dt)

t*t/o*Area Area t*t/o*.olume .ol End Sub

7. #lose the #ode $ditor or Microsoft !isual "asic and return to Microsoft Access 8. 4witch the form to -orm !iew and test the ellipse in the #ircular tab 9. Also test the cube and the bo* in the 6:;imensions tab

<. 4ave and close the form =. #lose Microsoft Access Techni&ues of Passing Arguments ptional Arguments If you create a procedure that ta'es an argument, whenever you call that procedure, you must provide a value for that argument. If you fail to provide a value for the argument, when the application runs, you would receive an error. Imagine you create a function that will be used to calculate the final price of an item after discount. The function would need the discount rate in order to perform the calculation. 4uch a function may loo' li'e this,
,unction Calculate6etPrice(DiscountRate As Double) As Currency Dim 7rigPrice As Double

7rigPrice CCur(t*t8ar5edPrice) Calculate6etPrice 7rigPrice 9 CLng(7rigPrice " DiscountRate " &::) ; &:: End ,unction

4ince this function e*pects an argument, if you don%t supply it, the following program would not compile,

,unction Calculate6etPrice(DiscountRate As Double) As Currency Dim 7rigPrice As Double 7rigPrice CCur(t*t8ar5edPrice) Calculate6etPrice 7rigPrice 9 CLng(7rigPrice " DiscountRate " &::) ; &:: End ,unction Private Sub cmdCalculate1Clic5() Dim dblDiscount< dblDiscount t*t6etPrice End Sub CDbl(t*tDiscountRate) Calculate6etPrice(dblDiscount)

If a procedure such as this #alculate>etPrice./ function uses the same discount rate over and over again, instead of supplying an argument all the time, you can provide a default value for the argument. If you do this, you would not need to provide a value for the argument when you call the procedure. 4uch an argument is referred to as optional. To ma'e an argument optional, in the parentheses of its procedure, start it with the Optional 'eyword. n the right side of the data type of the argument, type the assignment operator, followed by the desired default value that would be used for the argument if fail to provide one or decide not to provide one. "ased on this, the above #alculate>etPrice./ function could be defined as,
,unction Calculate6etPrice(7ptional DiscountRate As Double Currency Dim 7rigPrice As Double :%#) As

7rigPrice CCur(t*t8ar5edPrice) Calculate6etPrice 7rigPrice 9 CLng(7rigPrice " DiscountRate " &::) ; &:: End ,unction Private Sub cmdCalculate1Clic5() t*t6etPrice Calculate6etPrice() End Sub

>otice that, this time, you don%t have to provide a value for the argument when calling the function, if you omit the value of the argument, the default value would be used. At another time, when calling the function, if you want to use a value that is different from the default value, you should ma'e sure you provide the desired value. #onsider the following call,
,unction Calculate6etPrice(7ptional DiscountRate As Double Currency Dim 7rigPrice As Double :%#) As

7rigPrice CCur(t*t8ar5edPrice) Calculate6etPrice 7rigPrice 9 CLng(7rigPrice " DiscountRate " &::) ; &:: End ,unction Private Sub cmdCalculate1Clic5() Dim dblDiscount< dblDiscount t*t6etPrice End Sub CDbl(t*tDiscountRate) Calculate6etPrice(dblDiscount)

Instead of one, you can also create a procedure with more than one argument as we saw earlier. (ou may want all, one, or more than one of these arguments to be optional. To do this, declare each optional argument with the ptional 'eyword and assign it the desired value. #onsider the following e*ample where two arguments are optional,
,unction Calculate6etPrice(7rigPrice As Currency, 1 7ptional =a*Rate As Double :%:(>(, 1 7ptional DiscountRate As Double :%#() As Currency Dim curDiscount.alue As Currency Dim curPriceA+terDiscount As Currency Dim cur=a*.alue As Currency Dim cur6etPrice As Currency curDiscount.alue CLng(7rigPrice " DiscountRate " &::) ; &::

curPriceA+terDiscount 7rigPrice 9 curDiscount.alue cur=a*.alue CLng(curPriceA+terDiscount " =a*Rate " &::) ; &:: t*tDiscount.alue CStr(curDiscount.alue) t*tPriceA+terDiscount CStr(curPriceA+terDiscount) t*t=a*.alue CStr(cur=a*.alue) Calculate6etPrice curPriceA+terDiscount ! cur=a*.alue End ,unction Private Dim Dim Dim Sub cmdCalculate1Clic5() cur8ar5edPrice As Currency dblDiscountRate< dbl=a*Rate<

cur8ar5edPrice CCur(t*t8ar5edPrice) dblDiscountRate CDbl(t*tDiscountRate) dbl=a*Rate CDbl(t*t=a*Rate) t*t6etPrice Calculate6etPrice(t*t8ar5edPrice, t*t=a*Rate, dblDiscountRate) End Sub

If you create a procedure that ta'es more than one argument, when calling the procedure, ma'e sure you 'now what argument is optional and which one is re&uired. When calling a procedure that has more than one argument but only one argument is optional, you can provide a value for the re&uired argument and omit the others. 0ere is an e*ample,
,unction Calculate6etPrice(7rigPrice As Currency, 1 7ptional =a*Rate As Double :%:(>(, 1 7ptional DiscountRate As Double :%#() As Currency Dim curDiscount.alue As Currency Dim curPriceA+terDiscount As Currency Dim cur=a*.alue As Currency Dim cur6etPrice As Currency curDiscount.alue CLng(7rigPrice " DiscountRate " &::) ; &:: curPriceA+terDiscount 7rigPrice 9 curDiscount.alue cur=a*.alue CLng(curPriceA+terDiscount " =a*Rate " &::) ; &:: t*tDiscount.alue CStr(curDiscount.alue) t*tPriceA+terDiscount CStr(curPriceA+terDiscount) t*t=a*.alue CStr(cur=a*.alue)

Calculate6etPrice End ,unction

curPriceA+terDiscount ! cur=a*.alue

Private Sub cmdCalculate1Clic5() Dim cur8ar5edPrice As Currency cur8ar5edPrice CCur(t*t8ar5edPrice) t*t6etPrice Calculate6etPrice(t*t8ar5edPrice) End Sub

In reality, the Microsoft !isual "asic language allows you to create the procedure with the list of arguments as you see fit, as long as you ma'e sure you clearly specify which argument is optional and which one is re&uired. If you create a procedure that has more than one argument and at least one argument with a default value, if the optional argument is positioned to the left of a re&uired argument, when calling the procedure, if you don%t want to provide a value for the optional argument, enter a comma in its placeholder to indicate that there would have been a value for the argument but you prefer to use the default value. ?emember that you must provide a value for any re&uired argument. #onsider the following e*ample,
,unction Calculate6etPrice(7rigPrice As Currency, 1 7ptional =a*Rate As Double :%:(>(, 1 7ptional DiscountRate As Double :%#() As Currency Dim curDiscount.alue As Currency Dim curPriceA+terDiscount As Currency Dim cur=a*.alue As Currency Dim cur6etPrice As Currency curDiscount.alue CLng(7rigPrice " DiscountRate " &::) ; &:: curPriceA+terDiscount 7rigPrice 9 curDiscount.alue cur=a*.alue CLng(curPriceA+terDiscount " =a*Rate " &::) ; &:: t*tDiscount.alue CStr(curDiscount.alue) t*tPriceA+terDiscount CStr(curPriceA+terDiscount) t*t=a*.alue CStr(cur=a*.alue) Calculate6etPrice curPriceA+terDiscount ! cur=a*.alue End ,unction Private Sub cmdCalculate1Clic5() Dim cur8ar5edPrice As Currency Dim dblDiscountRate<

Dim dbl=a*Rate< cur8ar5edPrice CCur(t*t8ar5edPrice) dblDiscountRate CDbl(t*tDiscountRate) t*t6etPrice Calculate6etPrice(cur8ar5edPrice, , dblDiscountRate) End Sub

Practical 2earning, @sing ;efault Arguments 3. In the -orms section of the ;atabase window, double:clic' the ItemPrice form to open it 5. After viewing it, switch it to ;esign !iew 6. n the form, clic' the #alculate button 7. In the Properties window, clic' $vents and double:clic' the n #lic' field 8. #hange the file as follows,
,unction Calculate6etPrice(7rigPrice As Currency, 1 7ptional =a*Rate As Double :%:(>(, 1 7ptional DiscountRate As Double :%#() As Currency Dim curDiscount.alue As Currency Dim curPriceA+terDiscount As Currency Dim cur=a*.alue As Currency Dim cur6etPrice As Currency curDiscount.alue CLng(7rigPrice " DiscountRate " &::) ; &:: curPriceA+terDiscount 7rigPrice 9 curDiscount.alue cur=a*.alue CLng(curPriceA+terDiscount " =a*Rate " &::) ; &:: t*tDiscount.alue CStr(curDiscount.alue) t*tPriceA+terDiscount CStr(curPriceA+terDiscount) t*t=a*.alue CStr(cur=a*.alue) Calculate6etPrice curPriceA+terDiscount ! cur=a*.alue End ,unction Private Dim Dim Dim Sub cmdCalculate1Clic5() cur8ar5edPrice As Currency dblDiscountRate< dbl=a*Rate<

cur8ar5edPrice CCur(6?(t*t8ar5edPrice)) dblDiscountRate CDbl(6?(t*tDiscountRate)) dbl=a*Rate CDbl(6?((t*t=a*Rate)) t*t6etPrice Calculate6etPrice(cur8ar5edPrice, dbl=a*Rate, dblDiscountRate) End Sub

9. <. =. A.

?eturn to Microsoft Access and switch the form to -orm !iew Test it #lose the form When as'ed whether you want to save it, clic' (es

?andom #all of Arguments When you call a procedure that ta'es more than one argument, you must pass the arguments in the right order. #onsider the following function,
,unction ResumeEmployee@(salary As Currency, name As String, d2ired As Date) Dim strResult@ strResult name A B, B A CStr(d2ired) A B, B A CStr(salary) ResumeEmployee strResult End ,unction

When calling this function, you must pass the first argument as a currency value, the second as a string, and the third as a date value. If you pass a value in the wrong position, the compiler would throw an error and the program would not wor'. This is what would happen if you call it as follows,
Private Dim Dim Dim Dim Sub cmdResume1Clic5() str,ull6ame As String dte2ired As Date cur2ourlySalary As Currency strResume@

str,ull6ame Ct*t,ull6ameD dte2ired CDate(Ct*tDate2iredD) cur2ourlySalary CCur(t*t2ourlySalary) strResume ResumeEmployee(str,ull6ame, dte2ired, cur2ourlySalary) t*tResume strResume End Sub

While you must respect this rule, Microsoft !isual "asic provides an alternative. (ou don%t have to pass the arguments in their strict order. Instead, you can assign the desired value to each argument as long as you 'now their names. To do this, when calling the function, to assign the desired value to an argument, on the right side of the sub procedure or in the parentheses of the function, type the name of the argument, followed by the ,B operator, followed by the .appropriate/ value. Practical 2earning, ?andomly Passing Arguments 3. -rom the -orms section of the ;atabase window, open the Employees Records1 form 5. After view the form in -orm !iew, on the main menu, clic' !iew :C ;esign !iew 6. n the form, clic' the ?esume button 7. In the Properties window, clic' $vents and double:clic' the n #lic' field 8. #hange the file as follows,
,unction ResumeEmployee@(salary As Currency, name As String, d2ired As Date)

Dim strResult@ strResult name A B, B A CStr(d2ired) A B, B A CStr(salary) ResumeEmployee strResult End ,unction Private Dim Dim Dim Dim Sub cmdResume1Clic5() str,ull6ame As String dte2ired As Date cur2ourlySalary As Currency strResume@

str,ull6ame Ct*t,ull6ameD dte2ired CDate(Ct*tDate2iredD) cur2ourlySalary CCur(t*t2ourlySalary) strResume ResumeEmployee(nameE str,ull6ame, d2iredE dte2ired, 1 salaryE cur2ourlySalary) t*tResume strResume End Sub

9. ?eturn to Microsoft Access and switch the form to -orm !iew <. Test it

=. #lose the form A. When as'ed whether you want to save it, clic' (es Passing Arguments "y !alue 4o far, when creating a procedure with one or more arguments, we simply assumed that, when calling the procedure, we would provide the desired value.s/ for the argument.s/. With this techni&ue, the procedure receives the value of the argument and does what it wants with it. The argument itself is not changed. This techni&ue is referred to as passing an argument by value. To reinforce this, you can type the "y!al 'eyword on the left side of the argument. 0ere is an e*ample,
,unction Calculate=riangleArea<(/y.al /ase As Double, /y.al 2eig0t As Double) Calculate=riangleArea /ase " 2eig0t ; # End ,unction

Practical 2earning, Passing Arguments "y !alue 3. pen the rian!le form in ;esign !iew 5. n the form, clic' the #alculate button 6. In the Properties window, clic' $vents and double:clic' the n #lic' field 7. #hange the file as follows,

,unction Calculate=riangleArea<(/y.al /ase As Double, /y.al 2eig0t As Double) Calculate=riangleArea /ase " 2eig0t ; # End ,unction Private Sub cmdCalculate1Clic5() Dim dbl/ase< Dim dbl2eig0t< dbl/ase CDbl(Ct*t/aseD) dbl2eig0t CDbl(Ct*t2eig0tD) t*tArea End Sub Calculate=riangleArea(dbl/ase, dbl2eig0t)

8. ?eturn to Microsoft Access and switch the form to -orm !iew 9. Test it

<. 4witch the form bac' to ;esign !iew Passing Arguments "y ?eference We also saw that the main difference between a sub procedure and a function is that a function can return a value but a sub procedure cannot. Microsoft !isual "asic, li'e many other languages, provides an alternative to this. >ot only can a sub procedure return a value but also it ma'es it possible for a procedure .whether a sub or a function/ to return more than one value, a feature that even a regular function doesn%t have. When creating a procedure with an argument, we saw that, by default, the procedure could not modify the value of the argument. If you want to procedure to be able to alter the argument, you can pass the argument by reference. To do this, type the ByRe" 'eyword on the left side of the name of the argument. If you create a procedure that ta'es more than one argument, you can decide which one.s/ would be passed by value and which one.s/ would be passed by reference. There is no order that the arguments must follow.

Practical 2earning, Passing Arguments "y ?eference 3. ?eturn to Microsoft !isual "asic and change the file as follows,

Sub Calculate=riangleArea(/yRe+ Area As Double, 1 /y.al /ase As Double, 1 /y.al 2eig0t As Double) Area /ase " 2eig0t ; # End Sub Private Dim Dim Dim Sub cmdCalculate1Clic5() dbl/ase< dbl2eig0t< dblArea<

dbl/ase CDbl(Ct*t/aseD) dbl2eig0t CDbl(Ct*t2eig0tD) Calculate=riangleArea dblArea, dbl/ase, dbl2eig0t t*tArea dblArea End Sub

5. ?eturn to Microsoft Access and switch the form to -orm !iew 6. Test the form with different values than previously

7. #lose the form 8. When as'ed whether you want to save it, clic' (es Programmer:;efined ;ata Types Introduction The built:in data types we have used so far allow you to declare a variable of a specific 'nown type. Alternatively, you can create a new data type by using one of the above or by combining some them to get a new one. To do this, you must create a new module for the new type. (ou start the new type with the ype 'eyword followed by the name of the new type. The create of the type ends with the End ype e*pression,
=ype SampleType End =ype

"etween the Type line and the $nd Type line, you can declare one or more e*isting types as variables. That is, each declaration can be made of a name for a variable, followed by As, and followed by a

'nown data type. 0ere is an e*ample,


=ype Sp0ere Radius As Double Diameter As Double Area As Double End =ype

@sing a Programmer:;efined ;ata Type After creating the type, in the procedure or event where you want to use it, declare a variable based on it. To access any of the member variables of the type, enter the name of its variable, followed by a period operator, and followed by the name of the member variable. After accessing a member variable of a type, you can initiali)e, change its value, or assign it to another variable. Practical 2earning, @sing a #ustom Type 3. n the ;atabase window of Microsoft Access, clic' the Modules button 5. To create a new module, clic' the >ew button on the toolbar of the ;atabase window 6. @nder the ption $*plicit line, type the following,
=ype Employee Date2ired As Date ,ull6ame As String Fs8arried As /oolean 2ourlySalary As Double End =ype

7. 8. 9. <. =.

To save the module, on the 4tandard toolbar, clic' the 4ave button 4et the name to mod?outines and clic' D ?eturn to Microsoft Access and open the $mployee form in ;esign !iew ?ight:clic' the #reate button and clic' "uild $vent... ;ouble:clic' #ode "uilder and change the event as follows,
Private Sub cmdCreate1Clic5() Dim Contractor As Employee Contractor%Date2ired <&#;';#:::< Contractor%,ull6ame BLeslie AbramsonB Contractor%Fs8arried =rue Contractor%2ourlySalary #:%&( t*tDate2ired CStr(Contractor%Date2ired) t*t,ull6ame Contractor%,ull6ame c05Fs8arried%.alue Contractor%Fs8arried t*t2ourlySalary Contractor%2ourlySalary End Sub

A. #lose Microsoft !isual "asic 3E. 4witch the form to -orm !iew and clic' the #reate button

33. #lose the form. When as'ed whether you want to save, clic' (es 35. #lose Microsoft Access

Anda mungkin juga menyukai