Dear Rick,
Give this event code a try...
Code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Cell As Range
If Not Intersect(Target, Range("B4:B2503")) Is Nothing Then
For Each Cell In Intersect(Target, Range("B4:B2503"))
If Cell.Value Like "*[!A-Za-z0-9-]*" Then
MsgBox "You have at least one invalid character in cell " & _
Cell.Address(0, 0) & ". Please enter your value " & _
"again and this time remember that only letters, " & _
"digits and/or dashes are allowed!", vbCritical
Application.Undo
Exit Sub
End If
Next
End If
End Sub
HOW TO INSTALL Event Code
------------------------------------
If you are new to event code procedures, they are easy to install. To install it, right-click the name tab at the bottom of the worksheet that is to have the functionality to be provided by the event code and select "View Code" from the popup menu that appears. This will open up the code window for that worksheet. Copy/Paste the event code into that code window. That's it... the code will now operate automatically when its particular event procedure is raised by an action you take on the worksheet itself. Note... if you are using XL2007 or above, make sure you save your file as an "Excel Macro-Enabled Workbook (*.xlsm) and answer the "do you want to enable macros" question as "yes" or "OK" (depending on the button label for your version of Excel) the next time you open your workbook.
Dear Rick,
I saw the above code which is very closely matches to my requirement. But I would like to customize your code a bit to meet my exact requirement. My requirement is to allow only numeric, alphabets and some specific special characters such as $ & * ( ) < > / \ -
0-9 – Allowed
a-z and A-Z - Allowed
$ & * ( ) < > / \ - Allowed
If user enters except the above-mentioned characters in worksheet, then I want Msg box to alert the user and clear the cell.
I tried modifying the code as mentioned below but it doesn’t work.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Cell As Range
If Not Intersect(Target, Range("A:D")) Is Nothing Then
For Each Cell In Intersect(Target, Range("A:D"))
If Cell.Value Like "*[!A-Za-z0-9$ & *()<>/\]*" Then
MsgBox "You have at least one invalid character in cell " & _
Cell.Address(0, 0) & ". Please enter your value " & _
"again and this time remember that only letters, " & _
"digits and/or dashes are allowed!", vbCritical
Application.Undo
Exit Sub
End If
Next
End If
End Sub
Could you please help me with the VBA code? I have been searching for such VBA code to allow only specific special characters in VBA code but none of them are useful. I can’t use data validation as I’m using the same cell range for something else.
Please help. Thank in advance!