In a textbox, prevent certain typed characters from appearing. (Word and VBA)

Posted on 2011-10-19
Last Modified: 2012-08-13
    Using VBA with Word, I have a textbox and want to block certain characters typed so that they do not appear in the text. Specifically I want to put into the KeyPress Sub code that will intercept an apostrophe, check the letter to the left of where the apostrophe will go in the text, and if it is an “e” I want to replace that character with an “é”. In other words, I want to change “e'” to “é”. I have code that will do that now if the insertion point is at the end of the words being written. I hope soon to be able to do that when the insertion point is elsewhere in the text. What I cannot figure out is that after I have made the change, how do I get the apostrophe not to appear after the revised letter?

     Thanks for any help. If I can get this solution, I can simplify the typing of accented letters in a textbox.

Question by:JohnRobinAllen
    LVL 17

    Expert Comment

    I did do something like this quite a while ago, to prevent certain characters being entered - I think the thing is to change KeyAscii to 0 if it's a character you don't want to enter - this is my validation code.  I'm not sure exactly what code you have to enter an accented e, but this may help:
    Private Sub mctlTextBox_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
        Const cstrNumbers As String = "0123456789"
        Const cstrNumbersPlus As String = "+-."
        Const cstrAlpha As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        Const cstrSpace As String = " "
        Dim strValid As String
            Select Case meValidation
            Case NumberOnly
                strValid = cstrNumbers
            Case NumberPlusMinusDecimal
                strValid = cstrNumbers & cstrNumbersPlus
            Case Alpha
                strValid = cstrAlpha
            Case AlphaSpace
                strValid = cstrAlpha & cstrSpace
            Case AlphaNumeric
                strValid = cstrAlpha & cstrNumbers
            Case AlphaNumericSpace
                strValid = cstrAlpha & cstrNumbers & cstrSpace
            Case Else
                Exit Sub
        End Select
        If InStr(1, strValid, Chr$(KeyAscii)) = 0 Then
            KeyAscii = 0
        End If
    End Sub

    Open in new window

    LVL 17

    Accepted Solution

    Just playing quickly with that idea, this seems to do what you want (obviously just for accented lower case e, but the principle should be the same for others:
    Private Sub tbName_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
        Dim x As Long
        Dim strTemp As String
        If Chr$(KeyAscii) = "'" Then
            x = Me.tbName.SelStart
            If x > 0 Then
                strTemp = Me.tbName.Value
                If Mid$(strTemp, x, 1) = "e" Then
                    Mid(strTemp, x, 1) = Chr$(&HE9)
                    Me.tbName.Value = strTemp
                    Me.tbName.SelStart = x
                    KeyAscii = 0
                End If
            End If
        End If
    End Sub

    Open in new window


    Author Closing Comment

    I certainly wish I knew more about VBA, but your solution works. The first code used the term meValidation, and I could not find anything about that in MS Help. What I needed was to know how to kill a key that was pressed, and setting the KeyAscii to zero is the solution.
         The second bit of code was something I needed a couple of months ago. I finally encoded that and posted it a couple of minutes ago in another query. My solution was quite close to the one you submitted. I still have a few kinks to smooth out, but I am hopeful they will get solved soon.
         Thanks for all your help. You gave a lot more than I had asked for, and I am grateful.
    LVL 17

    Expert Comment

    Yes - sorry, my first example is a snippet from a larger piece of code I have developed to get some sort of proper validation for VBA text boxes.  meValidation is just an enum I have defined to enumerate different types of validation and the idea is that for each type, only the valid characters can be entered.  In fact I don't use validation that strict very often, but there is other code to do numeric only and date checking which is often useful.

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    Introduction This tutorial provides instructions on how to properly format your Word document using the inbuilt tools provided. The benefits of using these tools means your documents are more accessible and easily portable to other applications an…
    This is written from a 'VBA for MS Word' perspective, but I am sure it applies to most other MS Office components where VBA is used.  One thing that really bugs me is slow code, ESPECIALLY when it's mine!  In programming there are so many ways to…
    The viewer will learn how to make their project stand out over others by learning how to change colors and shapes, add spaces, change directions, and add bullets to their charts.
    Learn how to make your own table of contents in Microsoft Word using paragraph styles and the automatic table of contents tool. We'll be using the paragraph styles in Word’s Home toolbar to help you create a table of contents. Type out your initial …

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now