You are on page 1of 11

PROCEDURES: A procedure is a block of code that performs some operation.

The events we have been using so far are a special form of procedure known as an event procedure. For example, associating code with a CommandButton to quit an application is a procedure. The basic Syntax for a procedure is: [Private | Public][Static] Sub procName ([arglist]) Parts of the Procedure Part Public Description Indicates that the procedure is available to all modules. If Option Private is used in the module, the procedure is not available to modules outside of the project. Indicates that the procedure is only available to other procedures or functions in the current module or form. Indicates that all variables declared within the procedure are retained, even when the procedure is out of scope. The name of the procedure. Must be unique to the module if declared Private, otherwise unique to the project. The name of the procedure follows the naming rule for Variables. A list of variables passed to the procedure as arguments, and their data types. Multiple arguments are separated by commas. Arguments may be Optional, and may be Read Only.

Private Static

procName

arglist

The following example is a Private Procedure to print the sum of two numbers on the Form. Private Sub printSum(ByVal x As Integer, ByVal y As Integer) Debug.Print Str(x + y) End Sub OPTIONAL ARGUMENTS: If an argument has the Optional keyword in front of it, then that argument does not have to be provided to the procedure. MsgBox is an example of a procedure that takes optional arguments. If an argument is omitted, the comma must still be used as a placeholder. The following calls the MsgBox procedure, but omits the second parameter which describes the dialog box. MsgBox "Hello", , "Greeting" The following example is a procedure that uses optional arguments to specify a recipient and a sender.
19

"Gez" greeting "Hello. but this is changed in VB. Private Sub changeWhereCalled(ByRef num As Integer) num = num + 1 Debug.Print "To " & strRecipient & ". except it returns a value to the calling code. Private Sub noChangeWhereCalled(ByVal num As Integer) num = num + 1 Debug. This example is a procedure that alters a variable. End If Debug. The basic 20 . and any changes made within the procedure to the variable will not be reflected to where the procedure was called as it's only a copy. "Computer". Optional strRecipient As String. but does not change the value where it was called. how are you" greeting "Hello.Print strSender & " sends the message ". how are you?".Print Str(num) End Sub This example is a procedure that alters a variable. End If If strSender <> "" Then Debug. "Gez" READ ONLY ARGUMENTS The optional parts ByRef and ByVal are used to determine whether an argument is a copy of the variable. . Optional strSender As String) If strRecipient <> "" Then Debug. ByVal indicates the variable was passed by value. ". The actual variable from where it was called will be changed.Print strMessage End Sub The greeting procedure may be called with any of the following: greeting "Hello. "Computer" greeting "Hello.Print Str(num)End Sub FUNCTIONS A function is similar to a procedure. how are you?". ByRef is the default in Visual Basic 6. or the actual variable.Private Sub greeting(strMessage As String.Net. and any changes made within the procedure to the variable will be reflected to where the procedure was called. how are you?". ByRef indicates the variable is passed by reference.

Syntax for a function is: [Private | Public][Static] Function funcName ([arglist]) As Data Type ' Procedure body here [funcName = expression] End Function The following example uses the functions "getFormattedDate". "getWeekName" and "getAdornment" to illustrate the use of functions in Visual Basic. Private Function getFormattedDate(ByVal dateValue As Date) As String Dim strDate As String strDate = getWeekName(DatePart("w". dateValue)) strDate = strDate & Format(dateValue. dateValue)) strDate = strDate & DatePart("d". dateValue) strDate = strDate & getAdornment(DatePart("d". "mmmm yyyy") getFormattedDate = strDate End Function Private Function getWeekName(ByVal day As Integer) As String Select Case day Case 1 getWeekName = "Sunday " Case 2 getWeekName = "Monday " Case 3 getWeekName = "Tuesday " Case 4 getWeekName = "Wednesday " Case 5 getWeekName = "Thursday " Case 6 getWeekName = "Friday " Case 7 getWeekName = "Saturday " End Select End Function Private Function getAdornment(ByVal day As Integer) As String Select Case day Case 1 21 .

