Маска ввода для textbox vba excel

Создание маски ввода в TextBox с помощью кода VBA Excel на примере номера телефона и номера паспорта. Применимо для набора номера с клавиатуры.

В отличие от VBA Access в VBA Excel нет свойства InputMask объекта TextBox. Поэтому, чтобы добавить подобие маски для TextBox в VBA Excel, приходится писать дополнительную процедуру, контролирующую действия пользователя и добавляющую в нужные места вводимого номера знаки-разделители.

В следующих примерах мы будем создавать простые маски ввода в TextBox с помощью события TextBox_Change и оператора Select Case. Маска будет добавляться при вводе символов с клавиатуры. При вставке номера из буфера обмена, добавление маски не предусмотрено.

Мы не будем добавлять автоматическую проверку вводимого знака (цифра или другой символ), так как после ввода с клавиатуры в любом случае требуется зрительная проверка введенного номера.

Также, при редактировании полностью введенного номера, не стоит удалять более 1 цифры, иначе структура маски может будет нарушена.

Маска ввода номера телефона

Простой код для создания маски ввода номера телефона в TextBox в формате «+7(000)000-00-00»:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Private Sub TextBox1_Change()

    With TextBox1

        Select Case Len(.Text)

            Case 1

            ‘После ввода первого знака добавляем перед ним код страны и скобку

            .Text = «+7(« & .Text

            Case 6

            ‘После ввода шестого знака добавляем в конце скобку

            .Text = .Text & «)»

            Case 10, 13

            ‘После ввода десятого и тринадцатого знака добавляем в конце дефис

            .Text = .Text & «-«

            Case 17

            ‘Удаляем семнадцатый знак сразу после его ввода

            .Text = Left(.Text, 16)

        End Select

    End With

End Sub

Строки кода VBA Excel:

Case 17

‘Удаляем семнадцатый знак сразу после его ввода

.Text = Left(.Text, 16)

ограничивают длину строки, вводимой в TextBox, их можно заменить на установку максимальной длины при инициализации формы:

Private Sub UserForm_Initialize()

    TextBox1.MaxLength = 16

End Sub

Если ограничение строки установить при инициализации формы, при ручном редактировании введенного номера можно удалять две цифры без риска нарушить структуру маски.

Маска ввода номера паспорта

Простой код для создания маски ввода номера паспорта в TextBox в формате «00 00 000000»:

Private Sub TextBox2_Change()

    With TextBox2

        Select Case Len(.Text)

            Case 2, 5

            ‘После ввода первого и пятого знака добавляем в конце пробел

            .Text = .Text & » «

            Case 13

            ‘Удаляем тринадцатый знак сразу после его ввода

            .Text = Left(.Text, 12)

        End Select

    End With

End Sub

Если ограничение строки установить при инициализации формы:

Private Sub UserForm_Initialize()

    TextBox2.MaxLength = 12

End Sub

тогда при ручном редактировании введенного номера можно удалять две цифры без риска нарушить структуру маски.

 

Const MaskFiller As String = «__.__.__»  
‘  
Private Sub TextBox1_Enter()  
With Me.TextBox1  
If Not (.Text Like «##.##.##») Then  
.Text = MaskFiller  
End If  
If Len(.Tag) = 0 Then  
Application.SendKeys «{INSERT}»  
.Tag = «-1»  
End If  
End With  
End Sub  

  Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)  
Me.Tag = vbNullString  
End Sub  

  Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)  
