売上管理・在庫管理システムでの典型的な ByRef 活用パターン
業務システムでは「複数の値を返す」「参照を差し替える」といった場面が多く、ByRef が役立ちます。ただし副作用を避けるために「戻り値とByRefの役割分担」を意識することが重要です。ここでは 売上管理・在庫管理 の典型的なシナリオを掘り下げて紹介します。
1. 売上集計(合計・平均・最大)
- パターン: 主結果(合計)は戻り値、副次結果(平均・最大)は ByRef
- 用途: 日次売上の集計処理
Function CalcSales(ByVal sales() As Double, ByRef avg As Double, ByRef maxVal As Double) As Double
Dim i As Long, sum As Double
sum = 0
maxVal = sales(LBound(sales))
For i = LBound(sales) To UBound(sales)
sum = sum + sales(i)
If sales(i) > maxVal Then maxVal = sales(i)
Next
avg = sum / (UBound(sales) - LBound(sales) + 1)
CalcSales = sum ' 主結果(合計)
End Function
VB2. 在庫更新(残数とステータス)
- パターン: 在庫残数を ByRef で更新、ステータスを戻り値で返す
- 用途: 出庫処理で残数を減らし、在庫切れを判定
Function UpdateStock(ByRef stockQty As Long, ByVal orderQty As Long) As String
stockQty = stockQty - orderQty
If stockQty <= 0 Then
UpdateStock = "在庫切れ"
Else
UpdateStock = "在庫あり"
End If
End Function
VB3. 商品検索(参照差し替え)
- パターン: Range参照を ByRef で差し替え
- 用途: 商品コードに一致するセルを探して呼び出し元の参照を更新
Sub FindProduct(ByRef r As Range, ByVal productCode As String)
Dim found As Range
Set found = Sheet1.Range("A:A").Find(productCode)
If Not found Is Nothing Then
Set r = found
End If
End Sub
VB4. 複数結果返却(売上金額と利益)
- パターン: 売上金額は戻り値、利益は ByRef
- 用途: 売上と利益を同時に計算
Function CalcRevenue(ByVal unitPrice As Double, ByVal qty As Long, ByRef profit As Double) As Double
Dim revenue As Double
revenue = unitPrice * qty
profit = revenue * 0.3 ' 利益率30%と仮定
CalcRevenue = revenue
End Function
VB5. 在庫調整(複数値返却)
- パターン: ByRefで複数の在庫情報を返す
- 用途: 入庫処理で残数と更新日時を返す
Sub AdjustStock(ByRef stockQty As Long, ByRef lastUpdate As Date, ByVal addQty As Long)
stockQty = stockQty + addQty
lastUpdate = Now
End Sub
VB6. 参照破棄(リソース解放)
- パターン: ByRefで参照を消す
- 用途: 在庫検索用のRange参照を明示的に破棄
Sub ReleaseProductRange(ByRef r As Range)
Set r = Nothing
End Sub
VB✅ 設計指針まとめ
- 戻り値は主結果用 → 読みやすく安全。
- ByRefは副次結果や参照差し替え用 → 意図を明示して使う。
- 入力は必ずByVal → 呼び出し元を壊さない。
- コメントや名前付けで意図を明示 → 「返却用」「参照変更用」と分かるように。
💡 実務では「売上集計」「在庫更新」「商品検索」などで 複数値返却や参照差し替え が頻出します。ByRefを使うと便利ですが、副作用を避けるために戻り値との役割分担を徹底するのが安全設計のコツです。

