Excel VBA 函数返回值
Sub 定义一个过程
VB的函数定义格式与C有很大区别:
格式:
Sub 过程名(参数列表 ... )
过程体
End Sub
Function 定义一个函数
官方文档 🚀 Microsoft Docs | 编写 Function 过程
Function 函数名(参数列表 ... )
函数体
函数名 = 返回值
End Function
实例代码:
Sub Main()
temp = Application.InputBox(Prompt:= _
"Please enter the temperature in degrees F.", Type:=1)
MsgBox "The temperature is " & Celsius(temp) & " degrees C."
End Sub
Function Celsius(fDegrees)
Celsius = (fDegrees - 32) * 5 / 9
End Function
调用Sub过程或者Function函数
调用函数时,有两种形式:
- 可以直接将参数放在函数名后,英文逗号 ‘,’ 作为参数分隔符,不需要加圆括号。
此种调用方式,将舍弃函数返回值。
Sub Main()
MultiBeep 56
Message
End Sub
Sub MultiBeep(numbeeps)
For counter = 1 To numbeeps
Beep
Next counter
End Sub
Sub Message()
MsgBox "Time to take a break!"
End Sub
- 使用类c语言的方式,参数后加圆括号,用以包含参数。
Sub Main()
Answer3 = MsgBox("Are you happy with your salary?", 4, "Question 3")
HouseCalc 99800, 43100
Call HouseCalc(380950, 49500)
End Sub
Sub HouseCalc(price As Single, wage As Single)
If 2.5 * wage <= 0.8 * price Then
MsgBox "You cannot afford this house."
Else
MsgBox "This house is affordable."
End If
End Sub
- 函数名前,可加
Call
关键字,亦可省略。
References: