PDA

View Full Version : Macro for adding columns to selected word tables



dsouza26
08-10-2014, 04:35 AM
I want to create a macro to add a column with header 'Observed Behavior' to every table in the word document which has the column 'Input' in the table.

The value inside the column 'Observed Behavior' should be 'SAT' for all the rows in the those particular tables.


The new column 'Observed Behavior' should be the last column right next to the column 'Input'.
and it should not be added in any other table in the document.

eg:
original doc


ID
INPUT


1
A


2
B





ID
NAME


1
ABC


2
XYZ



After using macro:


ID
INPUT
OBSERVED BEHAVIOR


1
A
SAT


2
B
SAT






ID
NAME


1
ABC


2
XYZ

macropod
08-10-2014, 03:20 PM
Try:

Sub Demo()
Application.ScreenUpdating = False
Dim Tbl As Table, Rng As Range, i As Long
With ActiveDocument
For Each Tbl In Tables
With Tbl
Set Rng = .Cell(1, 2).Range
Rng.End = Rng.End - 1
If LCase(Rng.Text) = "input" Then
.Columns.Add
.Cell(1, 3).Range.Text = "OBSERVED BEHAVIOR"
For i = 2 To .Columns(3).Cells.Count
.Cell(i, 3).Range.Text = "SAT"
Next
End If
End With
Next
End With
Application.ScreenUpdating = True
End Sub
Note: Your descriptions are quite inconsistent. You refer to cells containing 'Input' and 'Observed Behavior', but then demonstrate them with 'INPUT' and 'OBSERVED BEHAVIOR'. These are obviously different.