PDA

View Full Version : Solved: Deleting blank rows in table



neilholmes
05-27-2011, 06:40 AM
Hi everyone, I am new to the forum and new to writing code for vba.

I am hoping that you will be able to help me.

I have been looking for a code that deletes blank rows from a table within a word document.

I have found the following code which works really well :


Dim i As Long
With Selection.Tables(1)
For i = .Rows.Count To 1 Step -1
If Len(.Cell(i, 2).Range.Text) = 2 Then
.Rows(i).Delete
End If
Next i
End With


The problem is, the code will delete all the blank cells. What I would really like the code to do is only delete the rows which are blank that follow the last row of text.

(Hope that makes sense)

For Example :

https://files.me.com/holmes.n/4vwy5j

At the moment the work around I have been using is to put a space in those 'blank' rows that I do not wish to delete.

If anyone can help that would be great.

Thanks

- Neil

macropod
05-27-2011, 03:55 PM
Hi Neil,

Try:

Sub DeleteEmptyRowsFromTable()
Dim tbl As Table, cel As Cell, i As Long, n As Long, fEmpty As Boolean
On Error GoTo ErrHandler
If Not Selection.Information(wdWithInTable) Then
MsgBox "Place the insertion point within a table!"
Exit Sub
End If
Set tbl = Selection.Tables(1)
n = tbl.Rows.Count
For i = n To 1 Step -1
fEmpty = True
For Each cel In tbl.Rows(i).Cells
If Len(cel.Range.Text) > 2 Then
fEmpty = False
Exit Sub
End If
Next cel
If fEmpty = True Then tbl.Rows(i).Delete
Next i
ExitHandler:
Set cel = Nothing: Set tbl = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description, vbExclamation
Resume ExitHandler
End Sub
Notes:
1. If you change second the 'Exit Sub' to 'Exit For', the macro will delete all empty rows in the table
2. The macro may fail on tables with vertically-merged cells.

macropod
05-27-2011, 04:21 PM
:p

neilholmes
05-31-2011, 02:16 AM
Many thanks... This works really well !

:yes