Monday, June 25, 2018

Text Masking in Excel VBA

Hello Friends,

Two days ago, I have posted one query here on Password Masking of Userform Textbox. David Miller tried to help me out but it's not happened actually.

Problem:

.PasswordChar property has been used to mask text to look like Password Characters just like "*********"

So, it's working fine in Windows Excel but not in MAC Excel.

Solution:

So, I developed a code which works with Textbox1_Change events. There is some limitation too with my solution. In general, you can edit the typed password during writing but in my case user won't be able to do so. if User wants to edit the password, they have to rewrite the whole code again.

My code will use the Cell A1 to store the actual password and will use it for credential matching.

here is the solution:

'/+++++++++++++++++++++++++++

Private Sub TextBox1_Change()

    Dim mystring As Variant
    Dim textlen As Integer
    Dim counter As Integer
    Dim passlen As Integer

    mystring = UserForm1.TextBox1.Value
    textlen = VBA.Len(mystring)
    passlen = VBA.Len(Sheets("Sheet1").Range("A1").Value)

    If VBA.Right(mystring, 1) = "*" Then
        If passlen <> textlen Then
            MsgBox "You're not allowed to do so"
            UserForm1.TextBox1.Value = ""
            Sheets("Sheet1").Range("A1").Value = ""
        Exit Sub
        End If
    Exit Sub
    End If

    For counter = 1 To textlen
        If textlen > 0 Then
            If VBA.Mid(mystring, counter, 1) = "*" Then
            Else
            Sheets("Sheet1").Range("A1").Value = Sheets("Sheet1").Range("A1").Value & VBA.Mid(mystring, counter, 1)
            End If
         End If
    Next

    If textlen > 0 Then
         UserForm1.TextBox1.Value = VBA.Replace(mystring, VBA.Mid(mystring, textlen, 1), "*")
    End If

End Sub

'/++++++++++++++++++++++++++++

this way text masking will be more universal and portable.

Thank you.

IsValidPasswordString Function

'Following function will verify if the password string contains following characters or not? Rem : List of Characters Group - ASCII Rem ...