I am trying to read the contents of a word document into any cell in excel. I have the filepath and filename of the document correctly written. When I run the code, I get a variable with 'Nothing' as the value for the contents of the word document (variable name = wdoc), but the word document is not an empty document.
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
This error is the result of inputting an incompatible variable type into the Documents.Open() method.
Set wdoc = wapp.Documents.Open(sFilePath & oFile)
The Documents.Open() method requires a filename as a string to be input. While sFilePath is declared as a string, oFile is declared as an object.
In this case the .Name property of the File-object produces the desired string. Thus the correct code is:
Set wdoc = wapp.Documents.Open(sFilePath & oFile.Name)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.