PDA

View Full Version : Solved: Apllying Macro to a whole workbook



Champers
07-23-2009, 07:04 AM
Hi All,

I have created a number of tables in a word document which I have attached and the Macro below removes all blank rows in the first table on the first page where the first column is blank.

However I would like it to go through all tables on each page and remove all blank rows where the first column is blank.

Any help would be appreciated.


'Sub Remove_Blank_Rows()
'
' Remove_Blank_Rows Macro
'
'
Sub RemoveBlankRows()
Dim I As Integer
Dim bDeleted As Boolean
Redo:
bDeleted = False
For I = 1 To ActiveDocument.Tables(1).Rows.Count
ActiveDocument.Tables(1).Rows(I).Select
ActiveDocument.Tables(1).Rows(I).Cells(1).Select
If Selection.Text = Chr(13) & Chr(7) Then
ActiveDocument.Tables(1).Rows(I).Delete
bDeleted = True
Exit For
End If
Next
If bDeleted Then GoTo Redo
MsgBox "DONE!"
End Sub


Thanks

Champers

Tommy
07-24-2009, 07:54 AM
This should be what you need :)
Sub RemoveBlankRows()
Dim I As Long, Tbls As Long
With ActiveDocument
For Tbls = 1 To .Tables.Count
For I = .Tables(Tbls).Rows.Count To 1 Step -1
If .Tables(Tbls).Rows(I).Cells(1).Range.Text = Chr(13) & Chr(7) Then
.Tables(Tbls).Rows(I).Delete
End If
Next
Next
End With
MsgBox "Done!"
End Sub



EDIT: fixed minor dumb mistake on my part.

fumei
07-24-2009, 11:10 AM
1. There is a logic error here.

"remove all blank rows where the first column is blank."

In any of the code posted (and mine as well!) there is NO testing to see if the row is blank. The code only checks to see if the first cell is blank. Logically, because the first row is blank does NOT mean any other cells in that row MUSt be blank.

That is, blank Cell(1) does not - logically - mean Cell(2), Cell(3)....are blank. It does not mean the row itself is "blank".

See the second table in the file attached. The first row has cell(1) blank...BUT...the row itself is NOT blank. There is content in other cells. Again, as this was not stated as a requirement, my demo code will remove that row.

2. It is much better to use objects.

Option Explicit

Sub RemoveEmptyRows()
Dim oTable As Table
Dim oRow As Row

For Each oTable In ActiveDocument.Tables
For Each oRow In oTable.Rows
If oRow.Cells(1).Range.Text = _
Chr(13) & Chr(7) Then
oRow.Delete
End If
Next
Next
End Sub
This does exactly as stated is the requirement.

For each table in the document
For each row in that table
If the first cell is blank, delete that row.

Demo attached. Click "Remove Blank Rows" on the top toolbar.

Champers
07-27-2009, 01:26 AM
That is great and thank you both for your help.

Thank you and best regards


Champers