Dim iPos As Integer  
Dim iL As Integer  
Dim iR As Integer  
Dim s As String  
With Me.TextBox1  
s = .Text  
iPos = Int(.Tag) ‘Позиция курсора  
Select Case iPos  
Case -1  
iPos = 0  
GoTo SetPos  
Case 0  
If KeyCode < Asc(«0») Or KeyCode > Asc(«3») Then  
GoTo NavigateKey  
Else  
Mid$(s, iPos + 1, 1) = Chr$(KeyCode)  
iPos = 1  
End If  
Case 1  
Select Case Left$(.Text, 1)  
Case «0»  
iL = Asc(«1»)  
iR = Asc(«9»)  
Case «1», «2»  
iL = Asc(«0»)  
iR = Asc(«9»)  
Case «3»  
iL = Asc(«0»)  
iR = Asc(«1»)  
End Select  
If KeyCode < iL Or KeyCode > iR Then  
GoTo NavigateKey  
Else  
Mid$(s, iPos + 1, 1) = Chr$(KeyCode)  
iPos = 3  
End If  
Case 3  
If KeyCode = Asc(«0») Or KeyCode = Asc(«1») Then  
Mid$(s, iPos + 1, 1) = Chr$(KeyCode)  
iPos = 4  
Else  
GoTo NavigateKey  
End If  
Case 4  
If Mid$(Me.TextBox1.Text, 4, 1) = «0» Then  
iL = Asc(«1»)  
iR = Asc(«9»)  
Else  
iL = Asc(«0»)  
iR = Asc(«2»)  
End If  
If KeyCode < iL Or KeyCode > iR Then  
GoTo NavigateKey  
Else  
Mid$(s, iPos + 1, 1) = Chr$(KeyCode)  
iPos = 6  
End If  
Case 6, 7  
If KeyCode < Asc(«0») Or KeyCode > Asc(«9») Then  
GoTo NavigateKey  
Else  
Mid$(s, iPos + 1, 1) = Chr$(KeyCode)  
iPos = IIf(iPos = 6, 7, 0)  
End If  
End Select  
GoTo Repaint  
NavigateKey:  
Select Case KeyCode  
Case 37 ‘Left  
Select Case iPos  
Case 1, 4, 7  
iPos = iPos — 1  
Case 3, 6  
iPos = iPos — 2  
End Select  
Case 39 ‘Right  
Select Case iPos  
Case 0, 3, 6  
iPos = iPos + 1  
Case 1, 4  
iPos = iPos + 2  
End Select  
Case 27 ‘Esc  
iPos = 0  
Case 9 ‘Tab  
Exit Sub  
End Select  
Repaint:  
KeyCode = 0  
.Text = s  
SetPos:  
.SelStart = iPos  
.SelLength = 1  
.Tag = Format$(iPos, «0»)  
End With  
End Sub

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
Private Sub TextBox2_Change()
    Dim t, i, x
        If f = False Then
            f = True
            If Len(TextBox2) > 10 Then
                TextBox2 = Left(TextBox2, 10)
                f = False
                Exit Sub
            End If
            
            x = Replace(TextBox2.Text, ".", "")
            
            If Len(x) > 0 Then
                t = Right(x, 1)
                If IsNumeric(t) Then
                        Select Case t
                        Case 0 To 9
                            TextBox2.Text = form2(x)
                    End Select
                Else
                    TextBox2.Text = Left(x, Len(x) - 1)
                End If
            End If
            f = False
        End If
End Sub
 
Private Function form2(s)
    Dim t, u, x, d, m, y
    Select Case Len(s)
    
        Case 1 'одна цифра
            If s > 3 Then
                form2 = ""
                Exit Function
            End If
            form2 = s
        Case 2
            If s < 32 Then
                form2 = s & "."
            Else
                form2 = Left(s, 1)
            End If
        Case 3
            d = Left(s, 2)
            m = Mid(s, 3, 1)
            If m < 2 Then
                form2 = d & "." & m
            Else
                form2 = d & "."
            End If
        Case 4
            d = Left(s, 2)
            m = Mid(s, 3, 2)
            If m < 13 Then
                form2 = d & "." & m & "."
            Else
                form2 = d & "." & Left(m, 1)
            End If
        Case 5
            d = Left(s, 2)
            m = Mid(s, 3, 2)
            y = Mid(s, 5, 1)
            If y >= 2 Then
                form2 = d & "." & m & "." & y
            Else
                form2 = d & "." & m & "."
            End If
        Case 6
            d = Left(s, 2)
            m = Mid(s, 3, 2)
            y = Mid(s, 5, 2)
            If y > 20 Then
                form2 = d & "." & m & ".20" & y
            Else
                form2 = d & "." & m & "." & y
            End If
        Case 7
            d = Left(s, 2)
            m = Mid(s, 3, 2)
            y = Mid(s, 5, 3)
            form2 = d & "." & m & "." & y
        Case 8
            d = Left(s, 2)
            m = Mid(s, 3, 2)
            y = Mid(s, 5, 4)
            form2 = d & "." & m & "." & y
    End Select
