Excel VBA 函數返回值

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函數

調用函數時,有兩種形式:

  1. 可以直接將參數放在函數名後,英文逗號 ‘,’ 作爲參數分隔符,不需要加圓括號。
    此種調用方式,將捨棄函數返回值。
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
  1. 使用類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
  1. 函數名前,可加Call關鍵字,亦可省略。

References:

Microsoft Docs | Calling Sub and Function procedures

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章