Password Inputbox -- Not a question

Juan Pablo González

MrExcel MVP
Joined
Feb 8, 2002
Messages
11,959
Hello. After seeing quite a few posts about "How can I use an Inputbox that shows "*" instead of the actual characters, to protect the password being entered ?" and the usual response, you have to create an Userform to do that, well, I decided to do something about that, and with the help of Ivan F Moala, came up with this class module that enables you to have just that, an Inputbox that has the option to use a "Password character", such as "*"

Here's the code for the class module

Name it something like PwdInputBox
Code:
'---------------------------------------------------------------------------------------
' ClassModule   : PwdInputBox
' DateTime      : 30/07/02 10:30
' Last modified : 31/07/02 08:49
' Author        : Juan Pablo Gonzalez
'                 Special thanks to Ivan F Moala for pointing the right way
' Purpose       : Shows a standard InputBox but with the cabalitie to have a PasswordChar
'                 for the text entered.
' Parameters    : Prompt As String, required.  Text to show on the InputBox
'                 PasswordChar As String, optional. Character to show as PasswordChar.
'                 If vbNullString is entered, the text will show up normally.
'                 Title As String, optional.  Title of the InputBox
'                 Default As String, optional.  Default text to show (Will appear with the
'                 PasswordChar selected.  String character to hide the text entered
'                 XPos As Long, optional.  Horizontal distance between the left border of
'                 the dialog, and the left border of the screen
'                 YPos As Long, optional.  Vertical distance between the upper border of
'                 the dialog, and the upper border of the sreen
' Outputs       : Variant.  Is pressed Ok, the text entered.  If pressed Cancel, False
'---------------------------------------------------------------------------------------

Option Explicit


Function PassInputBox(Prompt As String, Optional PasswordChar As String, Optional Title As String, Optional Default As String, Optional XPos As Long, Optional YPos As Long)
    Dim UF                                              'Store the VBComponent
    Dim VUF As Object                                   'Store the userform object
    Dim Lb  As Object                                   'Label for the Prompt
    Dim Tb  As Object                                   'TextBox which holds the password
    Dim BOk  As Object
    Dim BCancel  As Object
    Dim VBAVisible As Boolean                           'Store VBE.Mainwindow visible state to restore it
    Dim i As Integer
    
    'Default Title is the same as InputBox
    If Len(Title) = 0 Then Title = Application.Name
    
    'Store the visible property of the VBE mainwindow and hide it to prevent screen flashing
    VBAVisible = Application.VBE.MainWindow.Visible
    Application.VBE.MainWindow.Visible = False
    
    'Add temporary Userform
    Set UF = ThisWorkbook.VBProject.VBComponents.Add(3)
    
    'Add the textbox.  If no PasswordChar was supplied, the text will appear normally
    Set Tb = UF.Designer.Controls.Add("Forms.Textbox.1", "TextBox1")
    With Tb
        .PasswordChar = PasswordChar
        .Left = 4.5
        .Top = 69.75
        .Width = 254.25
        .Height = 15.75
        .Value = Default
    End With
    
    'Add the prompt
    Set Lb = UF.Designer.Controls.Add("Forms.Label.1")
    With Lb
        .Caption = Prompt
        .WordWrap = True
        .Left = 6.75
        .Top = 6.75
        .Width = 198
        .Height = 54
    End With
    
    'Button OK, it is the default button
    Set BOk = UF.Designer.Controls.Add("Forms.CommandButton.1", "BOk")
    With BOk
        .Caption = "OK"
        .Left = 209.25
        .Top = 4.5
        .Width = 49.5
        .Height = 18
        .Default = True
    End With
    
    'Button Cancel
    Set BCancel = UF.Designer.Controls.Add("Forms.CommandButton.1", "BCancel")
    With BCancel
        .Caption = "Cancel"
        .Cancel = True
        .Left = 209.25
        .Top = 27
        .Width = 49.5
        .Height = 18
    End With
    
    'Add code to the Userform module
    With UF.CodeModule
        i = .CountOfLines
        'MyText is a variant which will hold the answer the user pressed
        .InsertLines i + 0, "Public MyText as Variant"
        
        'Pressed Cancel, so assign False to MyText
        .InsertLines i + 1, "Private Sub BCancel_Click()"
        .InsertLines i + 2, "   MyText = False: Me.Hide"
        .InsertLines i + 3, "End Sub"
        
        'Pressed Ok, so assign the value of TextBox1 to MyText
        .InsertLines i + 4, "Private Sub BOk_Click()"
        .InsertLines i + 5, "   MyText = TextBox1.Value: Me.Hide"
        .InsertLines i + 6, "End Sub"
    
        'Closing the form using "X", so assign False to MyText
        .InsertLines i + 7, "Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)"
        .InsertLines i + 8, "   If CloseMode = 0 Then Cancel = True: MyText = False: Me.Hide"
        .InsertLines i + 9, "End Sub"
    End With

    'Properties for the userform
    With UF
        .Properties("Caption") = Title
        .Properties("Width") = 273
        .Properties("Height") = 108.75
        
        'Center on screen or show in a specific position
        If XPos > 0 Or YPos > 0 Then
            .Properties("StartUpPosition") = 0
            .Properties("Left") = XPos
            .Properties("Top") = YPos
        Else
            .Properties("StartUpPosition") = 1
        End If
    End With
    
    'Include the UF in the Userforms collection
    Set VUF = VBA.UserForms.Add(UF.Name)
    
    'Show the Userform
    VUF.Show
    'Pass the result to this function
    PassInputBox = VUF.MyText

    'Remove the VBcomponet
    ThisWorkbook.VBProject.VBComponents.Remove VBComponent:=UF
    
    'Restore the VBE Mainwindow
    Application.VBE.MainWindow.Visible = VBAVisible
