excel - 在 Excel 中使用 VBA 在 Word 中设置范围

标签 excel vba

在 Excel 中使用 VBA 打开该文件时,如何在 Word 中设置范围?

Dim wordApp As Word.Application
Dim wordObject As Word.Document
Dim wordRange As Word.Range

Dim filePath As String
Dim fileName As String

filePath = "C:\Users\"
fileName = "somename.docx"

Set wordApp = CreateObject("Word.Application")

With wordApp
    .Visible = True
    .Activate
    .WindowState = wdWindowStateNormal
End With

Set wordObject = wordApp.Documents.Open(filePath & fileName)

Set wordRange = Documents(fileName).Sections(1).Range

With wordRange
    'code
End With

造成问题的线路:
Set wordRange = Documents(fileName).Sections(1).Range

无论我在此返回中输入的字符串如何

4160 runtime error "Bad File Name"



如果我使用 ActiveDocument而不是 Documents() ,我得到

4248 runtime error: "This command is not available because no document is open".



即使在运行代码时打开多个未保存和保存的 Word 文档后,错误仍然存​​在,只是显示相同的错误消息。

最佳答案

Set wordRange = Documents(fileName).Sections(1).Range错误,因为 Excel 不知道 Documents是(或将其解析为 Word.Documents 以外的其他内容)

要解决此问题,您将使用(就像您在上一行中所做的那样)

Set wordRange = wordApp.Documents(fileName).Sections(1).Range

也就是说,您已经 Set Document(filepath & filename)wordObject ,所以使用它:
Set wordRange = wordObject.Sections(1).Range
此外,Excel 不知道 wdWindowStateNormal , 所以一个新的 Variant变量被创建(除非你有 Option Explicit ,你应该总是这样)并分配默认值 0 .这恰好是 Word.wdWindowStateNormal 的值所以没有伤害,但代码具有误导性。

要修复,请使用
.WindowState = 0 'wdWindowStateNormal

我很好奇您创建对象的方式。使用早期绑定(bind)而不是创建 New Word.Application您使用 CreateObject
  • 这是一个故意的决定吗?
  • 有什么好处?
  • 关于excel - 在 Excel 中使用 VBA 在 Word 中设置范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60131025/

    相关文章:

    java - 使用 Java 从 Excel 电子表格中收集列名称

    excel - 是否可以分阶段运行 VBA 宏以减少运行时间?

    vba - 如何强制 ControlSource 更新(excel 用户窗体)

    vba - MS Access 表单绑定(bind)到 ADO 断开连接的记录集

    c# - 有没有办法使用 C# 在 Excel 中模仿格式刷?

    excel - If Then,满足条件时连接

    excel - 反向组合框 : How to programmatically select an item in ActiveX ComboBox based on a TextBox value?

    excel - 如何通过 VBA 代码终止任务管理器进程?

    excel - 将 Cell.Address 保存在数组中并将其用作单元格公式中的变量

    sql - ms-access:通过在上面打印来填写申请