0
votes

I'm creating a Form in Microsoft Word. I have several 'Text form fields' some of which I want to restrict so users can only enter numbers. I don't understand why Microsoft gives you the option to change the 'Type' to 'Number' when that still allows any value to be input. Since that seems to be the case I have turned to VBA.

I'm trying to run a macro when the user exits one of these fields, to make sure the input is valid. I would rather not create a new macro for each field I want to restrict to numeric.

I think my problem is that I don't know how to get the result of the current field. I could create a different macro for each field, and get the result by specifying its name explicitly, but it seems like a smarter way would exist.

Here's what I have so far.

Sub validateNumericFields()
 'Check to see if the value in the current field is numeric
 'If it is not, send a message to the user, and set value to default value

 If IsNumeric(Selection.Fields(1).Result) = False Then
   MsgBox "You must enter a valid number.", vbExclamation
   Selection.Fields(1).Result = Selection.Fields(1).TextInput.Default
 End If
End Sub
1
Before we can discuss your problem we need to be sure we understand it. You appear to be "mixing and matching" terminology, which makes it difficult to be certain what you have. A "UserForm" is a VBA form; it has "text box controls". A Word document can be protected as a form and has "text form fields". Is it correct that you have the latter, not the former?Cindy Meister
Yes, the latter is correct. I have not created the input fields using VBA. I have inserted "Legacy Text Form Fields" into a Word document and will restrict editing so only the form fields can be edited by users.Jake
Which version of Word are you using? When I set a text box form field's type to Number it won't let me type text into it. Text is turned into a 0 (zero).Cindy Meister
I have Word 2010. If I use the tab key to navigate to the next field then the text gets turned to a zero, if the type is set to Number. But, if I use my cursor to navigate to an alternate field then the text remains.Jake
Could you be more specific what you mean by "use my cursor"?Cindy Meister

1 Answers

1
votes

There are various ways to get the "name" of a form field, since this is also a bookmark. The FormField object does have a Name property, but I can't get to it from the Selection object available when OnExit runs. But I can get the bookmark name, so:

Sub validateNumericFields()
  'Check to see if the value in the current field is numeric
  'If it is not, send a message to the user, and set value to default value
  Dim ff As word.FormField
  Set ff = ActiveDocument.FormFields(Selection.Bookmarks(1).Name)

  If IsNumeric(ff.Result) = False Then
     MsgBox "You must enter a valid number.", vbExclamation
     ff.Result = ff.TextInput.Default
  End If
End Sub