excel - 使用 VBA 打开 Word Doc 会导致空变量
问题描述
我正在尝试将 Word 文档的内容复制到 Excel 中的任何单元格中。我有文档的文件路径和文件名。
我得到一个变量,其中“Nothing”作为 Word 文档内容的值(变量名 = wdoc)。
Sub readEmails()
Dim oFSO As Object, oFolder As Object, oFile As Object
Dim i As Integer
Dim sFileSmall As String, sFileYear As String, sFilePath As String
Dim wapp As Word.Application
Dim wdoc As Word.Document
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' USER INPUT
sFileSmall = "C:\Users\filesToRead\"
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
sFilePath = sFileSmall
' Get variable with filenames from folder (Only contains word docs)
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.getfolder(sFilePath)
i = 1
For Each oFile In oFolder.Files
'Sheet1.Cells(i, 5).Value = oFile.Name
Set wapp = GetObject(, "Word.Application")
If wapp Is Nothing Then
Set wapp = CreateObject("Word.Application")
End If
wapp.Visible = True
Set wdoc = wapp.Documents.Open(sFilePath & oFile) '<---- Error here. Assigns an empty variable
' Range("a1:a1") = wdoc.Content.Text
i = i + 1
Next oFile
End Sub
解决方案
此错误是在Documents.Open()方法中输入不兼容的变量类型的结果。
Set wdoc = wapp.Documents.Open(sFilePath & oFile)
Documents.Open()方法需要输入文件名作为字符串。sFilePath被声明为字符串,而 oFile被声明为对象。
在这种情况下,文件对象的.Name属性会生成所需的字符串。因此正确的代码是:
Set wdoc = wapp.Documents.Open(sFilePath & oFile.Name)
推荐阅读
- python - python 3.6中的youtube视频评论下载器
- typescript - 接口泛型的类型推断
- logging - Kafka 应用程序日志配置
- python - 多类贝叶斯分类器中的得分精度和召回率
- android - 在滚动视图中设置列表视图的最佳主意是什么?
- python-3.x - 如何将报纸库用于需要身份验证的网站?
- jquery - 向下滑动和向上滑动反向
- amazon-web-services - AWS Lambda - 使用 .NET Core 构建无服务器 API
- android - 将谷歌地图放入 AppBarLayout
- java - 如何确定一个进程是否在 Java 中正确终止