'用户定义的类型未定义'错误

hol*_*do1 10 excel vba ms-word excel-vba

我在尝试执行此宏时遇到上述错误.我对Macros和编码很新,所以请原谅无知.

谢谢

Sub DeleteEmptyRows()

Dim oTable As Table, oRow As Row, _
TextInRow As Boolean, i As Long

Application.ScreenUpdating = False

For Each oTable In ActiveDocument.Tables
    For Each oRow In oTable.Rows

        TextInRow = False

        For i = 2 To oRow.Cells.Count
            If Len(oRow.Cells(i).Range.Text) > 2 Then
                'end of cell marker is actually 2 characters
                TextInRow = True
                Exit For
            End If
        Next

        If TextInRow = False Then
            oRow.Delete
        End If
    Next
Next
Application.ScreenUpdating = True

End Sub
Run Code Online (Sandbox Code Playgroud)

Dav*_*ens 16

您的错误是由以下原因引起的:

Dim oTable As Table, oRow As Row,
Run Code Online (Sandbox Code Playgroud)

这些类型的,TableRow不是变量类型,原产于Excel中.您可以通过以下两种方式之一解决此问题:

  1. 包括对Microsoft Word对象模型的引用.从工具|执行此操作 引用,然后添加对MS Word的引用.虽然不是绝对必要,但您可能希望完全限定像这样的对象Dim oTable as Word.Table, oRow as Word.Row.这称为早期绑定. 在此输入图像描述
  2. 或者,要使用后期绑定方法,必须将对象声明为泛型Object类型:Dim oTable as Object, oRow as Object.使用此方法,您不需要添加对Word的引用,但您也失去了VBE中的intellisense帮助.

我没有测试过您的代码,但我怀疑ActiveDocument使用方法#2无法在Excel中工作,除非您将其适当地限定为Word.Application对象的实例.我没有在你提供的代码中看到任何地方.一个例子是:

Sub DeleteEmptyRows()
Dim wdApp as Object
Dim oTable As Object, As Object, _
TextInRow As Boolean, i As Long

Set wdApp = GetObject(,"Word.Application")

Application.ScreenUpdating = False

For Each oTable In wdApp.ActiveDocument.Tables
Run Code Online (Sandbox Code Playgroud)