I am trying to loop through a folder and open each word document one at a time in VBA. I had the code working, and then I added two more files to the folder. Now it won't open my first file (which I had opened previously). My code is as follows:
I've tried lots of different things to get it to work again, and I ran out of ideas. Any help would be greatly appreciated.
VBA Code:
Sub readEmailsV2()
Dim oFSO As Object, oFolder As Object, oFile As Object
Dim i As Integer
Dim j As Integer
Dim pN As Integer
Dim sFileSmall As String, sFileYear As String, sFilePath As String
Dim wapp As Word.Application
Dim wdoc As Word.Document
Dim tabDest As Worksheet
Dim splitVals As Variant
Dim contentsVar As String
Dim jContent As String
Dim pageCount As Integer
Dim fpOpen As Variant
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' USER INPUT
sFileSmall = "C:\Users\rstrott\OneDrive - Research Triangle Institute\Desktop\VBApractice\Docket Index\filesToRead\"
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Get variable with filenames from folder (Only contains word docs)
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.getfolder(sFileSmall)
Set tabDest = ThisWorkbook.Sheets("FileContents")
Set wapp = GetObject(, "Word.Application")
If wapp Is Nothing Then
Set wapp = CreateObject("Word.Application")
End If
tabDest.Cells.Clear
tabDest.Range("a1:a1") = "File Title"
tabDest.Range("b1:b1") = "From:"
tabDest.Range("c1:c1") = "To:"
tabDest.Range("d1:d1") = "cc:"
tabDest.Range("e1:e1") = "Date Sent:"
tabDest.Range("f1:f1") = "Subject:"
tabDest.Range("g1:g1") = "Body:"
tabDest.Range("h1:h1") = "Page Count:"
i = 2
For Each oFile In oFolder.Files
' Assign variables
sFilePath = sFileSmall & oFile.Name
wapp.Visible = True
fpOpen = oFile.Path
Set wdoc = wapp.Documents.Open(sFilePath) ' <---- ERROR HERE: Output is 'Nothing'
pN = ActiveDocument.Paragraphs.Count
pageCount = ActiveDocument.ActiveWindow.ActivePane.Pages.Count
' Put paragraph contents in cells
tabDest.Cells(i, 1) = oFile.Name
tabDest.Cells(i, 2) = wdoc.Paragraphs(2)
tabDest.Cells(i, 3) = wdoc.Paragraphs(8)
tabDest.Cells(i, 4) = wdoc.Paragraphs(11)
tabDest.Cells(i, 5) = wdoc.Paragraphs(5)
tabDest.Cells(i, 6) = wdoc.Paragraphs(14)
Dim item As Variant
For j = 15 To pN
jContent = wdoc.Paragraphs(j).Range.Text
If j = 15 And Len(jContent) > 2 Then
contentsVar = wdoc.Paragraphs(j).Range.Text
ElseIf Len(jContent) > 2 Then
contentsVar = contentsVar & Chr(10) & wdoc.Paragraphs(j).Range.Text
End If
Next j
tabDest.Cells(i, 7) = contentsVar
tabDest.Cells(i, 8) = pageCount
' Close Word Doc
wdoc.Close _
SaveChanges:=wdDoNotSaveChanges
i = i + 1
Next oFile
End Sub
I've tried lots of different things to get it to work again, and I ran out of ideas. Any help would be greatly appreciated.