在 Word VBA 中查找表格标题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8434253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding table caption in Word VBA
提问by Adriaan
I want to automatically extract data from tables of a Word document. I do this by iterating over all tables in VBA. I.e.
我想从 Word 文档的表格中自动提取数据。我通过迭代 VBA 中的所有表来做到这一点。IE
For Each tbl In wdDoc.Tables
Next
Is it possible to find the caption for a given table? i.e. the document has "Table 3:" and then the table.
是否可以找到给定表格的标题?即文档有“表 3:”,然后是表。
Note that not all the tables in the document have got a caption and therefore the table numbers in captions are different than the document table enumeration.
请注意,并非文档中的所有表格都有标题,因此标题中的表格编号与文档表格枚举不同。
Any help is appreciated.
任何帮助表示赞赏。
回答by Drew Gaynor
Unfortunately, table captions are not actually associated with their tables through the Word Object Model. When a table caption is created, it is just text placed in a separate Paragraph object.
不幸的是,表格标题实际上并没有通过 Word 对象模型与其表格相关联。创建表格标题时,它只是放置在单独的 Paragraph 对象中的文本。
So, the short answer is that no, there is no goodway to find the caption for a given table.
因此,简短的回答是不,没有找到给定表格标题的好方法。
I did write some code that may help you though. It basically iterates through all Paragraph objects in the document and looks for the "Caption" style (alternatively, you could look for text formatted "Table #:", or whatever you'd like). If the very next Paragraph contains tables, it places the text of the caption into the first cell of the first table found.
我确实写了一些可能对你有帮助的代码。它基本上遍历文档中的所有 Paragraph 对象并查找“Caption”样式(或者,您可以查找格式为“Table #:”或任何您喜欢的文本)。如果下一个段落包含表格,它会将标题的文本放入找到的第一个表格的第一个单元格中。
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
Keep in mind that this is just an example of how you could tie together a caption with its table. With that said, it is not a very reliable method and I would not recommend using it unless you absolutely need tobecause table captions could presumably not have the caption styling, or there could be caption styling on something that isn't a caption, etc.
请记住,这只是一个示例,说明如何将标题与其表格联系在一起。话虽如此,这不是一种非常可靠的方法,除非您绝对需要,否则我不建议使用它,因为表格标题可能没有标题样式,或者可能在不是标题的内容上有标题样式等.