![](/img/trans.png)
[英]Opening word template and saving as .doc to current workbook folder - VBA in excel
[英]Opening Word Doc with VBA results in empty variable
我正在尝试将 word 文档的内容读入 excel 中的任何单元格。 我已正确写入文档的文件路径和文件名。 当我运行代码时,我得到了一个变量,它的值为 'Nothing' 作为 word 文档内容的值(变量名 = wdoc),但 word 文档不是空文档。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.