If you create a procedure that takes 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. Such a function would look like this: Function CalculateNetPrice(DiscountRate As Double) As Currency Dim OrigPrice As Double OrigPrice = CCur(txtMarkedPrice) CalculateNetPrice = OrigPrice - CLng(OrigPrice * DiscountRate * 100) / 100 End Function Since this function expects an argument, if you don't supply it, the following program would not compile:
Function CalculateNetPrice(DiscountRate As Double) As Currency Dim OrigPrice As Double OrigPrice = CCur(txtMarkedPrice) CalculateNetPrice = OrigPrice - CLng(OrigPrice * DiscountRate * 100) / 100 End Function Private Sub cmdCalculate_Click() Dim dblDiscount# dblDiscount = CDbl(txtDiscountRate) txtPriceAfterDiscount = CalculateNetPrice(dblDiscount) End Sub
If a procedure such as this CalculateNetPrice() 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. Such an argument is referred to as optional. To make an argument optional, in the parentheses of its procedure, start it with the Optional keyword. On 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 you fail to provide one or decide not to provide one. Based on this, the above CalculateNetPrice() function could be defined as: Function CalculateNetPrice(Optional DiscountRate As Double = 0.2) As Currency Dim OrigPrice As Double OrigPrice = CCur(txtMarkedPrice) CalculateNetPrice = OrigPrice - CLng(OrigPrice * DiscountRate * 100) / 100 End Function Private Sub cmdCalculate_Click() txtPriceAfterDiscount = CalculateNetPrice() End Sub
Notice 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 make sure you provide the desired value. Consider the following call: Function CalculateNetPrice(Optional DiscountRate As Double = 0.2) As Currency Dim OrigPrice As Double OrigPrice = CCur(txtMarkedPrice) CalculateNetPrice = OrigPrice - CLng(OrigPrice * DiscountRate * 100) / 100 End Function Private Sub cmdCalculate_Click() Dim dblDiscount# dblDiscount = CDbl(txtDiscountRate) txtPriceAfterDiscount = CalculateNetPrice(dblDiscount) End Sub
Instead of one, you can also create a procedure with more than one argument. You may want all, one, or more than one of these arguments to be optional. To do this, declare each optional argument with the Optional keyword and assign it the desired value. Consider the following example where two arguments are optional: Function CalculateNetPrice(OrigPrice As Currency, _ Optional TaxRate As Double = 0.0575, _ Optional DiscountRate As Double = 0.25) As Currency Dim curDiscountValue As Currency Dim curPriceAfterDiscount As Currency Dim curTaxValue As Currency Dim curNetPrice As Currency curDiscountValue = CLng(OrigPrice * DiscountRate * 100) / 100 curPriceAfterDiscount = OrigPrice - curDiscountValue curTaxValue = CLng(curPriceAfterDiscount * TaxRate * 100) / 100 txtDiscountValue = CStr(curDiscountValue) txtPriceAfterDiscount = CStr(curPriceAfterDiscount) txtTaxValue = CStr(curTaxValue) CalculateNetPrice = curPriceAfterDiscount + curTaxValue End Function Private Sub cmdCalculate_Click() Dim curMarkedPrice As Currency Dim dblDiscountRate# Dim dblTaxRate# curMarkedPrice = CCur(txtMarkedPrice) dblDiscountRate = CDbl(txtDiscountRate) dblTaxRate = CDbl(txtTaxRate) txtNetPrice = CalculateNetPrice(txtMarkedPrice, txtTaxRate, dblDiscountRate) End Sub
If you create a procedure that takes more than one argument, when calling the procedure, make sure you know what argument is optional and which one is required. When calling a procedure that has more than one argument but only one argument is optional, you can provide a value for the required argument and omit the others. Here is an example: Function CalculateNetPrice(OrigPrice As Currency, _ Optional TaxRate As Double = 0.0575, _ Optional DiscountRate As Double = 0.25) As Currency Dim curDiscountValue As Currency Dim curPriceAfterDiscount As Currency Dim curTaxValue As Currency Dim curNetPrice As Currency curDiscountValue = CLng(OrigPrice * DiscountRate * 100) / 100 curPriceAfterDiscount = OrigPrice - curDiscountValue curTaxValue = CLng(curPriceAfterDiscount * TaxRate * 100) / 100 txtDiscountValue = CStr(curDiscountValue) txtPriceAfterDiscount = CStr(curPriceAfterDiscount) txtTaxValue = CStr(curTaxValue) CalculateNetPrice = curPriceAfterDiscount + curTaxValue End Function Private Sub cmdCalculate_Click() Dim curMarkedPrice As Currency curMarkedPrice = CCur(txtMarkedPrice) txtNetPrice = CalculateNetPrice(txtMarkedPrice) End Sub
In reality, the Microsoft Visual Basic language allows you to create the procedure with the list of arguments as you see fit, as long as you make sure you clearly specify which argument is optional and which one is required. 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 required 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. Remember that you must provide a value for any required argument. Consider the following example: Function CalculateNetPrice(OrigPrice As Currency, _ Optional TaxRate As Double = 0.0575, _ Optional DiscountRate As Double = 0.25) As Currency Dim curDiscountValue As Currency Dim curPriceAfterDiscount As Currency Dim curTaxValue As Currency Dim curNetPrice As Currency curDiscountValue = CLng(OrigPrice * DiscountRate * 100) / 100 curPriceAfterDiscount = OrigPrice - curDiscountValue curTaxValue = CLng(curPriceAfterDiscount * TaxRate * 100) / 100 txtDiscountValue = CStr(curDiscountValue) txtPriceAfterDiscount = CStr(curPriceAfterDiscount) txtTaxValue = CStr(curTaxValue) CalculateNetPrice = curPriceAfterDiscount + curTaxValue End Function Private Sub cmdCalculate_Click() Dim curMarkedPrice As Currency Dim dblDiscountRate# Dim dblTaxRate# curMarkedPrice = CCur(txtMarkedPrice) dblDiscountRate = CDbl(txtDiscountRate) txtNetPrice = CalculateNetPrice(curMarkedPrice, , dblDiscountRate) End Sub
When you call a procedure that takes more than one argument, you must pass the arguments in the right order. Consider the following function: Function ResumeEmployee$(salary As Currency, name As String, dHired As Date) Dim strResult$ strResult = name & ", " & CStr(dHired) & ", " & CStr(salary) ResumeEmployee = strResult End Function 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 work. This is what would happen if you call it as follows: Private Sub cmdResume_Click() Dim strFullName As String Dim dteHired As Date Dim curHourlySalary As Currency Dim strResume$ strFullName = [txtFullName] dteHired = CDate([txtDateHired]) curHourlySalary = CCur(txtHourlySalary) strResume = ResumeEmployee(strFullName, dteHired, curHourlySalary) txtResume = strResume End Sub While you must respect this rule, Microsoft Visual Basic provides an alternative. You 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 know 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 := operator, followed by the (appropriate) value.
So 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 technique, the procedure receives the value of the argument and does what it wants with it. The argument itself is not changed. This technique is referred to as passing an argument by value. To reinforce this, you can type the ByVal keyword on the left side of the argument. Here is an example: Function CalculateTriangleArea#(ByVal Base As Double, ByVal Height As Double) CalculateTriangleArea = Base * Height / 2 End Function
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 Visual Basic, like many other languages, provides an alternative to this. Not only can a sub procedure return a value but also it makes 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 ByRef keyword on the left side of the name of the argument. If you create a procedure that takes 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.
Microsoft Access and Microsoft Visual Basic ship with various functions and procedures you can use in your database. Before creating your own procedures, you should know what is already available so you don't have to re-invent and waste a great deal of your time. The functions already created are very efficient and were tested in various scenarios so you can use them with complete reliability. The available functions range in various types. There are so many built-in functions and procedures that we can only introduce some of them here. You can find out about the others in the Help files because they are fairly documented. When studying variables, we introduced and also reviewed the conversion functions. We saw that each had a corresponding function used to convert a string value or an expression to that type. As a reminder, the general syntax of the conversion functions is: ReturnType = FunctionName(Expression) The Expression could be of any kind. For example, it could be a string or expression that would produce a value such as the result of a calculation. The conversion function would take such a value, string, or expression and attempt to convert it. If the conversion is successful, the function would return a new value that is of the type specified by the ReturnType in our syntax. The conversion functions are as follows:
These functions allow you to convert a known value to a another type.
In Lesson 3, we saw that different data types are used to store different values. To do that, each data type requires a different amount of space in the computer memory. To know the amount of space that a data type or a variable needs, you can call the Len() function. Its syntax is: Public Function Len( _ ByVal Expression As { Boolean | Byte | Double | Integer | Long | Object | Single | String | Date | Variant } _ ) As Integer To call this function, you can declare a variable with a data type of your choice and optionally initialize with the appropriate value, then pass that variable to the function. Here is an example: Public Sub Exercise() Dim Value As Integer Value = 774554 Len(Value) End Sub
If you want, you can make the computer produce a beeping a sound in response to something, anything. To support this, the Visual Basic language provides a function called Beep. Its syntax is: Public Sub Beep() Here is an example of calling it: Private Sub cmdBeep_Click() Beep End Sub If this function is called when a program is running, the computer emits a brief sound.
We will use many built-in functions in our lessons. Most of those functions will come from the Visual Basic language. Besides the libraries used in Microsoft Access, the Microsoft Windows operating system provides its own library of functions and objects. This library is called the Win32 Application Programming Interface or Win32 API, or simply Win32. The Win32 library is somehow available to applications but its functions are not directly available for a database. The Win32 library is made of procedures, functions, and classes (mostly structures) that you can use to complement a project. There are so many of these functions and objects that it is hard to know most or all of them. The best way to get acquainted with them is to check its documentation. To do this, you can visit the MSDN web site. The functions are stored in various sub-libraries called dynamic link libraries (DLLs).
Before using a Win32 function in your code, you must first have two pieces of information: the DLL in which the function was created and the actual name of the desired function in that library. Examples of DLLs are shfolder or Kernel32. Once you know the name of the library and the name of the function you want to use, you must import it in your Visual Basic code. The basic formula to follow is: Private Declare Function Win32FunctionName Lib "LibraryName" Alias "CustomName" (Arguments) As DataType The Win32FunctionName factor is the name of the function in the Win32 library. The LibraryName is the name of the library. You can create a custom name for the function as the CustomName factor. In the parentheses, you can enter the names and types of the arguments. If the procedure returns a value, you can specify its type after the As keyword. Here is an example: Option Compare Database Option Explicit Private Const MAX_PATH = 260 Private Const CSIDL_PERSONAL = &H5& Private Const SHGFP_TYPE_CURRENT = 0 ' We will use the Windows API to get the path to My Documents Private Declare Function SHGetFolderPath Lib "shfolder" _ Alias "SHGetFolderPathA" _ (ByVal hwndOwner As Long, ByVal nFolder As Long, _ ByVal hToken As Long, ByVal dwFlags As Long, _ ByVal pszPath As String) As Long Private Sub cmdCreateDatabase_Click() Dim strMyDocuments As String Dim strDbName As String Dim valReturned As Long Dim dbMVD As DAO.Database ' Initialize the string strMyDocuments = String(MAX_PATH, 0) ' Call the Shell API function to get the path to My Documents ' and store it in the strMyDocuments folder valReturned = SHGetFolderPath(0, CSIDL_PERSONAL, _ 0, SHGFP_TYPE_CURRENT, strMyDocuments) ' "Trim" the string strMyDocuments = Left(strMyDocuments, InStr(1, strMyDocuments, Chr(0)) - 1) ' Include the name of the database in the path strDbName = strMyDocuments & "\Motor Vehicle Division.mdb" ' Create the database Set dbMVD = CreateDatabase(strDbName, dbLangGeneral) End Sub
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|