End Function

A combination of integers, strings of characters, or other symbols is used to verify the identity of a user during the authentication process so, that they can access the system. But a password should always remain in a hidden format to prevent it from shoulder spying. Shoulder spying is a practice where a person collects our personal data by spying over our shoulders in Cyber Cafe or ATM. Let’s learn how to hide the password for that we need to mask the password in Excel Input Box.

Steps to Mask Password in VBA Excel Input Box

Follow the further steps to create a masked password in VBA:

Step 1: Press Alt+F11 in the Excel window to get the VBA window. 

Step 2: Select Insert in the Ribbon tab of the VBA code window.

Selecting-insert

Step 3: Then click on UserForm to get the toolbox and user form.

Clicking-on-userform

Step 4: Select CommandButton from Toolbox.

selecting-command-button

And then drag it to the UserForm1 tab.

Dragging-to-userform-1-tab

Step 5: Select TextBox from the toolbox and then drag it to UserForm1.

selecting-testbox

Step 6: Press F4 to get the Properties Window.

Step 7: Change the name of the Text Box to “txtPassword”

Changing-name-of-textbox

Step 8: Now, scroll down the Properties tab of txtPassword to assign a value of asterisk(*) in PasswordChar to create a password mask.

Creating-password-mask

Step 9: In the drop-down box select CommandButton1.

Selecting-commandbutton1

Step 10: Change the name of the CommandButton to CmdInput and Caption name to Submit.

Changing-name-of-commandbutton

Step 11: Change the caption name in the Properties – UserForm1 tab to Password.

changing-caption-name

Step 11: Double-click on Submit button of the Password form.

Clicking-submit

Step 12: Write the following code to see the password in the Message Box.

Code-to-see-password

Unload Me is used to close the form and remove its details from the memory. Now, to run the code press F5.

Step 13: Enter the password which will be hidden in the Excel window

entering-password

Step 14: Click on Submit button so that we can see the password in the message box

Clicking-submit

I have two validation for date and time as below in text boxes:

00/00 00:00;0;0;_

It will take (dd/mm hh:mm) and works fine

But sometimes i put

34/34 56:78 it will take , But it shouldn’t

Date sholdnot go beyond 31, month 12 time 24 and minute 59

Please help

David-W-Fenton's user avatar

asked Jul 16, 2009 at 5:47

1

I just encountered this problem with a Credit Card expiration date field yesterday. I’d stupidly changed 00/0000 as input mask to 00/00, and encountered the problem you’re having. the issue is that if the second pair of digits is a valid date, it will be interpreted as a date and the current year will be supplied tacitly. Thus, if you enter:

  06/09

for Jun 2009, it will be stored as:

  06/09/2009

On the other hand, if you enter:

  06/34

it will be interpreted as

  06/01/1934

So far as I can see, the only way for you to do what you want is to use a 4-digit year.

answered Jul 16, 2009 at 19:37

David-W-Fenton's user avatar

David-W-FentonDavid-W-Fenton

22.8k4 gold badges45 silver badges58 bronze badges

validate the date using IsDate()

Public Function ValidateDate(input As String) As Boolean    

    ValidateDate = IsDate(input)

End Function

this returns a boolean value, True if the input is a valid date string, False if it isn’t. The maximum values are

Day: 31

Month: 12

Hour: 23

Min: 59

Sec: 59

answered Jul 16, 2009 at 5:59

Russ Cam's user avatar

