VBA Functionの使い方
■引数なし・戻り値なし
【基本構文】
Function プロシージャ名()
//処理内容
End Function
【使用例】
Function func()
MsgBox "test"
End Function
----------------------------
Sub test()
Call func
End Sub
■引数あり・戻り値なし
【基本構文】
Function プロシージャ名(ByVal 引数名 As データ型)
//処理内容
End Function
【使用例】
Function func(ByVal str As String)
MsgBox str
End Function
----------------------------
Sub test()
Dim str As String
str = "test"
Call func(str)
End Sub
■引数なし・戻り値あり
【基本構文】
Function プロシージャ名() As 戻り値のデータ型
//処理内容
//プロシージャ名 = 戻り値
End Function
【使用例】
Function func() As Integer
Dim num As Integer
num = 10
func = num
End Function
----------------------------
Sub test()
Dim result As Integer
result = func()
MsgBox result
End Sub
■引数あり・戻り値あり
【基本構文】
Function プロシージャ名(ByVal 引数名 As データ型) As 戻り値のデータ型
//処理内容
//プロシージャ名 = 戻り値
End Function
【使用例】
Function func(ByVal i As Integer) As Integer
Dim num As Integer
num = i * 2
func = num
End Function
----------------------------
Sub test()
Dim result As Integer
result = func(10)
MsgBox result
End Sub
■複数の引数あり・戻り値あり
【基本構文】
Function プロシージャ名(ByVal 引数名1 As データ型, ByVal 引数名2 As データ型) As Variant
//処理内容
//プロシージャ名 = Array(戻り値1, 戻り値2)
End Function
【使用例】
Function func(ByVal i As Integer, ByVal j As Integer) As Variant
Dim num As Integer
num1 = i * 2
num2 = j * 2
func = Array(num1, num2)
End Function
----------------------------
Sub test()
Dim result As Variant
result = func(10, 20)
MsgBox result(0) & vbCrLf & result(1)
End Sub