Visual Basic 6の基礎 - 関数
ナビゲーションに移動
検索に移動
概要
基本構文
' 関数
[Private|Public] Function <関数名>([<引数> As <型>, ...]) [As <戻り値の型>]
' 処理
関数名 = 戻り値 '戻り値の設定
End Function
' サブルーチン
[Private|Public] Sub <サブルーチン名>([<引数> As <型>, ...])
' 処理
' ...略
End Sub
プロパティ
Property Get <プロパティ名>() As <型>
' 取得処理
' ...略
End Property
Property Let <プロパティ名>(<値> As <型>)
' 設定処理
End Property
引数の修飾子
- ByVal
- 値渡し
- ByRef
- 参照渡し (デフォルト)
- Optional
- 省略可能な引数
- ParamArray
- 可変長引数
関数の定義例
基本的な関数
Private Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
Add = x + y
End Function
' 使用例
Dim result As Integer
result = Add(5, 3) ' result = 8
参照渡しのサブルーチン
Private Sub Swap(ByRef a As Integer, ByRef b As Integer)
Dim temp As Integer
temp = a
a = b
b = temp
End Sub
' 使用例
Dim x As Integer, y As Integer
x = 1
y = 2
Swap x, y ' x = 2, y = 1
オプション引数
Private Function Multiply(ByVal x As Integer, Optional ByVal y As Integer = 1) As Integer
Multiply = x * y
End Function
' 使用例
Dim result As Integer
result = Multiply(5) ' result = 5
result = Multiply(5, 2) ' result = 10
可変長引数
Private Function Sum(ParamArray numbers() As Variant) As Long
Dim total As Long
Dim i As Integer
For i = 0 To UBound(numbers)
total = total + numbers(i)
Next
Sum = total
End Function
' 使用例
Dim result As Long
result = Sum(1, 2, 3, 4, 5) ' result = 15
プロパティ
Private m_Name As String
Property Get Name() As String
Name = m_Name
End Property
Property Let Name(ByVal value As String)
m_Name = value
End Property
' 使用例
Me.Name = "Test" ' 設定
Debug.Print Me.Name ' 取得