'Opening Word Doc with VBA results in empty variable
I am trying to copy the contents of a Word document into any cell in Excel. I have the filepath and filename of the document.
I get a variable with 'Nothing' as the value for the contents of the Word document (variable name = 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
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Slaqr |
