none
Powershell Word table cell merge RRS feed

  • Question

  • Hi,

    I want to merge certain cells in a Word table created with Powershell. I have the following script:


    $objWord = New-Object -comobject Word.Application 
    $objWord.Visible = $True 

    $objDoc = $objWord.Documents.Add() 
    $objSelection = $objWord.Selection 
     
    $objRange = $objSelection.Range 

    $a = $objDoc.Tables.Add($objRange, 3, 3) 
    $table = $objDoc.Tables.Item(1) 

    $table.AutoFitBehavior(1)

    $table.Cell(1, 1).Range.Text = "11" 
    $table.Cell(1, 2).Range.Text = "12" 
    $table.Cell(1, 3).Range.Text = "13" 
    $table.Cell(2, 1).Range.Text = "21" 
    $table.Cell(2, 2).Range.Text = "22" 
    $table.Cell(2, 3).Range.Text = "23" 
    $table.Cell(3, 1).Range.Text = "31" 
    $table.Cell(3, 2).Range.Text = "32" 
    $table.Cell(3, 3).Range.Text = "33" 

    Plase help me with a code to merge certain cells. eg. cell(2,2) merge with cell(2,3).

    The result should be a cell that is twice as wide as the others. Please advise how can I access the resulting cell (to change its text to "merged cell").

    Thanks a lot!

    Thursday, June 6, 2013 9:10 AM

Answers

  • Hello,

    You can use Cell.Merge Method (Word) to merge cells in the table.

    And you can specify cell's width and height by Cell.Width Property and Cell.Height Property.

    The VBA code should be like this:

    Dim cellw As Single
    With Table1
        cellw = .Cell(1, 1).Width
        .Cell(2, 3).Merge .Cell(2, 2)
        .Cell(2, 2).Range.Text = "merged cell"
        .Cell(2, 2).Width = cellw * 2
    End With

    I'm not familiar with PowerShell, but I think the conversion of code should be not difficult. Maybe this should work:

    $cellw = $table.Cell(1, 1).Width
    $table.Cell(2, 3).Merge($table.Cell(2, 2))
    $table.Cell(2, 2).Range.Text = "merged cell"
    $table.Cell(2, 2).Width = cellw * 2

    Best Regards,


    Damon Zheng
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Monday, June 10, 2013 12:44 PM
    Moderator