Russ CamRuss Cam

123k33 gold badges202 silver badges266 bronze badges

3

Input masks in Access cannot be restricted to ranges of values, like with a RegExp. Only way to do this is use some validation (which can be done on a keypress if you want to).

answered Jul 16, 2009 at 9:09

Birger's user avatar

BirgerBirger

4,33521 silver badges35 bronze badges

Approach the problem differently. Give the user a calendar to pick from. You could use something like Allen Browne’s Popup Calendar

Disable and lock the text field and you can guarantee that the format is correct.

answered Jul 16, 2009 at 14:57

BIBD's user avatar

BIBDBIBD

15k25 gold badges85 silver badges137 bronze badges

  • Remove From My Forums
  • Question

  • Simple,

    our client want to have a date mask as

    DD/MM/YYYY mask in the text box

    I can validate if the values are fine easily.

    However is there a way to have a mask showing

    __/__/____

    so use can only input numbers on the _ ?

    Normally it works in Access vba but this seems to be nowhere to be found in Excel vba.

Answers

  • Hi
    Okol-Gui,

    You had mentioned that,»I can validate if the values are fine easily.However is there a way to have a mask showing.so use can only input numbers on the _ ?»

    I find one example from old thread and try to modify it as per your requirement.

    You can try to refer code below.

    Dim NewString, MyString, mask As String
    Dim position, pos As Variant
    
    
    
    Private Sub TextBox1_Change()
    If IsNumeric(Right(TextBox1.Text, 2)) And Len(TextBox1.Text) >= 11 Then
        TextBox1.Text = Left(TextBox1.Text, Len(TextBox1.Text) - 1)
    Else
        position = TextBox1.SelStart
        MyString = TextBox1.Text
        pos = InStr(1, MyString, "_")
    If pos > 0 Then
        NewString = Left(MyString, pos - 1)
    Else
        NewString = MyString
    End If
    If Len(NewString) < 11 Then
        TextBox1.Text = NewString & Right(mask, Len(mask) - Len(NewString))
        TextBox1.SelStart = Len(NewString)
    End If
    End If
    If Len(TextBox1.Text) >= 11 Then
         TextBox1.Text = Left(TextBox1.Text, 10)
    End If
    
    
    End Sub
    
    Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Dim strDate As String
    strDate = Me.TextBox1
    If IsDate(strDate) Then
        strDate = Format(CDate(strDate), "DD/MM/YYYY")
        MsgBox strDate
      Else
        MsgBox "Wrong date format"
      End If
    End Sub
    
    Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    position = TextBox1.SelStart
    If KeyCode = 8 Then
        TextBox1.Text = mask
    End If
    End Sub
    Private Sub UserForm_Initialize()
    TextBox1.SelStart = 0
    mask = "__/__/____"
    TextBox1.Text = mask
    End Sub
    

    Output:

    Reference:

    Text Box With Input Mask

    Disclaimer: This response contains a reference to a third party World Wide Web site. Microsoft is providing this information as a convenience to you. Microsoft does not control these sites and has not tested any software or information found on these sites;
    therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure
    that you completely understand the risk before retrieving any software from the Internet.

    Regards

    Deepak


    MSDN Community Support
    Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to
    MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by

      Tuesday, April 10, 2018 1:58 PM

title keywords f1_keywords ms.prod api_name ms.assetid ms.date

TextBox.InputMask Property (Access)

vbaac10.chm11046

vbaac10.chm11046

access

Access.TextBox.InputMask

a705c2a4-ff2f-74d1-4a7c-1eade3b00ae8

06/08/2017

TextBox.InputMask Property (Access)

You can use the InputMask property to make data entry easier and to control the values users can enter in a text boxcontrol. Read/write String.

Syntax

expression. InputMask

expression A variable that represents a TextBox object.

Remarks

Input masks are helpful for data-entry operations such as an input mask for a Phone Number field that shows you exactly how to enter a new number: (__) . It is often easier to use the Input Mask Wizard to set the property for you.

