How to Merge Cells in the Row of a LibreOffice Writer Table Using a Macro

Hello everyone,

I am working with LibreOffice Writer and am trying to automate the process of creating a table and merging cells using a macro written in LibreOffice BASIC. I need to create a table with 2 columns and 12 rows. Specifically, I want to merge the cells in the second-last row (row 11, considering 1-based indexing).

I have written a macro to create the table and select the cells I want to merge, but I am encountering a error:

Sub CreateTableWithMergedRow
    Dim oDoc As Object
    Dim oTable As Object
    Dim oCell As Object

    ' Get the current document
    oDoc = ThisComponent

    ' Create a table with 2 columns and 12 rows
    oTable = oDoc.createInstance("com.sun.star.text.TextTable")
    oTable.initialize(12, 2)

    ' Insert the table into the document
    oDoc.Text.insertTextContent(oDoc.Text.getEnd(), oTable, False)

    ' Get the cells in the last row
    Dim oCellRange As Object
    oCellRange = oTable.getCellRangeByPosition(0, 11, 1, 11) ' Range from (0,11) to (1,11)

    ' Merge the last row's cells using the mergeCells method
    oCellRange.mergeCells()

    ' Set the text for the merged cell
    oCellRange.getCellByPosition(0, 0).setString("Merged Cell")

End Sub

Do you wish us to try and guess what the error message is and where it appears?

See here
image

So

' Get the cells in the last two rows
'oCellRange = oTable.getCellRangeByPosition(0, 11, 1, 11) ' Range from (0,11) to (1,11)
Dim oCursor As Object 
oCursor = oTable.createCursorByCellName("A11")
oCursor.goRight(1, True)
oCursor.goDown(1, True)
oCursor.mergeRange()

' Set the text for the merged cell
oTable.getCellByPosition(0, 10).setString("Merged Cell")
1 Like

yes, help me to solve the problem

Thanks its works