ByVal or ByRef:
在VBA中,过程的传参方式有两种,按值或按引用。
如果按引用,即传递的是传入参数的地址,那么在过程中对参数的修改会反映到参数本身
如果按值,则会拷贝一份,那么在过程中对参数的修改不会反映到调用者
vba中默认是按地址传递。
Sub语法:
[Private | Public] [Static] Sub name [(arglist)]
[statements]
[Exit Sub]
[statements]
End Sub
函数语法:
[Public | Private][Static] Function name [(arglist)] [As type]
[statements]
[name = expression]
[Exit Function]
[statements]
[name = expression]
End Function
在VBA中,过程的传参方式有两种,按值或按引用。
如果按引用,即传递的是传入参数的地址,那么在过程中对参数的修改会反映到参数本身
如果按值,则会拷贝一份,那么在过程中对参数的修改不会反映到调用者
vba中默认是按地址传递。
Sub语法:
[Private | Public] [Static] Sub name [(arglist)]
[statements]
[Exit Sub]
[statements]
End Sub
函数语法:
[Public | Private][Static] Function name [(arglist)] [As type]
[statements]
[name = expression]
[Exit Function]
[statements]
[name = expression]
End Function
'函数可以返回结果,而sub不能
Sub test_sub()
MsgBox "Hello World!"
Call test_func '如果只是调用函数,不接收返回值,则用call,否则必须用一个变量来接收
ret = test_func()
MsgBox ret
End Sub
Function test_func()
Debug.Print "test_func enter..."
test_func = 123 ' 一个函数必须要有返回值,且给函数设置返回值的方式就是将函数名作为变量,并赋值
End Function
Sub test_dim()
'变量可以不用显式声明,直接拿来用(这点和python,perl类似),但不声明变量类型时,默认是variant类型
g = 1
g = "123"
MsgBox g
'声明一个变量h,并限制它为Integer类型
' h As Integer
' h = 5
'dim用于声明变量,可以设置变量类型,并且dim修饰的变量的范围为 词法范围
Dim a
Dim b As String
Dim c, d
Dim e As String, f As Integer
End Sub
Sub test_scope()
MsgBox g
End Sub
Sub test_type()
Dim i As Integer
Dim s As String
Dim l As Long
Dim si As Single
Dim d As Double
Dim de As decimals
Dim b As Boolean
Dim by As Byte
Dim v As Variant
Dim c As Currency
Dim da As Date
Dim o As Object
End Sub
' sub 的修饰符
'private, 只有本模块下的过程可访问
'public,本工程下的所有模块均可访问
'static,在调用sub时,保存中间变量
Sub test_exit()
MsgBox 1
Exit Sub
MsgBox 2
End Sub
' 过程参数的 语法
' [Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type][= defaultvalue]
'Optional后面的参数都是可选的, Optional 与 ParamArray 在参数列表中互斥
Function add(a, b)
add = a + b
End Function
' 两种函数调用方式
Sub test_func()
add 1, 2
Call add(1, 2)
End Sub