VBA之方法函数

方法函数

  • Sub
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    ' Declares a procedure named GetInfo 
    ' This Sub procedure takes no arguments
    Sub GetInfo()
    ' Declares a string variable named answer
    Dim answer As String
    ' Assigns the return value of the InputBox function to answer
    answer = InputBox(Prompt:="What is your name?")
    ' Conditional If...Then...Else statement
    If answer = Empty Then
    ' Calls the MsgBox function
    MsgBox Prompt:="You did not enter a name."
    Else
    ' MsgBox function concatenated with the variable answer
    MsgBox Prompt:="Your name is " & answer
    ' Ends the If...Then...Else statement
    End If
    ' Ends the Sub procedure
    End Sub
  • Function
    1
    2
    3
    Function Celsius(fDegrees) 
    Celsius = (fDegrees - 32) * 5 / 9
    End Function

Sub或Function 调用

1
2
3
4
5
6
7
8
9
10
11
12
Sub Main() 
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