I am in need to optimizing some VBA which currently works functionally.
Given columns of sequential Dates (column B) and Times (column C), and Given a time window (T1 and T2), return a range of rows in which dates and times fall within T1 and T2. For example, I want MIN and MAX price between those two times.
The goal is to build Open/High/Low/Close charts for Excel candlestick charts and the data source has over 260,000 rows of data.
I currently have the following code that
Dim priceRange As Range
startRowNum = GetFirstRow(StartTime) << THIS TAKE 10 SECONDS
endRowNum = GetLastRow(endTime) << THIS TAKE 10 SECONDS
Set priceRange = Range(Cells(startRowNum, 4), Cells(endRowNum, 4))
targetRange.Offset(0, 2).Value = Application.WorksheetFunction.Max(priceRange)
targetRange.Offset(0, 3).Value = Application.WorksheetFunction.Min(priceRange)
To find the first row...
Function GetFirstRow(T As Date) As Long
'Starts at FirstRow and returns the first row where the time is greater than T1.
Dim currentRow As Long
Dim CompareTime As Date
Dim CompareDate As Date
currentRow = 4 'Start at row4 due to headers.
Do While (IsDate(Cells(currentRow, 2)))
CompareDate = Cells(currentRow, 2)
CompareTime = Cells(currentRow, 3)
marketTime = CompareDate + CompareTime
If (marketTime >= T) Then Exit Do
currentRow = currentRow + 1
Loop
GetFirstRow = currentRow
End Function
GetLastRow is very similar.
My issue is that the GetFirstRow function has to process 49,000 (yes, forty nine thousand) rows, and it takes about 10 seconds.... so it takes "minutes" to complete this run.
Can someone help me optimize this?
Note I Need the date since market data starts the night before. If this is what is slowing me down, I can filter that as I import the data?
Variant Arrayapproach - lots of examples on SOPublic myDynamicArray() As Variatand use the.Resize()property to map your data set so you can then loop through in memory, not a range.