|
|
Title | Use VBA to switch a Word table's rows and columns |
Description | This example shows how to use VBA to switch a Word table's rows and columns. |
Keywords | Word, table, row, column, switch, VBA |
Categories | Office, Utilities |
|
|
Subroutine SwitchRowsAndColumns gets a reference to the first table in the current selection (click on the table before calling the routine). It gets a Range holding the table, collapses the Range to the end of the table, adds a new paragraph, and collapses again to the spot after the new paragraph.
The code then adds a new table to the Range making its number of rows the same as the original table's number of columns and vice versa. The code then loops through the old table's rows and columns, copying the value at position (C, R) in the old table into the new table at position (R, C).
|
|
' Switch a table's rows and columns.
Sub SwitchRowsAndColumns()
Dim rng As Range
Dim old_table As Table
Dim new_table As Table
Dim r As Integer
Dim c As Integer
Dim txt As String
Set old_table = Selection.Tables(1)
Set rng = old_table.Range
rng.Collapse wdCollapseEnd
rng.InsertParagraph
rng.Collapse wdCollapseEnd
Set new_table = rng.Tables.Add(rng, _
old_table.Columns.Count, old_table.Rows.Count)
For r = 1 To old_table.Columns.Count
For c = 1 To old_table.Rows.Count
' Remove trailing weird characters.
txt = old_table.Cell(c, r).Range.Text
Do While Right$(txt, 1) < " "
txt = Left$(txt, Len(txt) - 1)
If Len(txt) < 1 Then Exit Do
Loop
new_table.Cell(r, c).Range.Text = txt
Next c
Next r
End Sub
|
|
-->
|
|