vba - 微软字。如何将确切的字符串复制到另一个文档?
问题描述
我需要复制一个始终以精确字符串“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)
谢谢!
解决方案
这段代码中有很多假设,但首先尝试一下。
它假定源文档的格式与您描述的一样,并且目标文档中存在一个 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
推荐阅读
- python - 在 Android 中使用 Keras 模型进行分类
- graphql - 使用 Gatsby 的 Markdown 帖子中的特色图像的绝对路径
- python - 基于混合单词和数字的多列对数据框进行排序
- c++ - 实现接口时没有遇到断点
- windows - 使用 shell 命令将 docker 的 VM 内存大小设置为 6GB
- powershell - 确定用户是否可以在 Windows 更新后进行 RDP
- python - 如何使用每个模块的测试数据初始化数据库?Pytest-django
- c# - 使用字符串作为 Id 的测试详细信息操作
- java - 使用 Jackson 将节点反序列化为基于根名称的子类型
- javascript - 将 Python API 调用转换为 Javascript 和 HTML 时未获取数据