MS Word 文档表单 - 在退出时检查文本表单字段的值 [英] MS Word Document Form - Check Value of Text Form Field on Exit

查看:52
本文介绍了MS Word 文档表单 - 在退出时检查文本表单字段的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Microsoft Word 中创建表单.我有几个文本表单字段",我想限制其中的一些,以便用户只能输入数字.我不明白为什么微软会在仍然允许输入任何值的情况下为您提供将类型"更改为数字"的选项.既然如此,我就转向了 VBA.

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.

这是我目前所拥有的.

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

推荐答案

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

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

这篇关于MS Word 文档表单 - 在退出时检查文本表单字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