当文件路径在变量中时,如何获得 table 的总行数?

How do I get a total row count of a table when the file path is in a variable?

我需要计算 Word 文档中 table1 的总行数。 文档路径在变量中,因为它会根据用户输入而改变。包含路径的变量是fpath.

当我使用变量而不是文件路径时,如何获得 table 1 的总行数?

由于 Documents(fpath).Tables(1).Rows.Count,我的代码似乎失败了。

Sub CountTableRows()
    Dim fpath as String  'contains file path                                                             
    Dim fdoc as Document
    Dim trows as Integer 'contains total number of rows in table
    Set fpath = "c:\folder\document.docx"
    Set fDoc = Documents.Open(fpath)
    fDoc.Activate
    trows = Documents(fpath).Tables(1).Rows.Count
    MsgBox "total rows= " & trows
End Sub

您可能希望修改您的代码以更具防御性,这样它就不会在遇到您隐藏的假设之一时崩溃。 (即文件存在,并且至少有 1 table)。

Public Function CountTableRows(ByVal ipPath As String, ByVal ipTableNo As Long) As Long

    CountTableRows = -1
    
    Dim myDoc As Word.Document
    If Not TryOpenDoc(ipPath, myDoc) Then
    
        Debug.Print "There was a problem opening '" & ipPath & "'"
        Exit Function
        
        
    End If
    
    Dim myRowCount As Long
    If Not TryCountRows(myDoc, ipTableNo, myRowCount) Then
    
        Debug.Print "Document '" & ipPath & "' does not have Table " & ipTableNo
        Exit Function
        
        
    End If
    
    myDoc.Close
    CountTableRows = myRowCount
    ' MsgBox "Total rows =" & myRowCount
        
End Function


Public Function TryOpenDoc(ByVal ipPath As String, ByRef opDoc As Word.Document) As Boolean

    TryOpenDoc = False
    
    On Error Resume Next
    Set opDoc = Application.Documents.Open(ipPath)
    If Err.Number <> 0 Then Exit Function
    
    Err.Clear
    TryOpenDoc = True
    
End Function


Public Function TryCountRows(ByRef ipDoc As Word.Document, ByVal ipTableNo As Long, ByRef opRowCount As Long) As Boolean

    TryCountRows = False
    If ipDoc.Tables.Count < ipTableNo Then Exit Function
   
    opRowCount = ipDoc.Tables(ipTableNo).Rows.Count
    
    TryCountRows = True
    
End Function