I have daily stock data for about two years.
The stock data is in 556 files but is arranged in the same way (note that about 5 additional stocks have been listed over this period). I want to summarize the movements in stock prices on one worksheet by picking them from the 556 files using match and index with my list of stock codes (named "MatchRange"). I've put the file names of the 556 files on row 2 of the summary worksheet.
I've used the code below but isn't working as it should. It just opens the files and closes them. Does anyone have any tips on how I can improve the code?
Sub NSEMerger()
Dim SummarySheet As Worksheet
Dim FolderPath As String
Dim i As Long
Dim n As Long
Dim c As Long
Dim FileName As String
Dim WorkBk As Workbook
Dim MatchRange As Range
Dim LookupRange As Range
Dim IndexRange As Range
'Define where data is being copied to, source folder and counter
Set SummarySheet = ActiveSheet
FolderPath = "C:\Users\lxxxx\Desktop\NSE Attachments\"
i = 1
'Define the size of the match range
n = Application.WorksheetFunction.Count(Range("MatchRange"))
' Call Dir the first time, pointing it to all Excel files in the folder path.
FileName = Dir(FolderPath & "*.xl*")
' Loop for all file names along the top row
Do While FileName = Range("A2").Offset(0, i).Value & ".xls"
' Open a workbook in the folder and define lookup range for match function and index range
Set WorkBk = Workbooks.Open(FolderPath & FileName)
Set LookupRange = WorkBk.Worksheets(1).Range("H:H")
Set IndexRange = WorkBk.Worksheets(1).Range("D:D")
' Open workbook and do match index
For c = 1 To n Step 1
SummarySheet.Range("MatchRange")(c).Offset(0, i).Value = Application.WorksheetFunction.Index(IndexRange, Application.WorksheetFunction.Match(SummarySheet.Range("MatchRange")(c), LookupRange, 0))
Next
' Close the source workbook without saving changes.
WorkBk.Close savechanges:=False
' Increase i to move to next data
i = i + 1
' Use Dir to get the next file name.
FileName = Dir()
Loop
End Sub