MS Word Document Form - Check Value of Text Form Field on Exit

北城以北 提交于 2020-01-07 03:22:48

问题


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:


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


来源:https://stackoverflow.com/questions/35093978/ms-word-document-form-check-value-of-text-form-field-on-exit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!