The module only has one property. so terminate recursion. A factorial is a number multiplied by every other integer below itself.e. i. implement recursion If Num = 1 Then Factorial = 1 Else Factorial = Num * Factorial(Num . down to 1. and so on. For example. Private Function factorial(ByVal Num As Double) As Double ' The factorial of 1 is 1. factorial 5 = 5 * factorial 4. either select "Add Module" from the Project menu. To add a new module into the current project. the factorial of the number 6 is: Factorial 6 = 6 * 5 * 4 * 3 * 2 * 1 Therefore the factorial of 6 is 720. as the factorial of 1 is 1. The following is the general rule for calculating factorial numbers. or right-click the Project in the Project Explorer and select "Add". Similarly. It can be seen from the above example that factorial 6 = 6 * factorial 5. the stack has ran out of space to place any more data. factorial(n) = n * factorial(n-1) The above rule terminates when n = 1. Name. modMathRoutines). then "Module".1) End If 22 . The three-letter mnemonic for a Module name is "mod" (eg. The following example calculates the Factorial of a number using recursion. ' otherwise. RECURSION Procedures and functions may be recursive (may call itself).getAdornment = "st " Case 2 getAdornment = "nd " Case 3 getAdornment = "rd " Case Else getAdornment = "th " End Select End Function MODULES Modules contain procedures or functions that may be called anywhere within the project if they're declared as Public. Each call to itself requires that the current state of the procedure is pushed onto the stack. This is important to remember as it's easy to create a stack overflow.

Public Sub Main() Dim strName As String strName = InputBox("Enter your name". To try this example. The procedure should be written in a module.End Function Sub Main Sub Main is a special procedure that may be used by Visual Basic to launch an application. Change it to the name of the Form you want to start. the date portion of dtmTest is 8/31/2001. "Name") frmStart. 2001 at 9:15:20 PM. August 31. add a Module to your project and change the Startup Object in Project Properties to Sub Main. with the time portion "zeroed out". The Sub Main procedure should be selected as the "Startup Object" in the "Project Properties" from the "Project" menu. with a time portion of 0 (12:00 AM midnight). TimeValue Returns the time portion of a Date/Time value. the time would be interpreted as 12:00 AM. (Note: When the time portion of a date/time variable is "zeroed out". The procedure may not be declared using the keyword Private. The following functions isolate the date portion and time portion.Show End Sub Date Time Functions In Visual Basic Now Returns the current date and time together Date Returns the current date Time Returns the current time For the examples that follow. assume that the current Date/Time (Now) is Friday. respectively. This example uses a form called frmStart. The name is then added to the caption of the Form. with the date portion "zeroed 23 .) Example: Dim dtmTest As Date dtmTest = DateValue(Now) At this point.Caption = "Hello " & strName frmStart. of a Date/Time value: Function DateValue Description Returns the date portion of a Date/Time value. This example uses Sub Main in a Module to prompt for a name.

second argument (Boolean) indicating whether or not to abbreviate the weekday name. 1899.out".) Example: Dim dtmTest As Date dtmTest = TimeValue(Now) At this point. the time portion of dtmTest is 9:15:20 PM. meaning do not abbreviate and return the full name. Example: strDOW = WeekdayName(6) ' strDOW = "Friday" The WeekdayName function takes an optional. with a date portion of 0 (12/30/1899). where 1 is Sunday and 7 is Saturday. the first three letters of the weekday name will be returned: Example: strDOW = WeekdayName(6. given a numeric argument with the value 1 through 7. Example: intMonth = Month(Now) ' intMonth = 8 MonthName Returns a string containing the month name ("January" thru "December"). Example: strMoName = MonthName(8) ' strMoName = "August" 24 . If True. (Note: When a date/time variable is "zeroed out". the date will actually be interpreted as December 30. given a numeric argument with the value 1 through 12. Example: intDOW = Weekday(Now) ' intDOW = 6 WeekdayName Returns a string containing the weekday name ("Sunday" thru "Saturday"). True) ' strDOW = "Fri" Month Returns a number from 1 to 12 indicating the month portion of a given date. By default. the second argument is False. The following functions are used to isolate a particular part of a date: Function Weekday Description Returns a number from 1 to 7 indicating the day of the week for a given date.

The MonthName function takes an optional. If True. the first three letters of the month name will be returned: Example: strMoName = MonthName(8. Thus. By default. 25 . meaning do not abbreviate and return the full name. the second argument is False. Month. second argument (Boolean) indicating whether or not to abbreviate the month name. Example: intMinute = Minute(Now) ' intMinute = 15 Second Returns an integer specifying a whole number between 0 and 59 representing the second of the minute. Day. Example: intSecond = Second(Now) ' intSecond = 20 The DatePart Function The generic DatePart function returns an Integer containing the specified part of a given date/time value. Example: intYear = Year(Now) ' intYear = 2001 The following functions are used to isolate a particular part of a time: Function Description Returns an integer specifying a whole number between 0 and 23 representing the hour of the day. Example: intDay = Day(Now) ' intDay = 31 Year Returns a number from 100 to 9999 indicating the year portion of a given date. Example: intHour = Hour(Now) ' intHour = 21 (for 9 PM) Minute Returns an integer specifying a whole number between 0 and 59 representing the minute of the hour. it incorporates the functionality of the Weekday. True) ' strMoName = "Aug" Day Returns a number from 1 to 31 indicating the day portion of a given date.

and the week number (1 through 53). String expression that is the interval of time you want to return. the first week is assumed to be the week in which January 1 occurs. Piecing Separate Numbers Together to Form a Date or Time Value In the previous examples. the "Julian" date (the day of the year from 1 to 366). Syntax: DatePart(interval. we saw ways to isolate parts of a date/time value. The string expression can be any of the following: Expression "yyyy" "q" "m" "y" "d" "w" "ww" Description Year Quarter Month Day of year Day Weekday Week Possible Range of Values 100 to 9999 1 to 4 1 to 12 1 to 366 (a "Julian" date) 1 to 31 1 to 7 1 to 53 "h" "n" "s" Date firstdayofweek Hour Minute Second 0 to 23 0 to 59 0 to 59 Required.firstdayofweek[.Year. firstweekofyear Optional. In addition. Minute. firstweekofyear]]) The DatePart function syntax has these parts: Part Interval Description Required. Date value that you want to evaluate. What if you need to go the "other way"? If you have the separate parts of a date/time value in 26 . A constant that specifies the first day of the week. and Second functions. A constant that specifies the first week of the year. If not specified. it can used to get the quarter of a given date (1 through 4) . If not specified. Optional. Sunday is assumed. Hour. date[.

Example: Dim intYear As Integer Dim intMonth As Integer Dim intDay As Integer Dim dtmNewDate As Date intYear = 2001 intMonth = 9 intDay = 2 dtmNewDate = DateSerial(intYear. intMonth.different variables and want to piece them together to formulate a date or time. minute. Example: Dim intHour As Integer Dim intMinute As Integer Dim intSecond As Integer Dim dtmNewTime As Date intHour = 11 intMinute = 34 intSecond = 44 dtmNewTime = TimeSerial(intHour. and second respectively. intSecond) 'returns 11:34:44 (AM) A function is similar to a normal procedure but the main purpose of the function is to accept a certain input from the user and return a value which is passed on to the main program to finish the execution. It returns a time based on those values. 27 . and day respectively. It returns a date based on those values. there are two functions you can use to do this:DateSerial and TimeSerial. intDay) ' returns 9/2/2001 The TimeSerial takes three numeric arguments: hour. month. the built-in functions (or internal functions) and the functions created by the programmers. The DateSerial takes three numeric arguments: year. intMinute. There are two types of functions.

Title. The format is myMessage=InputBox(Prompt.1 for types of command button displayed. Style Value 0 1 2 3 4 5 Table 10. This format is as follows: yourMsg=MsgBox(Prompt. "Startup Menu") The InputBox( ) Function An InputBox( ) function will display a message box where the user can enter a value or a message in the form of text. which accept the message input by the users. default-text .1: Style Values Named Constant Buttons Displayed vbOkOnly vbOkCancel vbAbortRetryIgnore vbYesNoCancel vbYesNo vbRetryCancel Ok button Ok and Cancel buttons Abort. 28 . Yes.The message displayed normally as a question asked. please refer Table 10. will display the message in the message box.The default text that appears in the input field where users can use it as his intended input or he may change to the message he wish to key in. Style Value.The title of the Input Box. x-position. No and Cancel buttons Yes and No buttons Retry and Cancel buttons Example: yourMsg=MsgBox( "Click OK to Proceed". The Title argument will display the title of the message board. default_text. Retry and Ignore buttons.The general format of a function is FunctionName (arguments) The arguments are values that are passed on to the function. The Style Value will determine what type of command buttons appear on the message box. Title) The first argument. Title . MsgBox ( ) Function The objective of MsgBox is to produce a pop-up message box and prompt the user to click on a command button before he /she can continues. Prompt. The arguments are explained as follows:    Prompt . y-position) myMessage is a variant data type but typically it is declared as string. 1.

29 . x-position and y-position .the position or the coordinate of the input box.

The default text that appears in the input field where users can use it as his intended input or he may change to the message he wish to key in. x-position and y-position . 12 .• • default-text .the position or the coordinate of the input box.