字段为空时删除行

时间:2015-01-29 17:47:39

标签: excel vba excel-vba ms-word word-vba

我正在尝试使用Visual Basic,以便我可以使用excel中的数据填充单词模板。我有一个宏从Microsoft Excel中的表填充Word文档表中的字段。到目前为止,如果excel表小于word表,则会在单词表中打印消息“Error!No document variable supplied”,并使用宏删除该字段(如下所示)。但是,我还想删除发生此错误的Word表中的整个行。你能帮我弄明白怎么做吗?

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

如何摆脱“没有提供文件变量”的行(或单元格)?

1 个答案:

答案 0 :(得分:0)

如果要删除当前选择的表格的整行,请使用:

Word.Selection.Rows.Delete