首页 > 解决方案 > 使用 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

标签: excelvbams-word

解决方案


此错误是在Documents.Open()方法中输入不兼容的变量类型的结果。

Set wdoc = wapp.Documents.Open(sFilePath & oFile) 

Documents.Open()方法需要输入文件名作为字符串。sFilePath被声明为字符串,而 oFile声明为对象。

在这种情况下,文件对象的.Name属性会生成所需的字符串。因此正确的代码是:

 Set wdoc = wapp.Documents.Open(sFilePath & oFile.Name) 

推荐阅读