首页 > 解决方案 > 运行时错误 5825:已删除 .docm 导入的对象

问题描述

再会,

我对 VBA 很陌生。我有一个 .docm 表格,我想将其读入 Excel 电子表格。该表单既有旧版控件也有新版控件。我找到了将 .docm 文档中的数据导入 Excel 的代码,但它在 .docm 行给了我一条错误消息WkSht.Cells(i, j) = .Result。我真的很茫然,因为我不确定它为什么被删除。任何帮助将不胜感激!

Sub GetFormData()
'Note: this code requires a reference to the Word object model.
'See under the VBE's Tools|References.
Application.ScreenUpdating = False
Dim wdApp As New Word.Application, wdDoc As Word.Document
Dim FmFld As Word.FormField, 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 FmFld In .FormFields
      j = j + 1
      With FmFld
        Select Case .Type
          Case Is = wdFieldFormCheckBox
            WkSht.Cells(i, j) = .CheckBox.Value
          Case Else
            WkSht.Cells(i, j) = .Result
        End Select
      End With
    Next
    For Each CCtrl In .ContentControls
      j = j + 1
      With CCtrl
        Select Case .Type
          Case Is = wdContentControlCheckBox
            WkSht.Cells(i, j) = .Checked
          Case wdContentControlDate, wdContentControlDropdownList, wdContentControlRichText, wdContentControlText
            WkSht.Cells(i, j) = .Range.Text
          Case Else
        End Select
      End With
    Next
    .Close SaveChanges:=False
  End With
  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

标签: excelformsimportms-word

解决方案


最简单的解决方案是使用:

On Error Resume Next
WkSht.Cells(i, j) = .Result
On Error Goto 0

要处理 ActiveX 控件,您需要添加如下代码:

Dim iShp As Word.InlineShape

到代码顶部的变量声明,然后代码如下:

    For Each iShp In ActiveDocument.InlineShapes
      j = j + 1
      With iShp
        If .Type = wdInlineShapeOLEControlObject Then
          With .OLEFormat
            Select Case Split(.ClassType, ".")(1)
              Case Is = "TextBox", "ComboBox", "ListBox"
                WkSht.Cells(i, j) = .Object
              Case "CheckBox", "OptionButton"
                WkSht.Cells(i, j) = .Object
              Case Else
            End Select
          End With
        End If
      End With
    Next

在代码中最后存在的“下一步”之后。


推荐阅读