简体   繁体   中英

Copy rows of text preceding a table in word using VBA

I am working through Excel and Word using VBA. From Excel I have a macro to copy all the tables from a specific word file using a macro. It actually work perfectly. However, now I am trying to copy also let's say the 10 previous rows of text of the table because these rows can contain useful information about the content of the table. I tried to find a method to get the position of my table or to copy text from a given position (row, column,...) but I found nothing.

My function to get all the tables from a word document is the following :

Private Function GetlisteTables(doc As Object) As Collection

    Dim tableau As Object
    Dim listeTableaux As New Collection

    For Each tableau In doc.Tables
        If tableau.Columns.Count > 4 Then

            On Error Resume Next
            listeTableaux.Add tableau
            
        End If
    Next tableau
    
    Set GetlisteTables = listeTableaux

End Function

I though I could use .Range on my table but this actually gives me the content of the table and I don't think it is useful in my case. Is there any method that can help me to copy a specific part (especially right before a table) of text in a word document using VBA ?

The Paragraph object has a Previous method, which can return the previous unit as specified.

So the starting and end character positions of the previous paragraph to a table can be found using:

With ActiveDocument.Tables(1).Range.Previous(Unit:=wdParagraph)
MsgBox .Start & ":" & .End
End With

Ref:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM