我对编程很陌生,我试图将表单字段的内容复制到同一个Word文档中的另一个表单字段中,如下所示:
Sub Copyfield()
Dim Temp As String
Temp = ActiveDocument.FormFields("Field1").Result
ActiveDocument.FormFields("Field2").Result = Temp
End Sub我的问题是,我的"Field1“是一个超过255个字符的文本,这似乎是一个”结果“的问题。我知道这里有一个非常相似的话题:Passing MS-Access string >255 characters to MS-Word field,但我仍然没有50 %的声誉来评论这个帖子。
有谁能帮我理解如何在代码中实现更改吗?
发布于 2016-02-23 19:17:30
这里有一种可能性。由于我没有您的环境,所以我更容易在文档中测试文本,而不是其他包含如此多内容的表单字段。您需要相应地调整代码。
关键是要在表单字段中获得选择,这样它就不会碰到“保护屏障”。仅使用FormField.Select就会将焦点放在字段的开头,VBA将其视为“受保护的”。向右移动一个字符可以纠正这一点,然后可以将长文本分配给所选内容。但是这个领域需要有内容。
因此,我的代码所做的是“切分”文本中进入表单字段的第一个单词。这足够短,可以将结果属性赋值,并允许选择向右移动。然后剩下的部分--长文本--可以分配给所选内容。
您可能希望将整个FormField.Result分配给一个字符串变量,然后操作该字符串。
Sub WriteLongTextToFormField()
Dim ffld As word.FormField
Dim doc As word.Document
Dim rng As word.Range
Dim s1 As String, s2 As String
Set doc = ActiveDocument
'Get the long text
Set rng = doc.Range(doc.Paragraphs(1).Range.Start, doc.Paragraphs(6).Range.End)
'Split off a bit to go into FormField.Result
s1 = rng.Words(1)
rng.MoveStart wdWord, 1
'The rest of the long text, to be assigned to Selection.Text
s2 = rng.Text
Set ffld = doc.FormFields("Text1")
ffld.result = s1
ffld.Select
Selection.MoveRight wdCharacter, 1
Selection.Text = s2
End Sub发布于 2016-02-24 12:28:51
好吧,在疯狂的边缘呆了3天后,终于在辛迪·迈斯特的帮助下(还有一些严肃的个人挖掘),我成功了。也许这对你们来说没什么大不了的,但是相信我,这就像看到了矩阵代码中的一切(从电影里的家伙到电影)。
我想发布并分享它,因为我试图在互联网的每一个角落找到它,而我却无法找到它。因此,希望它能对另一个编程文盲/哑巴人(就像我自己)有用。
以下是代码:
Sub CopyField()
Dim ffld As Word.FormField
Dim doc As Word.Document
Dim rng As String
Dim s1 As String, s2 As String
Set doc = ActiveDocument
'Get the long text
rng = ActiveDocument.FormFields("Field1").Result
'Split off a bit to go into FormField.Result
s1 = Left(rng, 4) 'Keeps the first 4 characters of the rng string starting from left to right this can be adapted
'The rest of the long text, to be assigned to Selection.Text
s2 = Mid(rng, 5) 'Starting from the 5th character from the left keeps the rest of the string
Set ffld = doc.FormFields("Field2")
ffld.Result = s1
ffld.Select
Selection.MoveRight wdCharacter, 1
ActiveDocument.Unprotect 'Unprotects the document!
Selection.Text = s2
ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True 'Protects the document again!
ActiveDocument.Bookmarks("Field1").Select ' "Sends cursor" back to Field1
End Sub代码的大部分是由@Cindy Meister..。我只是根据我的情况调整它,我有两个表单字段,而不是段落。我还必须添加一些行,以便在某个时候解除对文档的保护,以便使其正常工作(询问Pros的原因),并在处理后返回到"Field1“(这是一些页面)的最后指令。最后,给我的傻伙伴们一个提示:我在"Field1“属性上添加了宏"on”,以实现过程的自动化。
再次感谢辛迪,我希望你能在我黑暗的编程时刻再一次帮助我!(请做)
:)
https://stackoverflow.com/questions/35582772
复制相似问题