查找并复制包含 1 行的表格

查找并复制包含 1 行的表格

我有一个包含多个表格的 Word 文档,我想复制并放入只有 1 行的表格到新文档中。我有 VBA 代码来将所有表格从源文档复制到新文档,但只想复制只有 1 行的表格。这是我目前拥有的代码(来源:WordTips,The Macros ed 9)

Sub CopyTables()
  Dim Source As Document
  Dim Target As Document
  Dim tbl As Table
  Dim tr As Range
Set Source = ActiveDocument
Set Target = Documents.Add

For Each tbl In Source.Tables
Set tr = Target.Range
tr.Collapse wdCollapseEnd
tr.FormattedText = tbl.Range.FormattedText
tr.Collapse wdCollapseEnd
tr.Text = vbCrLf
Next
End Sub

答案1

使用Count的属性tbl来查明Rows您有多少个。

Option Explicit

Sub CopyTables()
    Dim Source As Document
    Dim Target As Document
    Dim tbl As Table
    Dim tr As Range
    Set Source = ActiveDocument
    Set Target = Documents.Add

    For Each tbl In Source.Tables
        If tbl.Rows.Count = 1 Then
            Set tr = Target.Range
            tr.Collapse wdCollapseEnd
            tr.FormattedText = tbl.Range.FormattedText
            tr.Collapse wdCollapseEnd
            tr.Text = vbCrLf
        End If
    Next
End Sub

相关内容