Skip to content

Instantly share code, notes, and snippets.

@jvarn
Last active March 26, 2024 09:54
Show Gist options
  • Save jvarn/bcf9fccac2f97bd7d83a129289b38a2a to your computer and use it in GitHub Desktop.
Save jvarn/bcf9fccac2f97bd7d83a129289b38a2a to your computer and use it in GitHub Desktop.
Reverse order of table columns in MS Word VBA
' Reverses LTR tables with visually RTL content and vice versa
' Tested with simple table (no merged cells) on Microsoft 365 versions of:
' Microsoft Word for Mac, Version 16.83
' Microsoft Word for Windows, Version 2402
Sub ReverseTableColumns()
Dim tbl As Table
Dim colCount As Long
Dim i As Long
Dim j As Long
Dim tempContent As String
If Selection.Information(wdWithInTable) Then
Set tbl = Selection.Tables(1)
colCount = tbl.Columns.Count
' Loop through cols, swap 1st & last, moving towards middle.
For i = 1 To colCount / 2
For j = 1 To tbl.Rows.Count
' Store first column content in temp variable
tempContent = tbl.cell(j, i).Range.Text
' Move last column content to 1st
tbl.cell(j, i).Range.Text = tbl.cell(j, colCount - i + 1).Range.Text
' Move temp content (original 1st column) to last
tbl.cell(j, colCount - i + 1).Range.Text = tempContent
Next j
Next i
' Adjust table properties.
With tbl
If .Rows.TableDirection = wdTableDirectionLtr Then
.Rows.TableDirection = wdTableDirectionRtl
.Rows.Alignment = wdAlignRowRight
.Range.ParagraphFormat.ReadingOrder = wdReadingOrderRtl
Elseif .Rows.TableDirection = wdTableDirectionRtl Then
.Rows.TableDirection = wdTableDirectionLtr
.Rows.Alignment = wdAlignRowLeft
.Range.ParagraphFormat.ReadingOrder = wdReadingOrderLtr
End If
End With
' Remove trailing paragraph marks.
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "^p"
.Replacement.Text = ""
.Forward = True
End With
Selection.Find.Execute Replace:=wdReplaceAll
Else
MsgBox "Please select a table first.", vbInformation
End If
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment