自分用です。
乱数で3ケタコードを出力します。
すべて違う数値を組み合わせる、ぞろ目にしない、123,456などにしない、最後を0にしないという条件です。

Sub ランダムな3桁コードを付ける()

    Dim シート名 As String
    シート名 = "コード一覧"

    Dim 新規シート As Worksheet
    On Error Resume Next
    Application.DisplayAlerts = False
    Worksheets(シート名).Delete ' 既に存在していれば削除
    Application.DisplayAlerts = True
    On Error GoTo 0

    Set 新規シート = Worksheets.Add
    新規シート.Name = シート名

    ' ランダムな3桁コード生成
    Dim 使用済みコード As Collection
    Set 使用済みコード = New Collection

    Dim 現在の数値 As Long
    Dim 百の位 As Long, 十の位 As Long, 一の位 As Long
    Dim 数値文字列 As String
    Dim 行番号 As Long
    
    '乱数の「種(シード)」を設定する
    Randomize

    For 行番号 = 1 To 50
        Do
            百の位 = Int(Rnd() * 9) + 1
            十の位 = Int(Rnd() * 10)
            一の位 = Int(Rnd() * 10)

            If 百の位 <> 十の位 And 百の位 <> 一の位 And 十の位 <> 一の位 And 一の位 <> 0 Then

                ' 連番パターン(昇順や降順)を除外
                If Not (百の位 + 1 = 十の位 And 十の位 + 1 = 一の位) _
                   And Not (百の位 - 1 = 十の位 And 十の位 - 1 = 一の位) Then
                   
                    現在の数値 = 百の位 * 100 + 十の位 * 10 + 一の位
                    数値文字列 = CStr(現在の数値)
            
                    On Error Resume Next
                    使用済みコード.Add 数値文字列, 数値文字列
                    If Err.Number = 0 Then
                        新規シート.Cells(行番号, 1).Value = 現在の数値 ' B列に出力
                        Exit Do
                    End If
                    Err.Clear
                    On Error GoTo 0
                End If
            End If
        Loop
    Next 行番号

    MsgBox "シート『" & シート名 & "』を作成し、コードを出力しました!", vbInformation

End Sub

 

おすすめの記事