简体   繁体   中英

How to disable special characters in excel sheet using VBA macro

Hi my main aim is to disable entering special characters by user after he open an excel sheet using a macro in VBA

I tried how to do it. I found one method for one character.

Sub Disable_Keys()
    Dim KeysArray As Variant
    Dim Key As Variant

    KeysArray = Array("@", "!", "~")

    'Disable the StartKeyCombination key(s) with every key in the KeysArray
    For Each Key In KeysArray
        Application.OnKey Key, "myMsg"
    Next Key
End Sub

Sub myMsg()
    MsgBox "All keys are valid characters"
End Sub

There is a problem with this one i am only disable two keys in that array. If i add 3 one like "~". It's not working for that key.

If you have any other solutions also please help me.

Your code works as written.

The issue is that the OnKey method interprets "~" as the Enter key. To have the tilde actually effected use, "{~}" instead. Here's documentation on the OnKey method.

To be explicit, use this: KeysArray = Array("@", "!", "{~}") .

Edit: Due to the comments, I just want to add something that you should do.

You'll want to move the code you listed to the ThisWorkBook module in the Workbook_Open event. You should also include a method such as this:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
        Dim KeysArray As Variant
        Dim Key As Variant

        KeysArray = Array("@", "!", "{~}")

        'Disable the OnKey settings with every key in the KeysArray
        For Each Key In KeysArray
            Application.OnKey Key, ""
        Next Key
End Sub

If you do not include this method, your keys in KeysArray will attempt to run the MyMsg sub until you close the Application, even after the workbook has been closed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM