【问题标题】:Delete Word Fields VBA does not work in Word 2013, worked in Word 2010删除 Word 字段 VBA 在 Word 2013 中不起作用,在 Word 2010 中起作用
【发布时间】:2014-04-19 04:34:53
【问题描述】:

我有一个从 Excel 运行的 VBA 宏,用于从 Word 文档中导入一些信息。在开始解析之前,我想摆脱目录和其他字段。下面的代码(精简到最低限度)在 Office 2010 中有效,但在 Office 2013 中无效。我收到 “对象字段中的方法删除失败” 错误消息,但我不明白为什么。

感谢您的任何提示!

Sub ImportBOD()

    Dim wdFileName As Variant
    Dim WordApp As Object

    Dim wdDoc As Word.Document

    Dim fld As Word.Field


     wdFileName = Application.GetOpenFilename("Word files (*.docx),*.docx", ,"Choose the Word document")

    If wdFileName = False Then Exit Sub '(user cancelled import file browser)

    Set WordApp = CreateObject("Word.Application")

    Set wdDoc = WordApp.Documents.Open(wdFileName, ReadOnly:=True)

    'Get rid of table of contents and other fields 
    For Each fld In wdDoc.ActiveWindow.Document.Fields
        fld.Delete
    Next


    wdDoc.Close SaveChanges:=wdDoNotSaveChanges

End Sub

【问题讨论】:

  • 删除时,您应该从集合中的最后一项转到第一项。请参阅下面的答案+我的评论。

标签: vba excel ms-word


【解决方案1】:

必须尝试通过索引删除它们吗?

For i = 1 to wdDoc.ActiveWindow.Document.Fields.Count
    wdDoc.ActiveWindow.Document.Fields.Item(i).Delete
Next i

我有时发现,在这种情况下,fld 在循环中删除活动对象并不总是成功的,而且 VBA 错误消息并不具体。此外,似乎 SEQ(Sequence Fields) 和 XE(IndexEntry Fields) 不能是 Unlinked,这表明 Delete 也可能会失败,尽管 Microsoft 没有具体说明是这种情况。

编辑

基于从后到前循环的评论

For i = wdDoc.ActiveWindow.Document.Fields.Count To 1 Step -1
    wdDoc.ActiveWindow.Document.Fields.Item(i).Delete
Next i

【讨论】:

  • 感谢您的建议,不幸的是我遇到了同样的错误。但是,我确实想出了一个解决方法:我使用 Unlink 而不是 Delete,这对我的目的来说是可以的。我想摆脱这些字段的原因是当我尝试按段落处理文档时遇到问题,即逐段循环遍历文档。这些字段以某种方式干扰了处理,但是使用 Unlink 将它们转换为文本就可以了
猜你喜欢
  • 2015-10-13
  • 1970-01-01
  • 1970-01-01
  • 2011-04-29
  • 2018-04-05
  • 1970-01-01
  • 2013-06-13
  • 2012-05-31
  • 2016-11-06
相关资源
最近更新 更多