VBS : Tutorial 5 (Funtions )
Functions
Example 1 : Syntax
Call func_name
Function Func_name()
msgbox 1+2
end function
Example 2: Returning Value
msgbox func_name
Function func_name()
func_name=1+2
end function
Example :Calculate
age of a person
Dim sVar1
sVar1=inputbox("e.g. 1947 "," Please Enter Years")
msgbox fn(sVar1)
Function fn(x)
fn= year(date)-x
End Function
Example 3: Sub-routine
Call func_name
Sub Func_name()
msgbox 1+2
end Sub
Example 4: Function
vs Sub
msgbox func_name
Sub Func_name()
func_name = 1+2
end Sub
Example 5 : Sending
Values to Functions
Dim a,b
a=3
b=4
msgbox Add(a,b)
Function Add(x,y)
Add=x+y
End Function
Example 6: Sending arrays to function
Dim a(9)
Call Add(a)
Function Add(x)
msgbox isarray(x)
End Function
Example 7 : Catching
the Return Value and Flags in framework
Dim a(9),bVar
bVar = Add(a)
msgbox bVar
Function Add(x)
Add=isarray(x)
End Function
Example 8: Function accept multiple arguements but returns only 1 value
Example 9: Variables are Global Unless declared ,-----NOT DECLARED i.e., PASS BY REF
msgbox a
call fn
call fn2()
msgbox a
Function fn()
a=5
msgbox a
end function
Function fn2()
msgbox a
a="dfsdf"
msgbox a
end function
Example 10: --- DECLARED
msgbox a
call fn
call fn2()
msgbox a
Function fn()
a=5
msgbox a
end function
Function fn2()
Dim a
msgbox a
a="dfsdf"
msgbox a
end function
Example
dim a
a=10.5
msgbox a
call fn
call fn2()
msgbox a
Function fn()
dim a
a=5
msgbox a
end function
Function fn2()
dim a
msgbox a
a="piyush"
msgbox a
end function
Example 9 : Pass By
Value and pass By Ref , By Default --> ByRef
-------------------------------------------
By Default variables are
passed ByRef
------------------------------------------
Ex Byval
Option Explicit
Dim strTest
strTest = "FOO"
RunTest (strTest)
msgbox strTest
Sub RunTest(ByVal strIn)
WScript.Echo strIn
strIn = "BAR"
msgbox strIn
End Sub
OUTPUT:
FOO
BAR
FOO
------------------------------------------------------
The default is ByRef. This
stands for "By Reference"
any changes that you make
inside the Sub/Function will be seen outside the Sub/Function. Here is a
demonstration:
Option Explicit
Dim strTest
strTest = "FOO"
RunTest (strTest )
msgbox strTest
Sub RunTest(strTest)
WScript.Echo strTest
strTest = "BAR"
msgbox strTest
End Sub
OUTPUT: >>
FOO
BAR
BAR
Example 1: Redim and
preserve
Redim a(1,2)
Redim a(2,3)
Example 2
Redim preserve a(1,2)
Redim a(2,3)
No comments:
Post a Comment