Example: Today's date is 28 November 2011
I have a folder "C:\2011\" which contains xlsx files. For this example, lets say there are 5 files:
Record_28 Jan.xlsx
Record_04 Feb.xlsx
Record_15 Apr.xlsx
Record_22 Jun.xlsx
Record_13 Aug.xlsx
I need a macro that scans in folder "C:\2011\" and opens the file with the closest date.
I have written the following, but it couldn't work. Can someone please help me check what went wrong with this code?
Sub Find_Open_File()
Dim fso As New FileSystemObject
Dim VPath As String
Dim VFile As Scripting.File
Dim VCont As Boolean
Dim VDate As Date
VPath = "C:\2011\"
VCont = True
VDate = VBA.Strings.Format(Date, "dd mmm")
While VCont
If InStr(fso.GetFileName(VFile), VPath & "Record_" & VDate) > 0 Then
VCont = False
Else
VDate = VDate - 1
End If
Wend
ChDir "C:\2011"
Workbooks.Open Filename:= VPath & "Record_" & VDate
End Sub
Additional Details:
I am getting an error message
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Run-time error '91':
Object variable or With block variable not set
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
The code stops at the line after 'While VCont'
Bookmarks