首页 文章

在Word VBA中查找表 Headers

提问于
浏览
4

我想自动从Word文档的表中提取数据 . 我通过迭代VBA中的所有表来完成此操作 . 即

For Each tbl In wdDoc.Tables
Next

是否可以找到给定表格的 Headers ?即文件有“表3:”,然后是表格 .

请注意,并非文档中的所有表都有 Headers ,因此 Headers 中的表编号与文档表枚举不同 .

任何帮助表示赞赏 .

1 回答

  • 6

    遗憾的是,表格 Headers 实际上并未通过Word对象模型与其表格相关联 . 创建表格 Headers 时,只是文本放在单独的段落对象中 .

    So, the short answer is that no, there is no good way to find the caption for a given table.

    我写了一些可能对你有用的代码 . 它基本上遍历文档中的所有Paragraph对象,并查找“Caption”样式(或者,您可以查找格式为“Table#:”的文本,或者您想要的任何内容) . 如果下一个段落包含表格,它会将 Headers 的文本放入找到的第一个表格的第一个单元格中 .

    Dim p As Paragraph
        Dim lastParagraphWasCaption As Boolean
        Dim lastCaptionText As String
        lastParagraphWasCaption = False
    
        For Each p In ActiveDocument.Paragraphs
            If lastParagraphWasCaption And p.Range.Tables.Count > 0 Then
                p.Range.Tables(1).Cell(1, 1).Range.Text = lastCaptionText
            End If
    
            If p.Range.Style = "Caption" Then
                lastParagraphWasCaption = True
                lastCaptionText = p.Range.Text
            Else
                lastParagraphWasCaption = False
            End If
        Next
    

    请记住,这只是一个如何将 Headers 与其表格绑定在一起的示例 . 有了这个说法,它不是一个非常可靠的方法和 I would not recommend using it unless you absolutely need to 因为表格 Headers 可能没有 Headers 样式,或者可能在不是 Headers 的内容上有字幕样式等 .

相关问题