I currently have VBA code that opens each text file in a given location and imports data into Excel. The problem is that I have 1000's of text file in the location and I do not want to import them all. I only want to import the 10 most recently created text files. How do I change my Do While loop to achive this?
Sub LoopThroughTextFiles()
' Defines variables
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim Text As String
Dim Textline As String
Dim LastCol As Long
Dim RowCount As Long
' Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Sheets("26").Select
Cells.Select
Selection.ClearContents
Range("A1").Select
' Defines LastCol as the last column of data based on row 1
LastCol = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
' Sets the folder containing the text files
myPath = "C:\26"& "\"' Target File Extension (must include wildcard "*")
myExtension = "*.dat"' Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
' Loop through each text file in folder
Do While myFile <> ""' Sets variable "RowCount" To 1
RowCount = 1
' Sets variable "Text" as blank
Text = ""' Set variable equal to opened text file
Open myPath & myFile For Input As #1
' Do until the last line of the text file
Do Until EOF(1)
' Add each line of the text file to variable "Text"
Line Input #1, Textline
Text = Textline
' Update RowCount row of the current last column with the content of variable "Text"
Cells(RowCount, LastCol).Value = Text
' Increase RowCount by 1
RowCount = RowCount + 1
Loop
' Close the text file
Close #1
' Increase LastCol by 1 to account for the new data
LastCol = LastCol + 1
' Get next text file name
myFile = Dir
Loop