1
votes

I am trying to use Visual Basic so that I can populate word templates with data from excel. I have a macro that fills in fields in a Word document table from a table in Microsoft Excel. So far, if the excel table is smaller than the word table, the message "Error! No document variable supplied" prints in the word table and I delete that field using the macro (below). BUT, I also want to delete the entire rows in the Word table where this error occurs. Can you help me figure out how to do this?

Sub Rectangle_Click()
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim ws As Worksheet
Dim oHeader As Word.HeaderFooter
Dim oSection As Word.Section
Dim oFld As Word.Field
Dim flds As Word.Fields
Dim fld As Word.Field
Set ws = ThisWorkbook.Sheets("Sheet1")
ws.Activate
On Error Resume Next
Set wrdApp = GetObject(, "Word.Application")
If wrdApp Is Nothing Then Set wrdApp = CreateObject("Word.Application")
On Error GoTo 0
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Add(Template:="C:\Documents\mytemplate.dotm")
With wrdDoc
    .Variables("foo1").Value = Range("A5").Value
    .Variables("foo2").Value = Range("A6").Value
    .Variables("foo3").Value = Range("A7").Value
    .Variables("bar1").Value = Range("B5").Value
    .Variables("bar2").Value = Range("B6").Value
    .Variables("bar3").Value = Range("B7").Value
    .Range.Fields.Update
End With
wrdDoc.Range.Fields.Update
Set flds = ActiveDocument.Fields
For Each fld In flds
    If fld.Type = wdFieldDocVariable Then
        If fld.Result = "Error! No document variable supplied." Then
            Debug.Print fld.Code
            'ALSO DELETE THE ROW WHERE THIS EMPTY FIELD WAS FOUND!!'
            fld.Delete
        End If
    End If
Next
Set wrdDoc = Nothing
Set wrdApp = Nothing
Application.CutCopyMode = False
End Sub

How can I get rid of rows (or cells) where "no document variable supplied" occurs?

1

1 Answers

0
votes

If you want to delete the whole row of table where your current selection is then use:

Word.Selection.Rows.Delete