Sub Open_My_Files()
Dim MyFile As String ' File to be appeneded
Dim MyPath As String ' Pathname to where CSV files are kept
Dim shIDS As Worksheet ' Inspection Data Sheet
Dim shCSV As Worksheet ' CSV worksheet
Dim rngAxis As Range
Dim rngNext As Range
Application.DisplayAlerts = False
' Initialize Variable
Set shIDS = Worksheets("Inspection Data Sheet")
MyPath = "C:\\users\amirfar1\desktop\"
MyFile = Dir(MyPath & "*.csv")
' With this synatax, you are telling Dir to get files that match *.csv - no need for an if statement later
' Loop through files
Do While MyFile <> ""
' Open the CSV file
With Workbooks.Open(MyPath & "\" & MyFile)
' We can "get away with the following because we know the CSV file is active since we just opened it.
' We also know that CSV files only have one sheet
' Copy sheet to this workbook
.Sheets(1).Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
' close the workbook
.Close SaveChanges:=False
End With
Set shCSV = ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
shCSV.Name = Replace(MyFile, ".csv", "")
Set rngAxis = shCSV.Cells.Find(What:="axis", _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
If Not rngAxis Is Nothing Then 'Test if axis found
If UCase(rngAxis.Offset(1, 0).Value) = "TP" Then 'Test if TP found below axis
Set rngNext = shIDS.Range("C1:C32, C41:C67, C77:C103, C113:C139").Find("", , xlValues, , 1, 1) 'Find next empty cell
If Not rngNext Is Nothing Then
rngNext.Value = rngAxis.Offset(1, 3).Value 'copy value to empty cell.
Else
'No more empty cells in range
End If
Else
'No TP found after axis
End If
Else
'Axis not found
End If
' Get the next file
MyFile = Dir()
Loop
Application.DisplayAlerts = True
End Sub
Bookmarks