允许用户在word vba宏中选择文本

发布于 2024-07-16 10:13:46 字数 363 浏览 1 评论 0原文

在 VBA for Word 2007 中,我希望能够打开文档、突出显示文本部分并将这些部分替换为链接到文档变量的字段。 该过程将是:

  1. 打开文档。
  2. 选择文本。
  3. 从列表中选择文档变量。
  4. 插入链接到所选文档变量的字段。
  5. 根据需要重复步骤 1-4。

无法事先知道要选择的文本是什么,或者哪个文档变量将链接到哪个字段,或者这些步骤将重复多少次。

只有微软才能让用户在运行时进行选择并将此选择传递回子例程这一最绝对基本、最简单的任务变得如此曲折和超现实。 我花了两天时间试图解决这个问题。 如果有人能帮忙,我将以你的名字命名我的下一个孩子。

In VBA for Word 2007, I want to be able to open a document, highlight sections of text and replace those sections with fields linked to a docvariables. The process would be:

  1. Open document.
  2. Select text.
  3. Select docvariable from list.
  4. Insert field linked to selected docvariable.
  5. Repeat steps 1-4 as required.

There is no way to know beforehand what the text to be selected is or which docvariable is going to be linked to which field or how many times these steps are going to be repeated.

Only with Microsoft could the most absolutely fundamental, simple task of allowing the user to make a selection at run-time and pass this selection back to sub-routine be so tortuous and surreal. I have spent 2 days trying to figure this out. If anyone can help, I will name my next child after you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鹿港巷口少年归 2024-07-23 10:13:46

我认为“曲折、超现实”是一种误解。

创建一个带有下拉列表的小表单(例如,名为“selVarName”),可让您选择所有可用的文档变量名称。 将表单链接到快速访问工具栏中的自定义按钮。

单击此表单中的“确定”后,请执行以下操作:

Private Sub btnOK_Click()
  Dim v As Word.Variable
  Dim n As String

  n = Me.selVarName.Value
  With Selection
    For Each v In .Document.Variables
      If v.Name = n Then v.Delete: Exit For
    Next v
    .Document.Variables.Add n, .Range.Text
  End With
End Sub

这已经具有附加功能。 例如,您可以进行其他检查,例如“未选择文本”。

I think "tortuous and surreal" is a misconception.

Create a small form with a dropdown (named "selVarName", for example) that lets you select all document variable names available. Link the form to a custom button in the Quick Access Toolbar.

Upon clicking "OK" in this form do something like this:

Private Sub btnOK_Click()
  Dim v As Word.Variable
  Dim n As String

  n = Me.selVarName.Value
  With Selection
    For Each v In .Document.Variables
      If v.Name = n Then v.Delete: Exit For
    Next v
    .Document.Variables.Add n, .Range.Text
  End With
End Sub

And this has bells and whistles already. You can do additional checking like "no text selected", for example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文