1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Excel】VBAでパスワード入力フォームを作る【ユーザーフォーム】

Last updated at Posted at 2022-10-14

やりたいこと

  • Excel VBAでダイアログを表示して、ユーザーにパスワードを入力させたい
  • 入力されたパスワードは*とかでシーリングしたい
  • InputBoxに近い感じで使いたい

InputBoxでは入力文字が隠せない

やりたいことは概ねInputBoxの機能で実現できるのですが、InputBoxでは入力した文字がそのまま画面に表示されてしまいます。
一方でユーザーフォームのテキストボックスにはPasswordCharプロパティがあり、そこに*等の文字を設定することで、入力された文字列を非表示にできます。
InputBoxの引数にPasswordCharがあれば万事解決だったのに。

簡単なユーザーフォームを作ってInputBoxの代わりに使う

さて、そういうわけで簡単なユーザーフォームを作成してInputBoxの代わりに使えるようにしましょう。
ポイントは以下のとおりです。

  • ユーザーフォームにテキストボックスとOK,Cancelボタン、ラベルを配置する
  • コードビハインドにInputBox関数に相当するInputPasswordBox関数を定義する
  • ついでにOK,Cancelのいずれかのボタンが押されたのか取得できるプロパティを実装する

コントロールの設定(プロパティ)

プロパティウィンドウで設定した項目です。(コードビハインドの前提条件)
書かれていないプロパティはデフォルト値のままです。

ユーザーフォーム

image.png

  • (オブジェクト名):FormInputPasswordBox
  • Caption:(コードで指定するので使わないけど、お好みで変更)

OKボタン

  • (オブジェクト名):ButtonOK
  • Default:True
  • Caption:OK

Cancelボタン

  • (オブジェクト名):ButtonCancel
  • Cancel:True
  • Caption:キャンセル

テキストボックス

  • (オブジェクト名):TextBoxPassword
  • PasswordChar:*

ラベル

  • (オブジェクト名):LabelMessage
  • Caption:(コードで指定するので使わないけど、お好みで変更)

コードビハインド

FormInputPassword
Option Explicit
Private IsCanceled_intarnal As Boolean
Private IsOKed_intarnal As Boolean

Public Function InputPasswordBox(caption As String, title As String) As String
    Me.LabelMessage.caption = caption
    Me.caption = title
    Call Me.Show
    InputPasswordBox = TextboxPassword.Value
End Function

Public Property Get IsCanceled() As Boolean
    IsCanceled = IsCanceled_intarnal
End Property
Private Sub ButtonCancel_Click()
    IsCanceled_intarnal = True
    Call Me.Hide
End Sub

Public Property Get IsOKed() As Boolean
    IsOKed = IsOKed_intarnal
End Property
Private Sub ButtonOK_Click()
    IsOKed_intarnal = True
    Call Me.Hide
End Sub

Private Sub UserForm_Initialize()
    IsCanceled_intarnal = False
    IsOKed_intarnal = False
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = vbFormControlMenu Then
        Cancel = True ''×ボタンで閉じられるとIsOKedプロパティとかが使えない
    End If
End Sub
Module
Option Explicit
Sub Login()
    Dim password As String
    ' パスワード入力用ユーザーフォーム
    Dim fipb As New FormInputPasswordBox
    password = fipb.InputPasswordBox("パスワードを入力してください", "パスワード入力")
    If fipb.IsCanceled Then
        Call MsgBox("キャンセルされました")
    End If
    Call Unload(fipb) ' ユーザーフォーム解放
End Sub

余談

先日C#でも似たようなことをやりました。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?