Search code examples
vbams-wordword-2013

VBA code to merge two cells together


My scenario is a document with one two-column table. I am reading from a database and populating each row/column, but for some records, I want to merge the two columns into one cell and populate that as a row, then after that, continue the two column scenario. I want to issue a VBA statement to merge the two cells together to make one cell across the entire row. This is impossible to "record" as a new macro. I don't know what the row number is at run time, I only know the column numbers. My search string is: '"Word 2013" VBA table merge cells' but I get a lot of site that show you how to do it manually, not with VBA code.

My current code:

With ActiveDocument.Tables(1)
.Cell(Row:=1, Column:=1).merge _
MergeTo:=.Cell(Row:=1, Column:=2)
.Borders.Enable = True
End With

In the document, I have a small table of one row and two columns. But I should be able to have a table of three rows with any mixture of columns, right? I just want to pick any two columns and merge them together to make one space, but at run-time I do not know what row number to provide.


Solution

  • I finally got this worked out, and I want to again thank you for your help. Here is my current code. The entire document is one two-column table, skinny, and includes hyperlinks so that it can be read and navigated on an iPhone. When a Unit value changes in the data, I want to 1) insert a new row below and merge it into one column, add a 'Go Home' link, then continue adding two-column rows.

    The document is finally converted to a .PDF and accessed by iOS users.

        'Add a row for a 'back to home' link 
        If (intUnitOrder > intCurrentUnit) Then
           Selection.InsertRowsBelow (1)
           rowno = Selection.Information(wdEndOfRangeRowNumber) - 1
           With ActiveDocument.Tables(1)
             .Cell(Row:=rowno, Column:=1).Merge MergeTo:=.Cell(Row:=rowno, _ 
             Column:=2)
           End With
    
           Selection.Tables(1).Rows(rowno).Range.ParagraphFormat. _
             Alignment = wdAlignParagraphRight
           Selection.Shading.BackgroundPatternColor = RGB(230, 230, 230)
           Selection.Font.ColorIndex = wdBlue
           Selection.Font.Italic = True
    
           ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, _
             Address:="#Home", SubAddress:="", _
             ScreenTip:="Go back to the top", _
             TextToDisplay:="back to Home"
    
           Selection.MoveDown wdLine, 1
           intCurrentUnit = intUnitOrder
        End If