Functions and Subroutines in Visual Basic
Functions and Procedures
Functions and Procedures (1.6)
Functions and subroutines are types of program units used to divide a program into smaller, more manageable parts.
Subroutines (Procedures): مجموعة من التعليمات تنفذ مهمة محددة ويمكن استدعاؤها أكثر من مرة من أجزاء مختلفة من البرنامج.
Functions (الدوال): تشبه الإجراءات الفرعية ولكنها تُرجع قيمة واحدة كنتيجة لتنفيذها.
Subroutines (البرامج الفرعية)
تُستخدم لتنفيذ مهام محددة ويمكن استدعاؤها عدة مرات.
يمكن أن تستقبل معاملات (مدخلات) لتخصيص سلوكها.
لا تُرجع قيمة بشكل مباشر، ولكن يمكنها تعديل قيم المعاملات المُمررة إليها.
Functions (الدوال)
تُستخدم لتنفيذ عمليات حسابية أو منطقية وإرجاع قيمة واحدة.
تستقبل معاملات (مدخلات) لتحديد البيانات التي ستعمل عليها.
يجب أن تحتوي على جملة إرجاع تحدد القيمة التي ستُرجعها الدالة.
Functions return a value, subroutines do not.
Subroutines perform an action, functions calculate a value.
Subroutines may or may not have arguments, functions usually have arguments.
Subroutines
Definition: A block of code that performs a specific task.
Declaration: Starts with
Private Sub
followed by the subroutine name and parameters, and ends withEnd Sub
.Example:
Private Sub sub_add_numbers(x As Integer, y As Integer) ' Code to add numbers End Sub
Placement: Subroutines can be placed in:
Form (General section): Accessible from any control on the form (Private Sub).
Module: Accessible from any form or control in the project (Public Sub).
To add a module, select "Add Module" from the "Project" menu.
Parameters: Variables that represent input or output values.
Input Parameters: Values passed into the subroutine.
Output Parameters: Values returned or modified by the subroutine.
Calling a Subroutine: Use the
Call
statement or simply write the subroutine name.Syntax:
Call sub_name(Par1, Par2, ..., Parn)
Or
sub_name(Par1, Par2, ..., Parn)
Event-Driven Subroutines: Execute when a specific event occurs (e.g., button click).
Example:
Private Sub Command1_Click() ' Code to execute on button click End Sub
Command1_Click
is a subroutine that runs whenCommand1
is clicked.
Example Subroutine: Adding Two Numbers
Scenario: A form with two text boxes for input, a button to sum the values, and a text box for the result.
Code: الإجراء يقرأ القيم من مربعي النص، ويجمعهما بعد تحويلهما إلى أعداد صحيحة، ثم يعرض النتيجة في مربع نص آخر.
Private Sub CmdSum_Click() Dim V1 As String Dim V2 As String Dim V3 As String Dim SUM As IntegerV1 = Text1.Text V2 = Text2.Text SUM = Cint(V1) + Cint(V2) V3 = CStr(SUM) Text3.Text = V3 End Sub
Note: The Dim keyword is used to declare the variables.
Subroutine Example with Input and Output
Private Sub ConstructMessage(V As Integer)
MsgBox "Value of V is = " & V
End Sub
Private Sub form_Load()
V = InputBox("Enter a value (V)")
ConstructMessage(V)
End Sub
This subroutine
ConstructMessage
takes an integerV
as input and displays a message box.MsgBox
is a function that displays a dialog box with a message.
Functions
Definition: A block of code that performs a specific task and returns a value.
User-Defined Functions: Functions created by the programmer.
Declaration: Starts with
Private Function
followed by the function name, parameters, and return type, and ends withEnd Function
.Syntax:
Private Function Fun_Name (Par1 As Type1, ..., Parn As TypeN) As Fun_Type ' Function body Fun_Name = ReturnValue ' Assign the return value End Function
Fun_Name
: The name of the function.Par1, ..., Parn
: Parameters (inputs) to the function.Type1, ..., TypeN
: Data types of the parameters.Fun_Type
: Data type of the value returned by the function.
Returning a value:
Assign the return value to function's name inside the function body:
FunctionName = value
Example:
Private Function Message(Val As Integer) As String
Message = "The value of amount is " +Cstr(Val)
End Function
Notes: HAs StringI specifies the return value's data type.
*HValI specifies an input value. *
HIntegerI Specifies the input's data type.
The return value can be String data type, and other data type
Functions can also be used with HSUBI and SUBI @Îc@ and LHPrivate.
Functions can also be used with HFunctionI @Îc@ and LHPrivate.
End Function is used to close a function.
Predefined Functions:
There are built in functions for Tools, Procedure.
Debugging
Breakpoint: A marker in the code where execution pauses, allowing you to inspect variables and step through the code.
Toggle Breakpoint: F9. Or use Debug option.
View: Menu Bar, Add Watch.
Immediate Window: A window where you can execute commands and inspect variables during debugging (Ctrl+G).
Debug -> View -> Immediate Window
Immediate Window: Can be used to find the values of variables by printing them.
Print: Can be used to print variables in the immediate window.
Examples:
#1/1
My Age is 45
This part talks about error types.
Logic errors, Compile errors, Runtime errors.
Also talks about how to fix them.
You can use the following in subroutines:
Exit.
Functions.
Or Call other functions.
Also you can create variables and use functions within one another to achieve modularity.
There are many ways of doing things.
Example with dividing the values.
Code:
Private Sub CmdDiv1_Click()
Dim num As Integer
Dim Den As Integer
Dim Res As String
num = Text1.Text
Den = Text2. Text
Res = Divide(num, Den)
If Res=!!!! Then
"Division by zero" = IblMini.Caption
Else
IblMini.Caption = Res
End If
End Sub
Private Function Divide (n As Integer, m As Integer) As String
If m = 0 Then
Exit Function
Else
Divide = " Division is " & n/m
End If
End Function
Built In Functions:
Many prebuilt functions are available for performing tasks.
Math.
String related.
Date and time related.
Example of Math functions:
Sqr(x)
calculates the square root.
Number = Text 1. Text
Sqr = 5
Abs(x)
Returns the absolute value of a number.
Example:
Abs(-45.6)
returns 45.6.
Int(x)
Returns the integer part of a number.
Example:
Int(332.54)
returns 332.
Log(x)
Returns the natural logarithm of a number.
Example:
Log(20)
returns 2.9957327.
Sin(x)
Returns the sine of an angle.
Cos(x)
Returns the cosine of an angle.
Tan(x)
Returns the tangent of an angle.
Example of String functions:
Len(String)
Returns the length of a string.
Trim(String)
Removes leading and trailing spaces from a string.
LTrim(String)
Removes leading spaces from a string.
RTrim(String)
Removes trailing spaces from a string.
Left(String, Length)
Returns a specified number of characters from the left side of a string.
Example:
Left("How – are – you", 7)
returns "How – a".
Right(String, Length)
Returns a specified number of characters from the right side of a string.
Example:
Right("Have – A – Nice – Day", 8)
returns "Nice – Day".
Mid(String, Start, Length)
Returns a specified number of characters from a string, starting at a specified position.
Example:
Mid("Have – A – Nice – Day", 4, 8)
returns "A – Nice".
Chr(Character)
Returns the character associated with the specified ASCII code.
Str(String)
Converts a number to a string.
Val(String)
Converts a string to a number.
Date and time related Built in functions:
There are certain aspects related to formatting in other languages so I will skip it.
Now
Returns the current date and time.
Date
Returns the current date.
Time
Returns the current time.
DateValue(DateTime)
Returns the date part of a DateTime value.
TimeValue(DateTime)
Returns the time part of a DateTime value.
Weekday(Date)
Returns a number representing the day of the week (1 for Sunday, 7 for Saturday).
Format(Expression, Style)
Returns a string formatted according to the specified style.
Year(Date)
Returns the year part of a date.
Example:
Year(#18/6/2012#)
returns 2012.
Month(Date)
Returns the month part of a date.
Example:
Month(#18/6/2012#)
returns 6.
Day(Date)
Returns the day part of a date.
Example:
Day(#18/6/2012#)
returns 18.