【发布时间】:2021-05-04 21:52:21
【问题描述】:
在我的 Word VBA 项目中,我在 ContentControl(s) 方面遇到了很多困难。 有许多内容控制文本字段都具有相同的名称(它们具有相同的名称,因为一开始所需字段的总数是未知的,所以我根据需要多次复制和粘贴这些字段)。现在我想遍历内容控制字段并根据各个项目的索引更改字段的名称(例如文档中的第一个字段=“One”,文档中的第二个字段=“two”等等) .
但是,正如其他线程中提到的,内容控制元素的索引与其在文档中的位置不对应(我不知道它对应于什么)。 因此,我没有按顺序排列字段,而是得到例如"四" --> "一" --> "三" --> "二"(或任何其他可能的组合)。
字段的内容来自用户窗体文本框。文本框被命名为 Text_Box_1 到 Text_Box_4:
Private Sub Test() 'Note: The actual code is more complex, this is just to demonstrate my problem.
Dim i As Integer
UserForm1.TextBox1 = "one"
UserForm1.TextBox2 = "two"
UserForm1.TextBox3 = "three"
UserForm1.TextBox4 = "four"
For i = 1 To 4 - 1 'Since there are four text boxes in the UserForm in this example, the text snippet containing the text field gets copied and pasted three times; Note: Here the number of textboxes is pre-determined and fixed, in the actual project, it is variable.
ActiveDocument.Bookmarks(Index:="Copy").Range.Copy '
ActiveDocument.Bookmarks(Index:="Paste").Range.Paste
Next i
For i = 1 To 4 'This code is supposed to loop through the four content control text fields and insert text from the corresponding UserForm text box. However, content control text field 1, unfortunately does no correspond to UserForm.TextBox1 for some reason.
ActiveDocument.SelectContentControlsByTitle("Number").Item(i).Range.Text = UserForm1.Controls("TextBox" & i)
Next i
End Sub
有没有办法以正确的顺序命名内容控制字段? 如果不是,那将是实现我的目标的另一种方法。 我认为遗留文本字段不是一种选择,因为必须保护文档;我没有过多地研究 ActiveX 文本字段。文本框(形状)可能是另一种选择,但它们可能有自己的缺点。
内容控制字段的行为如此怪异,而看似非常简单直接的事情却如此复杂(至少对我而言),这真的令人沮丧。
编辑:修正了标题中的错字。
【问题讨论】:
-
给定标题的内容控制索引 #s 根据插入的顺序分配。如果为它们分配标签,则可以保持标题不变并测试标签值。您可能还感兴趣:msofficeforums.com/word-vba/…、msofficeforums.com/word-vba/…、&msofficeforums.com/word-vba/…
-
您确定订单吗?每次执行代码时我都会得到不同的顺序,所以它似乎不是插入的顺序。我会看看你的链接。
标签: vba ms-word word-contentcontrol