PickupBrain

Transpose table in Ms Word with 1 click

Truly speaking, Ms Word doesn’t have a feature to transpose a table. However, there are a couple of different tricks by which you can transpose a Word table. One of the quickest way is by using a Macro. Though looks like quite a task however, if you are someone who frequently transpose a table then this could be of great time saver.

Steps to transpose table using Macro

  1. Place the cursor anywhere in the Ms Word Table
  2. Save and run the following Macro (you can assign keyboard shortcut or button to it)
Public Sub Transpose()
	'Variables
	Dim NewTable As Table
	Dim SourceTable As Table
	Dim TableRange As Range
	Dim TableAsArray() As String 'Will contain the table text in memory
	Dim RowDataAsArray() As String
	Dim RowCount As Long, ColumnCount As Long
	Dim SourceTableStyle As Style
	Dim i As Long, j As Long 'Loop Counters
 
	'If cursor is not in a table, exit macro
	If Not Selection.Information(wdWithInTable) Then
		MsgBox "Cursor should be in a table"
	Exit Sub
	End If
	
	Set SourceTable = Selection.Tables(1)
	RowCount = SourceTable.Rows.Count
	ColumnCount = SourceTable.Columns.Count
	Set SourceTableStyle = SourceTable.Style
	'Redefine array as a two dimensional array with exact row and column count
	ReDim TableAsArray(1 To RowCount, 1 To ColumnCount)
	
	For i = 1 To RowCount
		RowDataAsArray = Split(Expression:=SourceTable.Rows(i).Range.Text, _
		Delimiter:=vbCr)
		For j = 1 To ColumnCount
			'Last item in RowDataAsArray is vbCr, thus j - 1 to ignore that
			TableAsArray(i, j) = RowDataAsArray(j - 1)
		Next j
	Next
	
	Set TableRange = SourceTable.Range
	TableRange.Collapse wdCollapseEnd
	SourceTable.Delete
	
	'Creating a new table
	Set NewTable = TableRange.Tables.Add(TableRange, ColumnCount, RowCount)
	'Fill data in the new table
	For i = 1 To RowCount
		For j = 1 To ColumnCount
			NewTable.Rows(j).Cells(i).Range.Text = TableAsArray(i, j)
		Next
	Next
	'Applying style to the new table
	NewTable.Style = SourceTableStyle
 End Sub

Video tutorial to transposing Word table

Leave a Reply