ある程度の内容で配列を作る関数

「1から100の偶数の和を求めるワンライナー」が話題になっている。
qiita.com

一行のコードで求めるには?の命題に対し、様々な言語で解法が寄せられていて興味深い。私の場合はスマートな方法が思いつけず、愚直に「:」でつなぐぐらいが限界だ。
そこで今回は、指定した内容で配列をサクッと作成する関数を考えてみた。
(既に世の中にあるかもしれませんが、そこはご愛敬ということで)。

' content       配列に詰め込む値
' count_up      詰め込む値をカウントアップするか否か
' count_number  1回のカウントアップ量
' l_bound       インデックス番号の最小値
' u_bound       インデックス番号の最大値
Function DenseArray(content As Variant, _
                    Optional count_up As Boolean = False, _
                    Optional count_number As Long = 1, _
                    Optional l_bound As Long = 0, _
                    Optional u_bound As Long = 10) As Variant
          
    Dim arr() As Variant
    ReDim arr(l_bound To u_bound)
    Dim i As Long
        For i = l_bound To u_bound
            If count_up Then
                
                ' 数値でなければカウントアップできないので、ここで判別。
                If IsNumeric(content) Then
                    arr(i) = content + (i - 1) * count_number
                Else
                    arr(i) = content
                End If
            Else
                arr(i) = content
            End If
        Next
        DenseArray = arr
End Function

それでは早速、恒例のテストをば。
1~100のうち、偶数のみ配列に格納する。
実際は2から始まって100までの数値50個を、2ずつカウントアップして配列に格納。
これを合計することで、最初のお題に迫ってみる。

Sub test()
    Dim arr As Variant
        arr = DenseArray(2, True, 2, 0, 50)
        MsgBox WorksheetFunction.Sum(arr)
End Sub

結果、正しい値を得ることが出来た。
f:id:Infoment:20190815132710p:plain

さらに強引の一行で書くならば、こんな感じかな。

Sub test2()
    MsgBox WorksheetFunction.Sum(DenseArray(2, True, 2, 0, 50))
End Sub

今回の手法は、番外編ってことでm(_ _)m

参考まで。