首页 > 解决方案 > 微软字。如何将确切的字符串复制到另一个文档?

问题描述

我需要复制一个始终以精确字符串“p1”开头的单词,然后将该单词复制到另一个文档中的表格中。然后总是在确切的字符串之间复制一个句子并将该句子复制到同一个表中。

让我用一个例子来解释。以下是我需要复制的几段文字:

variable labels p1consid 'SDQ: Considerate (Parent1)'.

variable labels p1restles 'SDQ: Restless (Parent1)'.

variable labels p1somatic 'SDQ: Headache, stomach-ache (Parent1)'.

因此,“p1consid”应该转到表的第 1 列,而“SDQ:Considerate (Parent1)”应该转到同一表的第 2 列。

第 1 栏

p1consid

p1restles

p1somatic

第 2 栏

SDQ: Considerate (Parent1)

SDQ: Restless (Parent1)

SDQ: Headache, stomach-ache (Parent1)

谢谢!

标签: vbams-word

解决方案


这段代码中有很多假设,但首先尝试一下。

它假定源文档的格式与您描述的一样,并且目标文档中存在一个 2 列表。该表是第一个表,没有标题行,它是单行表。

Sub CopyStrings()
Dim docSrc As word.Document, docDst As word.Document
Dim rng As word.Range, tbl As word.Table, tRng As word.Range
Set docSrc = Documents.Open("Your Source Doc")
Set docDst = Documents.Open("Your Destination Doc")
Set rng = docSrc.Content
Set tbl = docDst.Content.Tables(1)
With rng.Find
    .ClearFormatting
    .Format = False
    .Forward = True
    .Text = "p1"
    .Wrap = wdFindStop
    .Execute
    Do While .found
        rng.MoveEnd word.WdUnits.wdWord, Count:=1
        Set tRng = tbl.rows(1).Cells(1).Range
        tRng.MoveEnd word.WdUnits.wdCharacter, Count:=-1
        tRng.Collapse word.WdCollapseDirection.wdCollapseEnd
        tRng.Text = rng.Text & vbCr
        rng.Collapse word.WdCollapseDirection.wdCollapseEnd
        rng.MoveStart word.WdUnits.wdWord, Count:=1
        rng.MoveStart word.WdUnits.wdCharacter, Count:=1
        rng.MoveEnd word.WdUnits.wdParagraph, Count:=1
        Set tRng = tbl.rows(1).Cells(2).Range
        tRng.MoveEnd word.WdUnits.wdCharacter, Count:=-1
        tRng.Collapse word.WdCollapseDirection.wdCollapseEnd
        tRng.Text = rng.Text
        rng.Collapse word.WdCollapseDirection.wdCollapseEnd
        .Execute
    Loop
End With
End Sub

推荐阅读