MS Word文档表单 - 在退出时检查文本表单字段的值

时间:2016-01-29 21:00:53

标签: vba ms-word word-vba

我正在Microsoft Word中创建一个表单。我有几个'文本表单字段',其中一些我想限制,所以用户只能输入数字。我不明白为什么微软允许你选择将'Type'更改为'Number',当仍然允许输入任何值时。由于这似乎是我转向VBA的情况。

我正在尝试在用户退出其中一个字段时运行宏,以确保输入有效。我宁愿不为我想限制为数字的每个字段创建一个新的宏。

我认为我的问题是我不知道如何获得当前字段的结果。我可以为每个字段创建一个不同的宏,并通过明确指定其名称来获得结果,但似乎存在更聪明的方式。

这是我到目前为止所拥有的。

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 个答案:

答案 0 :(得分:1)

有多种方法可以获得" name"表单字段,因为这也是一个书签。 FormField对象确实有一个Name属性,但是当OnExit运行时,我无法从Selection对象中获取它。但我可以得到书签名称,所以:

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