RandArray関数っぽいユーザー定義関数

先日、何度かRandBetween関数を使っている内に、気が付いた。
何だろう、これ。
f:id:Infoment:20200112225707p:plain

調べてみると、↓のような説明があった。
support.office.com

これは、面白そうだ。早速試してみよう。
A1を起点に、4行6列のランダムな表を作成する。値の範囲は、10~20の整数にしてみよう。

Sub test()
    Dim arr As Variant
        arr = WorksheetFunction.RandArray(4, 6, 10, 20, True)
        Range("A1").Resize(4, 6) = arr
End Sub

さて、結果は・・・失敗。
f:id:Infoment:20200112230519p:plain

ならばワークシートでは?と思い試してみたが、どうも未だ使えないらしい。
f:id:Infoment:20200112230717p:plain

残念。もし使えたら、色々と面白そうだったのに。

というわけで、疑似的に再現する関数を作成してみた。

Function DemiRandArray(r_max As Long, _
                       c_max As Long, _
                       dra_min As Long, _
                       dra_max As Long, _
                       integer_flag As Boolean) As Variant

    Dim arr() As Variant
    ReDim arr(1 To r_max, 1 To c_max)
    
    Dim r As Long
    Dim c As Long
        For r = 1 To r_max
            For c = 1 To c_max
                Select Case integer_flag
                    Case True
                        arr(r, c) = WorksheetFunction.RandBetween(dra_min, dra_max)
                    Case False
                        Dim temp As Double
                        Dim myFlag As Boolean
                            myFlag = False
                        Do While myFlag = False
                            temp = Rnd * (dra_max + 1)
                            If dra_min <= temp And temp <= dra_max Then
                                arr(r, c) = temp
                                myFlag = True
                            End If
                        Loop
                End Select
            Next
        Next
                
        DemiRandArray = arr
End Function

早速テストしてみよう。

整数ではない場合。

Sub Test()
    Dim arr As Variant
        arr = DemiRandArray(4, 6, 10, 20, False)
        Range("A1").Resize(4, 6) = arr
End Sub

f:id:Infoment:20200112232909p:plain

整数の場合。

Sub Test()
    Dim arr As Variant
        arr = DemiRandArray(4, 6, 10, 20, True)
        Range("A1").Resize(4, 6) = arr
End Sub

f:id:Infoment:20200112233003p:plain

これの使い処については・・・また考えてみます。

参考まで。