How to add rows to a merged Word table?

后端 未结 1 1460
悲哀的现实
悲哀的现实 2021-01-23 00:20

This is how the table looks like.

Code:

Sub WordTableTester()
Dim CurrentTable As table
Dim wdDoc As Document
Dim Rw As Long, c         


        
相关标签:
1条回答
  • 2021-01-23 00:59

    Working with merged rows in MS Word Table is slightly tricky.

    Is this what you want?

    Sub Sample()
        Dim CurrentTable As Table
        Dim wdDoc As Document
        Dim Rw As Long, col As Long
    
        Set wdDoc = ActiveDocument '<~~ Created this for testing
        Set CurrentTable = wdDoc.Tables(1)
    
        Rw = 9: col = CurrentTable.Columns.Count
    
        wdDoc.Range(CurrentTable.Cell(Rw, 1).Range.Start, _
        CurrentTable.Cell(Rw, col).Range.Start).Select
    
        wdDoc.Application.Selection.InsertRowsBelow
    End Sub
    

    ScreenShot

    Edit

    You table's format is all screwed up. Table was created with few rows and then the cells were merged/split to create new rows and hence you were getting the error. Also since you are automating word from excel, I would recommend the following way.

    Try this

    Sub WordTableTester()
        Dim oWordApp As Object, oWordDoc As Object, CurrentTable As Object
        Dim flName As Variant
        Dim Rw As Long, col As Long
    
        flName = Application.GetOpenFilename("Word files (*.docx),*.docx", _
        , "Please choose a file containing requirements to be imported")
    
        If flName = False Then Exit Sub
    
        Set oWordApp = CreateObject("Word.Application")
        oWordApp.Visible = True
    
        Set oWordDoc = oWordApp.Documents.Open(flName)
        Set CurrentTable = oWordDoc.Tables(1)
    
        Rw = 7: col = CurrentTable.Columns.Count
    
        oWordDoc.Range(CurrentTable.Cell(Rw, 1).Range.Start, _
        CurrentTable.Cell(Rw, col).Range.Start).Select
    
        oWordDoc.Application.Selection.InsertRowsBelow
    End Sub
    
    0 讨论(0)
提交回复
热议问题