PDA

View Full Version : Solved: Delete Empty Rows in a Table



ktselios
04-23-2012, 11:33 PM
Hi!

This is my first post here. I am a newbie to VBA.

What I try to do:

I want to delete empty rows in every table in a word protected form.
The table cantains some cells with explanation text and the other cells usually contain text formfiels.

I found a code from another post which I used it according to my needs.
Take a look:



Sub DeleteEmptyRows()

ActiveDocument.Unprotect Password:="**"
Dim oCell As Word.Cell
Dim oTable As Word.Table
Dim oForm As Word.FormField
Dim oRange As Range
Dim TextInForm As Boolean
Dim oRows As Integer
Dim i As Integer
Dim lastRow As Integer
Dim lastColumn As Integer
For Each oTable In ActiveDocument.Tables

oRows = oTable.Rows.Count
Set oRange = oTable.Rows(1).Range

For i = 1 To oRows

TextInForm = False

For Each oCell In oRange.Rows(1).Cells
For Each oForm In oCell.Range.FormFields
If oForm.Result <> "" Then
TextInForm = True
Exit For
End If
Next oForm

Next oCell

If TextInForm Then
Set oRange = oRange.Next(wdRow)
Else
oRange.Rows(1).Delete
End If

Next i

lastRow = oTable.Rows.Count
lastColumn = oTable.Columns.Count
oTable.Cell(lastRow, lastColumn).Range.FormFields(1).ExitMacro = "addRow"

Next oTable

ActiveDocument.Protect Password:="**", Type:=wdAllowOnlyFormFields, NoReset:=True

End Sub


The problem is that this code deletes all rows when the text formfield is empty, AND every row that contains TEXT (I don't want this!! :banghead: )

What I want is to just delete empty rows and keep the rows with text and not empty formfields.

Any suggestion?

Thanks
:hi:

macropod
04-24-2012, 05:50 AM
Try something along the lines of:
Sub DelBlankRows()
Dim Pwd As String, pState As Boolean, Tbl As Table, oRow As Row
Dim oCel As Cell, Rng As Range, Fld As FormField, Str As String
With ActiveDocument
pState = False
If .ProtectionType <> wdNoProtection Then
Pwd = InputBox("Please enter the Password", "Password")
pState = True
.Unprotect Pwd
End If
For Each Tbl In .Tables
For Each oRow In Tbl.Rows
Str = vbNullString
For Each oCel In oRow.Cells
Set Rng = oCel.Range
With Rng
.End = .End - 1
If .FormFields.Count > 0 Then
For Each Fld In Rng.FormFields
Str = Str & Trim(Fld.Result)
Next
Else
Str = Str & Trim(.Text)
End If
End With
Next
If Str = vbNullString Then
On Error Resume Next 'skip vertically merged cells
oRow.Delete
End If
Next oRow
Next Tbl
If pState = True Then .Protect Type:=wdAllowOnlyFormFields, Noreset:=True, Password:=Pwd
pState = False: Pwd = vbNullString: Set Rng = Nothing
End With
End Sub

ktselios
04-25-2012, 10:51 PM
Hi Paul!

I tried your code in my document
It worked PERFECT!

Thanks a lot!!!