View Single Post
  #1   Report Post  
Posted to microsoft.public.excel.programming
michelle michelle is offline
external usenet poster
 
Posts: 310
Default File not found when opening

Hello all!

I have set up a function that loops through all the files in a certain
folder and find & open a prior month's file and return that file name.
However, when I run the function sometimes (not all the time) I get a
run-time error 1004, file not found. I don't understand why this is since
the loop is only running through the file names in that folder. The file to
be opened is not in use by another user either. My code is below. Any
insight would be amazing. Thanks.

--
Cheers,
Michelle
"Anyone who says he can see through women is missing a lot." Groucho Marx

Sub test()
Const acct As String = "xxx"
Dim tmp As String

tmp = PrevFile(acct)
End Sub

Function PrevFile(acct As String)
Dim myPath As String, myName As String, folder As String
Dim m As Variant
Dim y As Integer
Dim tmp As Variant

m = Month(ThisWorkbook.Worksheets(1).Range("B3").Value ) - 1
If m < 10 Then
m = "0" & m & "_"
Else
m = m & "_"
End If
y = Year(ThisWorkbook.Worksheets(1).Range("B3").Value)
folder = y & " PC Reports"
myPath = "G:\Reports New\" & folder & "\*.xls"
myName = Dir(myPath)
Do
If InStr(1, myName, m, vbTextCompare) 0 And InStr(1, myName, acct,
vbTextCompare) 0 Then
Application.DisplayAlerts = False
Workbooks.Open Filename:=myName, UpdateLinks:=False
Application.DisplayAlerts = True
Exit Do
End If
myName = Dir
MsgBox myName
Loop While myName < ""
PrevFile = myName
End Function