End Function

and here's an example Sub to show how it works.

Code:
Sub TestMe()
    Dim ans As Variant            'ans is declared Variant to work similar to Application.InputBox
    Dim App As PwdInputBox        'Reference the class module
    Set App = New PwdInputBox     'Create a new instance
    
    ans = App.PassInputBox("Please enter the password", "*", "My Application") 'Show the Inputbox and store the result
    If ans = False Then
        MsgBox "Pressed Cancel"
    Else
        MsgBox "The password entered is: " & ans
    End If
End Sub
 
...and the usual response, you have to create an Userform to do that....

I wonder why to use this code Juan Pablo and not to use a user form and a text box with passwordchar=* or whatever i want, without any code ?
 
Upvote 0

Excel Facts

What is the last column in Excel?
Excel columns run from A to Z, AA to AZ, AAA to XFD. The last column is XFD.
truely amazing!

Thanks.

I am also having problems with another piece of code you just helped with on lotus notes.


CODE____________________________________
Loop While vaMsg = ""

On Error Resume Next

Set rnBody = Application.InputBox("Please enter the range:", _
, Selection.Address, , , , 8)
If rnBody Is Nothing Then Exit Sub
On Error GoTo 0

Set noSession = CreateObject("Notes.NotesSession")
Set noDatabase = noSession.GETDATABASE("", "")

If noDatabase.IsOpen = False Then noDatabase.OPENMAIL

CODE______________________
with the line set RNBODY I can click and drag the range,
but the error message still exits sub.
Where am I going wrong?
thanks
 
Upvote 0
Rather than post a new topic, I searched and found this classmodule which almost completely meets my needs....

How can the class module be amended so that the userform contains 2 text boxes and labels - UserName and Password?

TIA,
Mark
 
Upvote 0
Well, you would need to add three things basically:

A second label, Lb2, a second TextBox, Tb2, and another Public variable, UserName for example. You can guide yourself with the code that uses

With Lb

and

With Tb

and in the BOk_Click and BCancel_Click you need to add before hidding the form:

UserName = TextBox2.Value

assuming that's the name that you'll give to the second textbox.
 
Upvote 0
I inserted the code and the class module into my existing code during my WorkbookOpen event. I keep getting an error message that says

Run time error '50289'
Can't perform operation because the project is protected.

What do I need to do to make this work? (Without unprotecting the project)
 
Upvote 0
Hi all,
Used the .InsertLines method together with dynamically inserted textbox'es but my code doesnt seem to work...