The InputMask property can contain up to three sections separated by semicolons (;).

Section Description
First Specifies the input mask itself; for example, !(999) 999-9999. For a list of characters you can use to define the input mask, see the following table.
Second Specifies whether Microsoft Access stores the literal display characters in the table when you enter data. If you use 0 for this section, all literal display characters (for example, the parentheses in a phone number input mask) are stored with the value; if you enter 1 or leave this section blank, only characters typed into the control are stored.
Third Specifies the character that Microsoft Access displays for the space where you should type a character in the input mask. For this section, you can use any character; to display an empty string, use a space enclosed in quotation marks (» «).
In Visual Basic you use a string expression to set this property. For example, the following specifies an input mask for a text box control used for entering a phone number:
Forms!Customers!Telephone.InputMask = "(###) ###-####"

When you create an input mask, you can use special characters to require that certain data be entered (for example, the area code for a phone number) and that other data be optional (such as a telephone extension). These characters specify the type of data, such as a number or character, that you must enter for each character in the input mask.

You can define an input mask by using the following characters.

Character Description
0 Digit (0 to 9, entry required, plus [+] and minus [?] signs not allowed).
9 Digit or space (entry not required, plus and minus signs not allowed).
# Digit or space (entry not required; spaces are displayed as blanks while in Edit mode, but blanks are removed when data is saved; plus and minus signs allowed).
L Letter (A to Z, entry required).
? Letter (A to Z, entry optional).
A Letter or digit (entry required).
a Letter or digit (entry optional).
&; Any character or a space (entry required).
C Any character or a space (entry optional).
. , : ; — / Decimal placeholder and thousand, date, and time separators. (The actual character used depends on the settings in the Regional Settings Properties dialog box in Windows Control Panel).
< Causes all characters to be converted to lowercase.
> Causes all characters to be converted to uppercase.
! Causes the input mask to display from right to left, rather than from left to right. Characters typed into the mask always fill it from left to right. You can include the exclamation point anywhere in the input mask.
|Causes the character that follows to be displayed as the literal character (for example, A is displayed as just A).

Note Setting the InputMask property to the word «Password» creates a password-entry control. Any character typed in the control is stored as the character but is displayed as an asterisk (*). You use the Password input mask to prevent displaying the typed characters on the screen.

When you type data in a field for which you’ve defined an input mask, the data is always entered in Overtype mode. If you use the BACKSPACE key to delete a character, the character is replaced by a blank space.

If you move text from a field for which you’ve defined an input mask onto the Clipboard, the literal display characters are copied, even if you have specified that they not be saved with data.

Note Only characters that you type directly in a control or combo box are affected by the input mask. Microsoft Access ignores any input masks when you import data, run an action query, or enter characters in a control by setting the control’s Text property in Visual Basic or by using the SetValue action in a macro.

When you’ve defined an input mask and set the Format property for the same field, the Format property takes precedence when the data is displayed. This means that even if you’ve saved an input mask, the input mask is ignored when data is formatted and displayed. The data in the underlying table itself isn’t changed; the Format property affects only how the data is displayed.

The following table shows some useful input masks and the type of values you can enter in them.

Input mask Sample values
(000) 000-0000 (206) 555-0248
(999) 999-9999 (206) 555-0248
( ) 555-0248
(000) AAA-AAAA (206) 555-TELE
#999 ?20
2000
>L????L?000L0 GREENGR339M3
MAY R 452B7
>L0L 0L0 T2F 8M4
00000-9999 98115-
98115-3007
>L<?????????????? Maria
Brendan
SSN 000-00-0000 SSN 555-55-5555
>LL00000-0000 DB51392-0493

See also

Concepts

TextBox Object

Like this post? Please share to your friends:
  • Масло гидравлическое минеральное mobil dte 10 excel 32
  • Масло гидравлическое mobil dte 10 excel 32 характеристики
  • Маска ввода даты для excel
  • Маска ввода в excel что это
  • Маска ввода в excel 2007