Macro needed to verify just 4 numbers

C

charlie6067

I've read several postings but just can't seem to get it to work.

I have several Word 97 fields and want to validate on exit that only
numbers 0, 1, 4, 9 were typed. Otherwise, a message box will displays
with instructions, and the cursor will return to that field so it can
be corrected. Seems very simple but I'm not having any success.

Thanks for your help,
Charlie
charlie6067
 
G

Greg Maxey

Charlie,

You question isn't very clear. Do you mean the field can only contain 1
number which must be either a 0, 1, 4 or 9? Or must be 0149? Or must be
four characters long and each character must be a 0, 1, 4, or 9? Or any
length as long as each character is a 0, 1, 4, or 9?

Assuming the last here is a some code that should work. Run the AonExit
from the field you want to validate and the AonEntry from all other fields.

Option Explicit
Private Bookmark As String
Private bInvalid As Boolean
Public Sub AOnExit()
Dim chkStr As String
Dim i As Long
bInvalid = False
With GetFieldData
Bookmark = .Name
chkStr = .Result
For i = 1 To Len(chkStr)
If Mid(chkStr, i, 1) <> 4 And Mid(chkStr, i, 1) <> 9 _
And Mid(chkStr, i, 1) <> 1 And Mid(chkStr, i, 1) <> 0 Then
MsgBox "Foul"
bInvalid = True
Exit Sub
End If
Next
End With
End Sub
Public Sub AOnEntry()
If bInvalid Then
ActiveDocument.FormFields(Bookmark).Select
Bookmark = ""
End If
End Sub
Private Function GetFieldData() As Word.FormField
With Selection
If .FormFields.Count = 1 Then
'CheckBox or DropDown
Set GetFieldData = .FormFields(1)
ElseIf .FormFields.Count = 0 And .Bookmarks.Count > 0 Then
Set GetFieldData = ActiveDocument.FormFields _
(.Bookmarks(.Bookmarks.Count).Name)
End If
End With
End Function
 
J

Jezebel

Suggest a cleaner way to test --

Dim pIndex as long
Const pVALIDCHARS as string = "0149"

for pIndex = 1 to len(pVALIDCHARS)
chkstring = replace(chkString, mid(pVALIDCHARS, pIndex, 1), "")
next

if len(chkstring) > 0 then
... contains bad characters
end if
 
C

charlie6067

Greg and Jezebel - A million thanks for your help and quick coding. It
works great! I've felt for many years that people can learn more from
these forums than anywhere else. And, people like you make these forums
the high quality that they are.

Thanks again,
Charlie
charlie6067
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top