gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:23:38 24 4
gpt4 key购买 nike

在 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/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com