将Word Form数据拉入Excel工作簿时的OLE和/或运行时438错误

时间:2018-06-26 21:00:10

标签: excel vba excel-vba ms-word

此脚本运行良好,直到无效。我在一个Excel工作簿中与一个Word表单的多个副本在同一文件夹中。宏应从每个表单中提取数据并将其复制到工作簿中的一行。我现在收到“ OLE Excel正在等待另一个应用程序”错误或运行时438错误。我使用的宏如下:

    Sub GetFormData()
    Application.ScreenUpdating = False
    Dim wdApp As New Word.Application
    Dim wdDoc As Word.Document
    Dim CCtrl As Word.ContentControl
    Dim strFolder As String, strFile As String
    Dim WkSht As Worksheet, i As Long, j As Long
    strFolder = GetFolder
    If strFolder = "" Then Exit Sub
    Set WkSht = ActiveSheet
    i = WkSht.Cells(WkSht.Rows.Count, 1).End(xlUp).Row
    strFile = Dir(strFolder & "\*.docm", vbNormal)
    While strFile <> ""
        i = i + 1
    Set wdDoc = wdApp.Documents.Open(Filename:=strFolder & "\" & strFile,   AddToRecentFiles:=False, Visible:=False)
    With wdDoc
      j = 0
    For Each CCtrl In .ContentControls
        j = j + 1
        WkSht.Cells(i, j).FormulaLocal = CCtrl.Range.Text
        Next
    End With
    wdDoc.Close SaveChanges:=False
    strFile = Dir()
Wend
wdApp.Quit
Set wdDoc = Nothing: Set wdApp = Nothing: Set WkSht = Nothing
Application.ScreenUpdating = True
End Sub

   Function GetFolder() As String
Dim oFolder As Object
GetFolder = ""
Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
Set oFolder = Nothing
End Function

问题似乎始于“设置wdDoc = wdApp ...”

对此我有点菜鸟。因此,感谢您的帮助。     马特。

1 个答案:

答案 0 :(得分:0)

我看到了两个可能的问题,第一个几乎可以肯定是引起错误的;第二个可能导致此错误(但可能不是VBA):

  1. 您在同一行中声明并实例化Word应用程序:

    将wdApp设置为新Word.Application

您不应该这样做。相反:

Dim wdApp As Word.Application
Set wdApp = New Word.Application

我不记得有关“为什么”的确切详细信息,但这与立即创建Word.Application对象有关,并且在某种程度上您无法再使用Set wdApp = Nothing来控制它。

  1. 正确地,应该按照创建它们的相反顺序释放“外部”应用程序的所有对象。您已声明Word.ContentControl类型的对象,但不要释放它:

    设置Set CCtrl = Nothing:设置wdDoc = Nothing:设置wdApp = Nothing:设置WkSht = Nothing

相关问题