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