【问题标题】:Can we access a word table by it's name and not index using vba?我们可以通过名称访问单词表而不是使用 vba 索引吗?
【发布时间】:2020-08-19 08:27:18
【问题描述】:

我想从 word 文档中访问表格,并且我得到了一个使用其索引的方法。但是对于我的项目,它会引起混乱,所以我想使用他们的名字,就像我们在 excel 中使用这个一样。

Set tbl = oExcelWorksheet.ListObjects("Table2").Range

但是在word中访问一个表我只找到了这个命令

Set oTable = ActiveDocument.Tables("1")

word VBA 中是否有任何其他命令,通过它我可以使用表名来访问表而不是索引。

【问题讨论】:

  • Word 中的表格没有名称。
  • @Timothy 是对的,但有一个解决方法

标签: vba ms-word


【解决方案1】:

正如@Timothy 在 cmets 中正确指出的那样,word 中的表格没有名称。

一种解决方法是使用您要为表格命名的名称为每个表格的第一个单元格(或任何其他单元格)添加书签

然后您可以使用此书签来定位您的表。例如你可以使用这个功能(我使用了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

【讨论】:

  • 你的函数可以简化为两行 - On Error Resume Next, Set GetTable = ThisDocument.Bookmarks(sTableRange).Range.Tables(1)
  • @freeflow 好多了,太棒了。没想到。非常感谢。更新了我的答案
猜你喜欢
  • 1970-01-01
  • 2020-11-18
  • 2012-05-01
  • 2018-04-07
  • 2011-06-20
  • 2013-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多