関数から結果を返すにはどうすればいいですか?
例えば、以下のようになります。
Public Function test() As Integer
return 1
End Function
これはコンパイルエラーになります。
この関数が整数を返すようにするにはどうしたらいいですか?
オブジェクト以外の戻り値型の場合は、次のように関数名に値を代入する必要があります。
Public Function test() As Integer
test = 1
End Function
使用例。
Dim i As Integer
i = test()
関数が Object 型を返す場合は、次のように Set
キーワードを使用する必要があります。
Public Function testRange() As Range
Set testRange = Range("A1")
End Function
使用例です。
Dim r As Range
Set r = testRange()
関数名に戻り値を代入しても、関数の実行は終了しないことに注意してください。関数を終了させたい場合には、明示的に Exit Function
と言う必要があります。たとえば、以下のようになります。
Function test(ByVal justReturnOne As Boolean) As Integer
If justReturnOne Then
test = 1
Exit Function
End If
'more code...
test = 2
End Function
ドキュメント: http://msdn.microsoft.com/en-us/library/office/gg264233%28v=office.14%29.aspx
返り値を関数名に設定するだけでは、Java(または他の)の return
文とは 正確には 同じではありません。
public int test(int x) {
if (x == 1) {
return 1; // exits immediately
}
// still here? return 0 as default.
return 0;
}
VBでは、正確に同等のものが2行必要ですもしあなたが関数の最後に戻り値を設定していないならば。つまり、VBでは正確な裏付けは次のようになります。
Public Function test(ByVal x As Integer) As Integer
If x = 1 Then
test = 1 ' does not exit immediately. You must manually terminate...
Exit Function ' to exit
End If
' Still here? return 0 as default.
test = 0
' no need for an Exit Function because we're about to exit anyway.
End Function
このように、メソッド内の他の変数と同じように、戻り値の変数を使用できることも知っておくといいでしょう。こんな感じです。
Public Function test(ByVal x As Integer) As Integer
test = x ' <-- set the return value
If test <> 1 Then ' Test the currently set return value
test = 0 ' Reset the return value to a *new* value
End If
End Function
あるいは、リターン変数がどのように機能するかの極端な例(ただし、実際にどのようにコーディングすべきかの良い例であるとは限りません)、つまり、あなたが夜眠れなくなるような例です。
Public Function test(ByVal x As Integer) As Integer
test = x ' <-- set the return value
If test > 0 Then
' RECURSIVE CALL...WITH THE RETURN VALUE AS AN ARGUMENT,
' AND THE RESULT RESETTING THE RETURN VALUE.
test = test(test - 1)
End If
End Function