I have code below which open a specific file in a directory. I could have several csv files with BR1 in the name, but want the latest file name containing BR1
I want me code amended so that it attaches the last file name specified in the code
Your assistance in this regard is most appreciated
I want me code amended so that it attaches the last file name specified in the code
Code:
If objFSO.GetExtensionName(objMyFile) = "csv" And UCase(Left(objFSO.GetBaseName(objMyFile), 12)) = UCase("Sales BR1") Then
Your assistance in this regard is most appreciated
Code:
Sub Open_Spec_Files()
Dim objFSO As Object
Dim objMyFolder As Object
Dim objMyFile As Object
Dim wbMyWorkBook As Workbook
Dim lngLastRow As Long
Application.ScreenUpdating = False
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objMyFolder = objFSO.GetFolder("C:\Sales") 'Directory path (WITHOUT trailing backslash!!) where the relevant files reside. Change to suit.
For Each objMyFile In objMyFolder.Files
'If the current file's extension is 'csv' and the first 4 characters of the file name is 'EKRT' (not case sensitive) then...
If objFSO.GetExtensionName(objMyFile) = "csv" And UCase(Left(objFSO.GetBaseName(objMyFile), 12)) = UCase("Sales BR1") Then
'...set the wbMyWorkBook variable by opening the workbook and copy the data from range A4:O[lngLastRow].
Set wbMyWorkBook = Workbooks.Open(objMyFolder & "\" & objMyFile.Name)
'Finds the last row across columns A to O (inclusive) of the first sheet (note a csv file can only have one sheet) in the *.csv file
On Error Resume Next
lngLastRow = wbMyWorkBook.Sheets(1).Range("A:O").Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
On Error GoTo 0
If lngLastRow >= 4 Then
With wbMyWorkBook
.Sheets(1).Range("A4:O" & lngLastRow).Copy Destination:=ThisWorkbook.ActiveSheet.Range("A2")
.Close SaveChanges:=False 'Close the *.csv without saving and changes
End With
End If
End If
Next objMyFile
Set objFSO = Nothing
Set objMyFolder = Nothing
Application.ScreenUpdating = True
End Sub