Depend on the amount of data (made with an example of 20) the form creates the necessary Textbox'es (from i=1 to the amount). The size has been made similar to the already inserted labels (with j=1 to 6)
For each textbox(i) and( j=4) i need to create a "Private Sub TextBox" & i & j & "_AfterUpdate" and it goes well... but nothing happens when I try to update the textbox when the form is showed...

Can anybody tell me why? (Juan!)...

My code is:

Private Sub UserForm_Initialize()
On Error Resume Next
Dim TBray(20) As MSForms.TextBox
Dim DTPray(20) As MSComCtl2.DTPicker
Dim intTop As Integer
Dim i As Integer, x As Integer
BackColor = RGB(146, 154, 151)
For i = 1 To 6
Me.Controls("Label" & i).BackColor = RGB(146, 154, 151)
Next i
intTop = 0
Label4.Caption = Label4.Caption & " " & Sheets("Data").Range("C7")
For i = 1 To WorksheetFunction.CountIf(Sheets("Data").Range("S12:S65536"), "<>" & "")
For j = 1 To 6
If j <> 3 Then
Set TBray(i) = Controls.Add("Forms.TextBox.1", "TextBox" & i & j)
With TBray(i)
.Top = intTop + 52
.Width = Me.Controls("Label" & j).Width
.Left = Me.Controls("Label" & j).Left
.Height = 16
.Font.Size = 8
.Text = Sheets("Data").Cells(11 + i, 18 + j).Value
If j = 2 Or j = 4 Then .TextAlign = fmTextAlignRight
If j = 2 Then .Text = Format(Sheets("Data").Cells(11 + i, 18 + j).Value, "0.00%")
If j = 4 Then
.Text = Format(Sheets("Data").Cells(11 + i, 18 + j).Value, "#,##0.000")
With ThisWorkbook.VBProject.VBComponents.Item("UserForm2").CodeModule
x = .CountOfLines
.InsertLines x + 1, "Private Sub TextBox" & i & j & "_AfterUpdate()"
.InsertLines x + 2, "On Error Resume Next"
.InsertLines x + 3, "If IsNumeric(TextBox" & i & j & ".Value) = False Then TextBox" & i & j & ".Value = Format(Sheets(""Data"").Range(""V12""), ""#,##0.000"")"
.InsertLines x + 4, "If TextBox" & i & j & ".Value < 0 Then"
.InsertLines x + 5, vbTab & "MsgBox ""Du har indtastet en ugyldig værdi!"", vbCritical, ""Get Data"""
.InsertLines x + 6, vbTab & "TextBox" & i & j & ".Value = Format(Sheets(""Data"").Range(""V12""), ""#,##0.000"")"
.InsertLines x + 7, "End If"
.InsertLines x + 8, "TextBox" & i & j & ".Value = Format(TextBox" & i & j & ".Value, ""#,##0.000"")"
.InsertLines x + 9, "End Sub"
End With
End If
End With
Else
Set DTPray(i) = Controls.Add("MSComCtl2.DTPicker", "DTPicker" & i & j)
With DTPray(i)
.Top = intTop + 52
.Width = Label3.Width
.Left = Label3.Left
.Height = 16
If Sheets("Data").Cells(11 + i, 21).Value <> "" Then
.Value = Format(Sheets("Data").Cells(11 + i, 21).Value, "dd-mm-yy")
Else
.Enabled = False
End If
.Font.Size = 8
End With
End If
Next j
intTop = intTop + 18
Next i
ScrollHeight = intTop + 100
End Sub
 
Upvote 0
Upvote 0
I know this is an old listing..

I installed and compiled OK (Excel 2003 on XP)

When I run the test, it responds with : Invalid procedure call or argument, highlighting line

ans = App.PassInputBox("Please enter the password", "*", "My Application") 'Show the Inputbox and store the result

Any ideas?
 
Upvote 0
You probably don't have the 'Trust access to the VB Project' box checked in the Macro security dialog. Anyway, try using DK's code (link above), it works much better.
 
Upvote 0

Forum statistics

Threads
1,215,873
Messages
6,127,442
Members
449,382
Latest member
DonnaRisso

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top