では、Excel シートに結果を書き込む形で、ByVal / ByRef の違いが一目でわかるサンプルを作ります。
コピーして標準モジュールに貼り付ければそのまま動きます。
Excel で動かせるサンプル(セルに出力)
以下のコードを 標準モジュール(Module1) に貼り付けてください。
サンプル 1:ByVal と ByRef の違いをセルに表示する
Sub Sample_ByVal_ByRef()
' --- 初期値 ---
Dim a As Integer
Dim b As Integer
a = 5
b = 5
' --- Before(処理前の値) ---
Range("A1").Value = "Before (処理前)"
Range("A2").Value = "a = " & a
Range("A3").Value = "b = " & b
' --- 処理実行 ---
Change_ByVal a ' 値渡し → a の値は変わらない
Change_ByRef b ' 参照渡し → b の値は変更される
' --- After(処理後の値) ---
Range("C1").Value = "After (処理後)"
Range("C2").Value = "a = " & a
Range("C3").Value = "b = " & b
End Sub
' 値渡し(ByVal) → 呼び出し元の値は変わらない
Sub Change_ByVal(ByVal x As Integer)
x = x + 10
End Sub
' 参照渡し(ByRef) → 呼び出し元の値が変わる
Sub Change_ByRef(ByRef x As Integer)
x = x + 10
End Sub
VB実行するとどうなる?
| セル | 内容 |
|---|---|
| A1 | Before(処理前) |
| A2 | a = 5 |
| A3 | b = 5 |
| C1 | After(処理後) |
| C2 | a = 5(ByVal → 変わらない) |
| C3 | b = 15(ByRef → 変わる) |
Excel の画面で Before / After を見比べられるので、違いが一発で理解できます。
サンプル 2:文字列を変更してセルに出力する例
Sub Sample_String_ByVal_ByRef()
Dim s1 As String, s2 As String
s1 = "Hello"
s2 = "Hello"
Range("A5").Value = "Before"
Range("A6").Value = "s1 = " & s1
Range("A7").Value = "s2 = " & s2
AddMark_ByVal s1
AddMark_ByRef s2
Range("C5").Value = "After"
Range("C6").Value = "s1 = " & s1
Range("C7").Value = "s2 = " & s2
End Sub
Sub AddMark_ByVal(ByVal text As String)
text = text & "!"
End Sub
Sub AddMark_ByRef(ByRef text As String)
text = text & "!"
End Sub
VB結果:
| Before | After | |
|---|---|---|
| s1 = Hello | → | Hello(変わらない) |
| s2 = Hello | → | Hello!(変わる) |
サンプル 3:配列の要素を書き換えてセルに出力
Sub Sample_Array_ByRef()
Dim arr(1 To 3) As String
arr(1) = "A": arr(2) = "B": arr(3) = "C"
Range("A10").Value = "Before"
Range("A11").Value = Join(arr, ", ")
ModifyArray arr
Range("C10").Value = "After"
Range("C11").Value = Join(arr, ", ")
End Sub
Sub ModifyArray(ByRef a() As String)
a(1) = "X" ' 1番目だけ変更
End Sub
VB結果:
| Before | After | |
|---|---|---|
| A, B, C | → | X, B, C |
サンプル 4:2つの数字を入れ替えてセルに出力(Swap)
Sub Sample_Swap()
Dim x As Integer, y As Integer
x = 3
y = 7
Range("A15").Value = "Before"
Range("A16").Value = "x = " & x
Range("A17").Value = "y = " & y
SwapValues x, y
Range("C15").Value = "After"
Range("C16").Value = "x = " & x
Range("C17").Value = "y = " & y
End Sub
Sub SwapValues(ByRef a As Integer, ByRef b As Integer)
Dim tmp As Integer
tmp = a
a = b
b = tmp
End Sub
VB結果:
| Before | After | |
|---|---|---|
| x = 3 | → | x = 7 |
| y = 7 | → | y = 3 |
ここまでのサンプルをまとめて実行する「総合テスト」
全部まとめて走らせたい場合:
Sub RunAllSamples()
Call Sample_ByVal_ByRef
Call Sample_String_ByVal_ByRef
Call Sample_Array_ByRef
Call Sample_Swap
MsgBox "全てのサンプルが実行されました!", vbInformation
End Sub
VB