我想从 Word 文档访问表格,我得到了一个使用其索引的方法。但对于我的项目来说,这会引起困惑,所以我想使用它们的名称,就像我们在 excel 中使用它一样。
设置 tbl = oExcelWorksheet.ListObjects("Table2").Range
但是在word中访问表格我只找到了这个命令
设置 oTable = ActiveDocument.Tables("1")
Word VBA 中是否有其他命令可以使用表名访问表而不是索引。
最佳答案
正如 @Timothy 在评论中正确指出的那样,Word 中的表格没有名称。
一种解决方法是使用您想要为表格指定的名称为每个表格的第一个单元格(或任何其他单元格)添加书签
然后您可以使用此书签来定位您的 table 。例如,您可以使用此功能(我使用 here 的建议)[请参阅下面的 Edit1]
Function GetTable(sTableName As String) As Table
Dim sCell_1_Range As Range
With ThisDocument
On Error Resume Next
Set sCell_1_Range = .Bookmarks(sTableName).Range
If Err.Number > 0 Then Exit Function ' table not found
On Error GoTo 0
Set GetTable = .Tables(.Range(0, sCell_1_Range.End).Tables.Count)
End With
End Function
像这样使用它
Sub TestTableWithName()
Dim myTable As Table
Set myTable = GetTable("SecondTable")
If Not myTable Is Nothing Then
myTable.Range.Select
End If
End Sub
编辑1
@freeflow 建议更好地实现该功能
Function GetTable(sTableName As String) As Table
On Error Resume Next
Set GetTable = ThisDocument.Bookmarks(sTableName).Range.Tables(1)
End Function
这意味着 - 根据您的编码风格 - 您甚至可能不需要使用函数。如果直接使用,请记住使用On Error GoTo 0
关于vba - 我们可以使用 vba 通过名称而不是索引来访问单词表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63463443/