Excel VBA | 配列を返す関数

VBA
スポンサーリンク

「指定範囲の素数の最小値・最大値・個数・合計」をまとめて返す関数を作ってみましょう。今回は配列にまとめて返す形にします。


サンプルコード

Function PrimeStatsInRange(ByVal startNum As Integer, ByVal endNum As Integer) As Variant
    Dim i As Integer, j As Integer
    Dim isPrime As Boolean
    Dim minPrime As Long, maxPrime As Long
    Dim count As Long, total As Long
    Dim found As Boolean
    
    minPrime = 0
    maxPrime = 0
    count = 0
    total = 0
    found = False
    
    For i = startNum To endNum
        If i >= 2 Then
            isPrime = True
            ' 素数判定(2~√iまで)
            For j = 2 To Int(Sqr(i))
                If i Mod j = 0 Then
                    isPrime = False
                    Exit For
                End If
            Next j
            
            If isPrime Then
                If Not found Then
                    minPrime = i   ' 最初に見つかった素数が最小値
                    found = True
                End If
                maxPrime = i       ' 素数が見つかるたびに更新 → 最後が最大値
                count = count + 1
                total = total + i
            End If
        End If
    Next i
    
    ' 結果を配列で返す {最小値, 最大値, 個数, 合計}
    Dim result(1 To 4) As Long
    result(1) = minPrime
    result(2) = maxPrime
    result(3) = count
    result(4) = total
    
    PrimeStatsInRange = result
End Function
VB

呼び出し例

Sub TestPrimeStats()
    Dim stats As Variant
    
    stats = PrimeStatsInRange(10, 50)
    MsgBox "最小の素数: " & stats(1) & vbCrLf & _
           "最大の素数: " & stats(2) & vbCrLf & _
           "素数の個数: " & stats(3) & vbCrLf & _
           "素数の合計: " & stats(4)
End Sub
VB

実行結果(10~50の場合)

  • 素数一覧 → 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47
  • 最小値 → 11
  • 最大値 → 47
  • 個数 → 11
  • 合計 → 311

ポイント

  • 配列を返すことで「複数の情報」を一度にまとめて返せる
  • stats(1) が最小値、stats(2) が最大値、stats(3) が個数、stats(4) が合計
  • 範囲を変えれば「100~200の素数統計」なども簡単に取得可能

👉 この関数をさらに拡張して「平均値」や「中央値」まで返すようにすると、統計的な分析にも使えます。

VBA
スポンサーリンク
シェアする
@lifehackerをフォローする
スポンサーリンク
タイトルとURLをコピーしました