【问题标题】:Replace text in Word document from Excel从 Excel 替换 Word 文档中的文本
【发布时间】:2014-03-27 22:51:52
【问题描述】:

我需要遍历 excel 表格中的一行并使用单元格值在 Word 文档中进行替换。我使用记录宏来获取代码,它实际上替换了文本。但是当我从 Excel 宏中使用它时它不起作用。

Dim WordApp As Object
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True

Dim WordDoc As Object
Set WordDoc = WordApp.Documents.Open(doc_path_str)

Dim find_what, find_repl As String

For col_idx = params_hdr_range.Column To params_hdr_range.Column + params_hdr_range.Columns.Count - 1
    find_what = CStr(scnd_sheet.Cells(params_hdr_range.Row - 1, col_idx).Value)
    find_repl = CStr(scnd_sheet.Cells(model_found_range.Row, col_idx).Value)
    WordApp.Selection.Find.ClearHitHighlight
    WordApp.Selection.Find.ClearFormatting
    WordApp.Selection.Find.Replacement.ClearFormatting
    With WordApp.Selection.Find
      .Text = find_what
      .Replacement.Text = find_repl
      .Forward = True
      .Wrap = wdFindContinue
      .Format = False
      .MatchCase = False
      .MatchWholeWord = False
      .MatchWildcards = False
      .MatchSoundsLike = False
      .MatchAllWordForms = False
    End With
    WordApp.Selection.Find.Execute Replace:=wdReplaceAll
Next col_idx

find_what 和 find_repl 具有正确的值(“{MODEL}”和“F22-2”),与我在录制宏时使用的值相同,但没有进行替换。这段代码唯一做的就是选择文档中的文本“{MODEL}”。但它并没有取代它,尽管它经历了很多列和其他值(例如“{PRICE}”),但没有其他任何事情发生。
我该如何解决这个问题?

【问题讨论】:

  • 您是否在 Excel VBA 项目中添加了对 Word 的引用?如果您不知道,Excel 将不会知道 Word 常量的值,例如 wdReplaceAll
  • 把它作为答案发布,我会接受它:)

标签: vba excel ms-word


【解决方案1】:

除非您在 Excel VBA 项目中添加对 Word 对象库的引用,否则 Excel 不会知道 Word 常量(例如 wdReplaceAll)的值。

您可以添加引用、在 Excel VBA 中声明常量,或使用常量的值(可在 Word VBA 对象浏览器中找到)

【讨论】:

  • 我想知道为什么每次按回车时都会出现这些荒谬的消息,但无法在此处添加警告。
  • @Sergi0 - 你的意思是什么消息?如果您指的是 VBEditor 中的消息,您可以通过 Tools >> Options >> Editor >> 取消选中“auto syntax check” 禁用这些消息
  • 是的,我知道。但是自动语法检查不是问题,那个消息框是 :) 我的意思是,来吧,它不再是 Windows 3.11,当人们很高兴看到任何 GUI 时
猜你喜欢
  • 2021-10-13
  • 2019-12-12
  • 2021-05-29
  • 1970-01-01
  • 2019-05-20
  • 2015-10-05
  • 1970-01-01
  • 2013-08-21
  • 1970-01-01
相关资源
最近更新 更多