mugaxのなんでも情報局

いろんな分野について発信していきます。

ランダムな文字列作成

■ランダムな文字列作成


'---------------------------------------------
'ランダムな文字列作成
'   hasNumがTrueの場合  : A-Z,a-z,0-9
'           Falseの場合 : A-Z,a-zのみ
'---------------------------------------------
Function GetRandStr(Optional length As Long = 5, Optional hasNum As Boolean = False) As String

    Dim i As Long
    Dim chrCode As Long
    Dim tChr As String
    Dim tStr As String
    Dim tNum As Long

    '長さが負(-n)の場合、1文字以上n文字以下の長さをランダムに設定
    If length < 0 Then
        length = WorksheetFunction.RandBetween(1, Abs(length))
    End If

    For i = 1 To length
        tChr = Chr(Asc("A") + WorksheetFunction.RandBetween(0, 25))
        '50パーセントの確率で小文字にする
        If WorksheetFunction.RandBetween(0, 1) = 1 Then
            tChr = LCase(tChr)
        End If
        
        '数字を含む場合
        If hasNum = True Then
            '数字、英大文字、英小文字の割合を元に乱数を作成
            tNum = WorksheetFunction.RandBetween(0, 10 + 26 + 26 - 1)
            '0-9なら数字を入れる
            If tNum < 10 Then
                tChr = tNum
            End If
        End If
        
        tStr = tStr & tChr
    Next

    GetRandStr = tStr

End Function