Function - VBScript
Overview
The Function
command in VB Script allows you to define user-defined functions or subroutines within a script. It enables modular code organization and reuse, promoting code maintainability and efficiency.
Syntax
Function FunctionName[(parameters)]
[statements]
[Exit Function]
End Function
Parameters:
- FunctionName: Name of the function. Must start with a letter, followed by letters, digits, or underscores.
- parameters: Optional list of parameters passed to the function enclosed in parentheses.
Options/Flags
None.
Examples
Simple Function:
Function Add(a, b)
Add = a + b
End Function
Function with Default Parameters:
Function Min(a, b, c = 0)
Min = IIf(a < b, IIf(a < c, a, c), IIf(b < c, b, c))
End Function
Function with Exit Statement:
Function ValidateInput(input)
If input = "" Then
Exit Function "Empty input"
End If
' Continue validation...
End Function
Common Issues
- Name Collisions: Function names must be unique within the script to avoid overwriting.
- Missing End Statement: Always terminate functions with
End Function
to avoid runtime errors. - Recursion: Recursive functions (functions calling themselves) can cause stack overflow if not implemented carefully.
Integration
Functions can be combined with other VB Script commands to create complex scripts. For example, you can use Function
with InputBox
to prompt the user for input and return the validated result.
Related Commands
Sub
– Defines a subroutine without a return value.Option Explicit
– Enforces explicit variable declaration, preventing potential errors.- VB Script Function Library – Official Microsoft documentation on various built-in functions.