vbams-word

Converting text to table with line break within same cell in Word


I have a text separated by tabs that I need to convert to a table. So a tab = new column, paragraph break = new row. Text blocks with line breaks (shift+enter) should be kept together, not separated into different rows.

Is this possible in Word, for instance using VBA? Or do I have to replace carriage return with something else, for instance semicolon? Please see example below. I would prefer the colors to be separated by a carriage return so each color has a new line within the cell.

integer fruit colors
1 apple red ;green ;yellow
2 orange orange
3 lime green; white

Solution

  • Yes, this is possible with VBA, but I agree with the comments above that it might be easier to do this manually rather than with VBA. If VBA is required for some reason, then I think this will do what you're hoping to accomplish.

    '''the manual linefeed character is equal to chr(11)
    Dim sLineFeed As String
    sLineFeed = Chr(11)
    
    With Selection
        '''we'll remove the linefeed character before converting to table
        .Text = Replace(.Text, sLineFeed, "xxRestore")
        .ConvertToTable Separator:=wdSeparateByTabs
    
        Dim c As Cell
        '''restore the linefeed character
        For Each c In .Tables(1).Columns(3).Cells
            c.Range.Text = Replace(c.Range.Text, "xxRestore", sLineFeed)
        Next c
    End With