I understand that multiple threads of this question has already been posted by me. They contain wrong information and I have asked for them to be deleted.
Problem: I have a Workbook containing two worksheets "X" and "FILES". The worksheet "FILES" contains the name of each file in a directory on my desktop "C:\Users\Owner\Desktop\DATA-X" in cells (A1:A1000) (There are 1000 files in the folder "DATA-X". The worksheet "X" is a blank worksheet.
The following code loops 1000 times, each time importing the "k"th file from the folder "DATA-X" and storing it in the worksheet "X". After each loop, the worksheet "X" gets replaced with the data in the next file from the folder "DATA-X". As the program is running, it can be seen in the task manager that memory is accumulating in the Excel program. In fact, it cannot finish because it will use up all memory by then (I get a message "OUT OF MEMORY"). Why is this memory leak occuring and how can I fix this? Any help would be greatful.
Sub MemoryTest()
Dim qt As QueryTable
Dim WSh As Worksheet
Sheets("X").Select
For k = 1 To 1000
Cells.Select
Selection.Delete Shift:=xlUp
Range("A1").Select
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & "C:\Users\Owner\Desktop\DATA-X" & "\" & Sheets("FILES").Cells(k, 1).Value _
, Destination:=Range("$A$1"))
.Name = Sheets("FILES").Cells(k, 1)
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Range("A1").Select
Selection.TextToColumns Destination:=Range("A1"), DataType:=xlFixedWidth, _
FieldInfo:=Array(0, 1), TrailingMinusNumbers:=True
For Each WSh In ThisWorkbook.Worksheets
For Each qt In WSh.QueryTables
qt.ResultRange.ClearContents
qt.Delete
Next qt
Next WSh
Do Until ActiveWorkbook.Connections.Count = 0
ActiveWorkbook.Connections(ActiveWorkbook.Connections.Count).Delete
Loop
Next k
End Sub
Bookmarks