【ExcelVBA】パスワード自動生成サンプルコード
スポンサーリンク

パスワード生成コード

Sub Create_password(pass_cel As Range, pass_len As Integer, req_char As Integer, req_num As Integer, req_sym As Integer)
    
    Dim rc As VbMsgBoxResult
    Dim massage As String
    If pass_cel = "" Then
        rc = MsgBox("パスワードを入力しますか?", vbYesNo + vbQuestion, "パスワード作成の確認")
        massage = "パスワードを入力しました"
    Else
        rc = MsgBox("パスワードを変更してもよろしいですか?", vbYesNo + vbQuestion, "パスワード変更の確認")
        massage = "パスワードを変更しました"
    End If
    
    If rc = vbYes Then
        Dim password_result As String
        Dim password_string As String
        Dim char As String
        Dim num As String
        Dim symbol As String
        Dim count As Integer
    
        password_string = "123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ+-<>_()#$%&*[]\?!@"
        char = "ABCDEFGHIJKLMNPQRSTUVWXYZ"
        num = "123456789"
        symbol = "+-<>_()#$%&*[]\?!@"
        count = 1
    
        If req_char = 1 Then
            password_result = password_result & Mid(char, WorksheetFunction.RandBetween(1, Len(char)), 1)
            count = count + 1
        End If
        If req_num = 1 Then
            password_result = password_result & Mid(num, WorksheetFunction.RandBetween(1, Len(num)), 1)
            count = count + 1
        End If
        If req_sym = 1 Then
            password_result = password_result & Mid(symbol, WorksheetFunction.RandBetween(1, Len(symbol)), 1)
            count = count + 1
        End If
    
        For cnt = count To pass_len
            password_result = password_result & Mid(password_string, WorksheetFunction.RandBetween(1, Len(password_string)), 1)
        Next

   	 	pass_cel.Value = password_result
    	MsgBox massage, vbInformation
    Else
        MsgBox "処理を中止しました", vbCritical
    End If
End Sub

実行方法

Sub main()
    Create_password Range("B2"), 13, 1, 1, 1
End Sub

関数の呼び出し方法は、関数名である「Create_password」をメインメソッド内で記述し、それに続き引数を5つ入力します。引数の順番は以下の通りです。

  1. パスワードを入力したいセルの番地を指定
  2. パスワードの長さを半角数字で入力
  3. 大文字が必須の場合は「1」どちらでも良い場合は「0」
  4. 数字が必須の場合は「1」どちらでも良い場合は「0」
  5. 記号が必須の場合は「1」どちらでも良い場合は「0」

サンプルのメインメソッドでは、セルB2に13文字のパスワードを大文字・数字・記号が必ず含まれるパスワードを生成しています。

スポンサーリンク
おすすめの記事