【发布时间】:2020-03-21 18:46:57
【问题描述】:
在 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 运行时错误“错误的文件名”
如果我使用ActiveDocument 而不是Documents(),我会得到
4248 运行时错误:“此命令不可用,因为没有打开文档”。
即使在运行代码时打开多个未保存和保存的 Word 文档后,错误仍然存在,只是显示相同的错误消息。
【问题讨论】: