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

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

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 & DatePart("d", dateValue) strDate = strDate & getAdornment(DatePart("d", dateValue)) strDate = strDate & Format(dateValue, "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

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. To add a new module into the current project, either select "Add Module" from the Project menu, or right-click the Project in the Project Explorer and select "Add", then "Module". The module only has one property, Name. The three-letter mnemonic for a Module name is "mod" (eg. modMathRoutines). RECURSION Procedures and functions may be recursive (may call itself). 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, i.e. the stack has ran out of space to place any more data. The following example calculates the Factorial of a number using recursion. A factorial is a number multiplied by every other integer below itself, down to 1. For example, the factorial of the number 6 is: Factorial 6 = 6 * 5 * 4 * 3 * 2 * 1 Therefore the factorial of 6 is 720. It can be seen from the above example that factorial 6 = 6 * factorial 5. Similarly, factorial 5 = 5 * factorial 4, and so on. The following is the general rule for calculating factorial numbers. factorial(n) = n * factorial(n-1) The above rule terminates when n = 1, as the factorial of 1 is 1. Private Function factorial(ByVal Num As Double) As Double ' The factorial of 1 is 1, so terminate recursion, ' otherwise, implement recursion If Num = 1 Then Factorial = 1 Else Factorial = Num * Factorial(Num - 1) End If
22

End Function Sub Main Sub Main is a special procedure that may be used by Visual Basic to launch an application. The procedure should be written in a module. The procedure may not be declared using the keyword Private. The Sub Main procedure should be selected as the "Startup Object" in the "Project Properties" from the "Project" menu. This example uses Sub Main in a Module to prompt for a name. The name is then added to the caption of the Form. To try this example, add a Module to your project and change the Startup Object in Project Properties to Sub Main. This example uses a form called frmStart. Change it to the name of the Form you want to start. Public Sub Main() Dim strName As String strName = InputBox("Enter your name", "Name") frmStart.Caption = "Hello " & strName frmStart.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, August 31, 2001 at 9:15:20 PM.
The following functions isolate the date portion and time portion, respectively, of a Date/Time value:

Function DateValue

Description

Returns the date portion of a Date/Time value, with the time portion "zeroed out". (Note: When the time portion of a date/time variable is "zeroed out", the time would be interpreted as 12:00 AM.) Example: Dim dtmTest As Date dtmTest = DateValue(Now) At this point, the date portion of dtmTest is 8/31/2001, with a time portion of 0 (12:00 AM midnight).

TimeValue Returns the time portion of a Date/Time value, with the date portion "zeroed 23

out". (Note: When a date/time variable is "zeroed out", the date will actually be interpreted as December 30, 1899.) Example: Dim dtmTest As Date dtmTest = TimeValue(Now) At this point, the time portion of dtmTest is 9:15:20 PM, with a date portion of 0 (12/30/1899).
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, where 1 is Sunday and 7 is Saturday. Example:
intDOW = Weekday(Now) ' intDOW = 6

WeekdayName Returns a string containing the weekday name ("Sunday" thru

"Saturday"), given a numeric argument with the value 1 through 7. Example:


strDOW = WeekdayName(6) ' strDOW = "Friday"

The WeekdayName function takes an optional, second argument (Boolean) indicating whether or not to abbreviate the weekday name. By default, the second argument is False, meaning do not abbreviate and return the full name. If True, the first three letters of the weekday name will be returned: Example:
strDOW = WeekdayName(6, True) ' strDOW = "Fri"

Month

Returns a number from 1 to 12 indicating the month portion of a given date. Example:
intMonth = Month(Now) ' intMonth = 8

MonthName

Returns a string containing the month name ("January" thru "December"), given a numeric argument with the value 1 through 12. Example:
strMoName = MonthName(8) ' strMoName = "August"

24

The MonthName function takes an optional, second argument (Boolean) indicating whether or not to abbreviate the month name. By default, the second argument is False, meaning do not abbreviate and return the full name. If True, the first three letters of the month name will be returned: Example:
strMoName = MonthName(8, True) ' strMoName = "Aug"

Day

Returns a number from 1 to 31 indicating the day portion of a given date. Example:
intDay = Day(Now) ' intDay = 31

Year

Returns a number from 100 to 9999 indicating the year portion of a given date. 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:
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. Example:
intMinute = Minute(Now) ' intMinute = 15

Second

Returns an integer specifying a whole number between 0 and 59 representing the second of the minute. 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. Thus, it incorporates the functionality of the Weekday, Month, Day,
25

Year, Hour, Minute, and Second functions. In addition, it can used to get the quarter of a given date (1 through 4) , the "Julian" date (the day of the year from 1 to 366), and the week number (1 through 53). Syntax: DatePart(interval, date[,firstdayofweek[, firstweekofyear]])
The DatePart function syntax has these parts: Part Interval Description

Required. String expression that is the interval of time you want to return. 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. Date value that you want to evaluate. Optional. A constant that specifies the first day of the week. If not specified, Sunday is assumed. firstweekofyear Optional. A constant that specifies the first week of the year. If not specified, 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, we saw ways to isolate parts of a date/time value. What if you need to go the "other way"? If you have the separate parts of a date/time value in

26

different variables and want to piece them together to formulate a date or time, there are two functions you can use to do this:DateSerial and TimeSerial. The DateSerial takes three numeric arguments: year, month, and day respectively. It returns a date based on those values. 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, intDay) ' returns 9/2/2001 The TimeSerial takes three numeric arguments: hour, minute, and second respectively. It returns a time based on those values. 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, intMinute, 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. There are two types of functions, the built-in functions (or internal functions) and the functions created by the programmers.

27

The general format of a function is FunctionName (arguments) The arguments are values that are passed on to the function.

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. This format is as follows: yourMsg=MsgBox(Prompt, Style Value, Title)

The first argument, Prompt, will display the message in the message box. The Style Value will determine what type of command buttons appear on the message box, please refer Table 10.1 for types of command button displayed. The Title argument will display the title of the message board.

Style Value 0 1 2 3 4 5

Table 10.1: Style Values Named Constant Buttons Displayed vbOkOnly vbOkCancel vbAbortRetryIgnore vbYesNoCancel vbYesNo vbRetryCancel Ok button Ok and Cancel buttons Abort, Retry and Ignore buttons. Yes, No and Cancel buttons Yes and No buttons Retry and Cancel buttons

Example: yourMsg=MsgBox( "Click OK to Proceed", 1, "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. The format is myMessage=InputBox(Prompt, Title, default_text, x-position, y-position) myMessage is a variant data type but typically it is declared as string, which accept the message input by the users. The arguments are explained as follows:

Prompt - The message displayed normally as a question asked. Title - The title of the Input Box. default-text - 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.

28

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

29

You might also like