I want to turn it into function so i can use it on particular Sheets
Assistant
Sure! Could you please share the code or snippet you want to turn into a function? That way, I can help you refactor it properly to work on particular Sheets.
User
Sub GetValuesForDateInterval()
Dim ws As Worksheet
Dim startDate As Date, endDate As Date
Dim startCell As Range, endCell As Range
Dim lastRow As Long
Dim i As Long
Dim currentDate As Date
Dim maxDateLEEnd As Date
Dim minDateGEStart As Date
Dim valForMaxDate As Variant
Dim valForMinDate As Variant
Dim foundMax As Boolean, foundMin As Boolean
code
' Change these ranges to where your start and end datetime cells are located
' For example, they can be in Sheet1 cells D1 (start) and E1 (end)
Dim paramSheet As Worksheet
Set paramSheet = ThisWorkbook.Worksheets("Sheet1") ' Change as needed
Set startCell = paramSheet.Range("D1") ' Start datetime
Set endCell = paramSheet.Range("E1") ' End datetime
startDate = startCell.Value
endDate = endCell.Value
If startDate > endDate Then
MsgBox "Start datetime is greater than end datetime. Please correct them."
Exit Sub
End If
Dim report As String
report = "Sheet: Value at max datetime <= End, Date and Value; Value at min datetime >= Start, Date and Value" & vbCrLf & vbCrLf
' Loop through all worksheets except the parameter input sheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> paramSheet.Name Then
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
foundMax = False
foundMin = False
maxDateLEEnd = 0
minDateGEStart = 0
' Because data is sorted by Date descending,
' iterating from top to bottom means dates go from largest to smallest
' So for maxDate <= End, we'd find the first date <= end from top
' For minDate >= Start, hopefully we can scan entire range as well.
' Initialize minDateGEStart to a very large date (for comparison)
minDateGEStart = DateSerial(9999, 12, 31)
For i = 2 To lastRow ' assuming row 1 has headers
currentDate = ws.Cells(i, "A").Value
' Check and update maxDateLEEnd
If currentDate <= endDate Then
If (Not foundMax) Or (currentDate > maxDateLEEnd) Then
maxDateLEEnd = currentDate
valForMaxDate = ws.Cells(i, "B").Value
foundMax = True
End If
End If
' Check and update minDateGEStart
If currentDate >= startDate Then
If (Not foundMin) Or (currentDate < minDateGEStart) Then
minDateGEStart = currentDate
valForMinDate = ws.Cells(i, "B").Value
foundMin = True
End If
End If
Next i
report = report & ws.Name & ": "
If foundMax Then
report = report & "MaxDate <= End: " & Format(maxDateLEEnd, "yyyy-mm-dd hh:mm:ss") & " Val: " & valForMaxDate & "; "
Else
report = report & "No date <= End found; "
End If
If foundMin Then
report = report & "MinDate >= Start: " & Format(minDateGEStart, "yyyy-mm-dd hh:mm:ss") & " Val: " & valForMinDate
Else
report = report & "No date >= Start found"
End If
report = report & vbCrLf
End If
Next ws
MsgBox report, vbInformation, "Values from Sheets"
End Sub
I have that VBA macros. I want to turn it into function so i can use it on particular Sheets
Assistant
Got it! You want to convert your Sub GetValuesForDateInterval() into a function so that you can call it for particular worksheets and get the values back (instead of looping through all sheets inside the macro).
Here's how to refactor your code:
Make a function that accepts:
a Worksheet object (the sheet to process),
the start date,
the end date.
The function will return a result string (or you can alternatively return a custom data type/object if you want more complex info).
Remove the MsgBox inside the function; return values instead.
You can still keep your parameter sheet part outside and call the function passing the target sheet in a loop or individually.
Refactored code:
vba
Function GetValuesForDateInterval(ws As Worksheet, _
startDate As Date, _
endDate As Date) As String
Dim lastRow As Long
Dim i As Long
Dim currentDate As Date
Dim maxDateLEEnd As Date
Dim minDateGEStart As Date
Dim valForMaxDate As Variant
Dim valForMinDate As Variant
Dim foundMax As Boolean, foundMin As Boolean
' Initialize flags and variables
foundMax = False
foundMin = False
maxDateLEEnd = 0
minDateGEStart = DateSerial(9999, 12, 31) ' very large date
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
For i = 2 To lastRow ' assuming headers in row 1
currentDate = ws.Cells(i, "A").Value
' Check maxDate <= endDate
If currentDate <= endDate Then
If (Not foundMax) Or (currentDate > maxDateLEEnd) Then
maxDateLEEnd = currentDate
valForMaxDate = ws.Cells(i, "B").Value
foundMax = True
End If
End If
' Check minDate >= startDate
If currentDate >= startDate Then
If (Not foundMin) Or (currentDate < minDateGEStart) Then
minDateGEStart = currentDate
valForMinDate = ws.Cells(i, "B").Value
foundMin = True
End If
End If
Next i
' Build output string
Dim result As String
result = ws.Name & ": "
If foundMax Then
result = result & "MaxDate <= End: " & Format(maxDateLEEnd, "yyyy-mm-dd hh:mm:ss") & " Val: " & valForMaxDate & "; "
Else
result = result & "No date <= End found; "
End If
If foundMin Then
result = result & "MinDate >= Start: " & Format(minDateGEStart, "yyyy-mm-dd hh:mm:ss") & " Val: " & valForMinDate
Else
result = result & "No date >= Start found"
End If
GetValuesForDateInterval = result
End Function
User
I want to turn it into macros which work like this - I highlight cells in one Column which are datetime so macros use it like parameters (start and end of time interval) like that (E2 - end, E3 - start, then it write result on F2 and works with next params E3-end, E4 - start and write result of macros on F3).
Assistant
Thanks for the clarification! You want a macro that:
Works on the selected range of cells (which contain datetimes specifying start and end intervals in pairs, e.g. E2=EndDate, E3=StartDate for row 2, then E3=EndDate, E4=StartDate for row 3),
For each pair of End and Start datetime intervals, run calculations on a specific worksheet (or multiple worksheets as you want),
Then write the result next to the corresponding Start cell (e.g., in column F).
Summary of the logic:
The user selects a vertical range of datetime cells,
For each pair (EndDate = current cell, StartDate = next cell), run the function to get those values,
Output the result adjacent to the StartDate cell (i.e., one row down on column F),
Then slide down the range and repeat until no more pairs left (stop at second-last cell because you need pairs).
Here's the approach:
We'll create a Sub macro ProcessDateIntervalsFromSelection,
Use your GetValuesForDateInterval function to get results (adjusted for one sheet or multiple),
Write the output in column F next to each start date (note that start date is the next cell after end date).
The code implementations
Step 1: Update your function slightly to accept worksheet(s)
Let’s assume you want to run this on a specific worksheet named "Data" (or you can adjust the code to loop multiple sheets):
vba
User
I wanted to add to result a result from other Sheet and i have an error because of function returning string value. I need to turn it into returning number value so i can sum values of result of function from different Sheets
Assistant
Understood! You want your function to return numeric results (e.g., a sum or specific numeric value from the sheet based on the date interval) instead of a descriptive string, so you can add/sum results returned from multiple sheets.
What numeric value exactly do you want returned from each sheet?
The current function finds two "values" (from column B):
The value corresponding to the max date ≤ endDate (call it valForMaxDate),
The value corresponding to the min date ≥ startDate (call it valForMinDate).
You can return:
Either one of these values,
Their sum,
Their difference,
Something else numeric built from these two.
Let's assume you want the sum of these two values per sheet; you can adjust as needed.
⚠️ Important: you must be careful with data types — the values from column B can be numeric or non-numeric (text). Only numeric values should contribute to the numeric result; otherwise, they should be treated as zero or ignored.
Here's how to modify GetValuesForDateInterval to return a Double (a numeric type) and ignore non-numeric values safely:
vba
User
I have an error ByRef argument type mismatch. I used your function and my sub macros -
Sub ProcessDateIntervalsFromSelection()
Dim selRange As Range
Dim wsData As Worksheet
Dim i As Long
Dim endDate As Date
Dim startDate As Date
Dim outputCell As Range
Dim result As String
code
Assistant
Thanks for sharing your code.
Problem explanation:
The error
code
ByRef argument type mismatch
means you are passing a value to a parameter expecting a different type - or you are mixing String variables with numeric function return values.
What is wrong in your code?
Your function:
vba
Function GetValuesForDateInterval(...) As Double
returns a Double (number).
But in your sub:
vba
Dim result As String
...
result = GetValuesForDateInterval(...)
result = result + GetValuesForDateInterval(...)
you declared result as String, but you're performing numeric addition with + on the function return values. This causes a type mismatch error because VBA can't add numbers to strings directly.
How to fix?
You must declare result as Double (or Variant), NOT as String in your Sub:
vba
Dim result As Double
And initialize it accordingly.
Corrected relevant parts of your macro:
vba
User
Okay i fixed it. Now this line - If IsDate(selRange.Cells(i, 1).Value) And IsDate(selRange.Cells(i + 1, 1).Value) Then - always returning false and macros doesnt work. How to fix it?
Assistant
If IsDate(selRange.Cells(i, 1).Value) is always returning False, it means VBA is not recognizing the cell content as a valid date.
This issue often arises due to:
Cell being empty or containing text instead of valid date/time.
Date stored as text but in a format VBA does not recognize.
Leading/trailing spaces or other invisible characters in the cells.
Regional settings mismatch (dates in format VBA doesn't parse properly).
The cell actually contains a formula resulting in text.
Things to check and solutions:
1. Make sure the cells actually hold Excel-recognized dates, not text
Try this in your workbook for your selected range column (e.g., Column E):
Select the cells
Format them as Date (Right-click → Format Cells → Date)
Or use Excel formula in a spare column next to your data: =ISNUMBER(E2)
If this returns TRUE, it's a numeric date.
If FALSE, it's text or invalid.
If the dates are stored as text you need to convert them, e.g.:
Use Text to Columns on your column with fixed date format.
Or use a formula to convert text date to date, e.g. =DATEVALUE(E2) or =--E2.
2. Add trimming / cleaning in VBA before IsDate
Sometimes cells look like dates but contain spaces or hidden chars.
Try modifying your VBA check:
vba
Dim testText As String
testText = Trim(selRange.Cells(i, 1).Text)
If IsDate(testText) And IsDate(Trim(selRange.Cells(i + 1, 1).Text)) Then
' use CDate(testText) to convert string to date properly
startDate = CDate(Trim(selRange.Cells(i + 1, 1).Text))
endDate = CDate(testText)
'...
Else
' not date
End If
Note: Use .Text property (the displayed text) or .Value (the raw underlying value). Sometimes .Text is more consistent if the cell contains formulas or formatted text.
3. Debug print the cell values / types to inspect
Insert debug lines before your If to see what VBA is actually reading:
vba
User
I use datetimes from Microsoft SQL Server. Does it matter? And how to fix it?
Assistant
Thanks for the info — since your dates come from Microsoft SQL Server, Excel sometimes imports these datetimes as text strings, depending on how the data is brought in (e.g., via ODBC, copy-paste, Power Query, etc.). This can cause the IsDate() function in VBA to return False even if the cells look like datetime because the cell contents are strings, possibly in a format Excel VBA does not automatically recognize as Date.
Why does it matter?
SQL Server datetimes often come formatted as ISO standard strings (e.g., "2023-06-14 15:30:00").
Excel VBA’s IsDate() can be locale dependent and may not recognize certain datetime string formats.
If Excel treats SQL datetime strings as text, IsDate() returns False.
How to fix it?
Approach 1: Convert SQL datetime string format explicitly in VBA using CDate or DateValue + TimeValue
If you know your SQL datetime format (e.g., yyyy-mm-dd hh:mm:ss), VBA may not recognize it automatically.
You can parse the string to extract parts and rebuild a date.
Example code snippet to convert a SQL datetime string to VBA Date:
vba
Function ParseSQLDateTime(s As String) As Variant
' Expects s like "yyyy-mm-dd hh:mm:ss" or "yyyy-mm-ddThh:mm:ss"
' Returns Date if successful, else CVErr
Dim dt As Date
Dim datePart As String, timePart As String
Dim spacePos As Long
On Error GoTo fail
' Find space between date and time
spacePos = InStr(s, " ")
If spacePos = 0 Then spacePos = InStr(s, "T") ' Handle ISO format with T
If spacePos > 0 Then
datePart = Left(s, spacePos - 1)
timePart = Mid(s, spacePos + 1)
Else
' If no time part, just date
datePart = s
timePart = "00:00:00"
End If
dt = DateValue(datePart) + TimeValue(timePart)
ParseSQLDateTime = dt
Exit Function
fail:
ParseSQLDateTime = CVErr(xlErrValue)
End Function
User
I use copy paste from table Microsoft SQL Server. I used your ParseSQLDateTime function and while debugging it going to that line fail:
ParseSQLDateTime = CVErr(xlErrValue) - so macros doesnt works correct
Assistant
Thanks for the update. Since your pasted SQL Server datetime strings are going to the error line in the ParseSQLDateTime function, it means the function is unable to parse the string successfully using DateValue and TimeValue.
Let’s debug and fix it step-by-step
Step 1: Check exactly how the pasted datetime looks in Excel
Before proceeding, let’s verify how the datetime strings appear when copied from SQL Server into Excel.
Please do this:
Select the cell containing one of those pasted SQL Server datetimes.
The exact format of the string (the brackets will show leading/trailing spaces or invisible chars).
Step 2: Adjust parser to your exact format
Your SQL Server strings may use a format like:
"2023-06-14 15:30:00"
Or "2023-06-14T15:30:00" (ISO8601)
Or may have milliseconds: "2023-06-14 15:30:00.000"
Or other variation
Updated ParseSQLDateTime function (robust to trailing milliseconds and spaces)
vba
User
I have format like this "2023-06-14 15:30:00.000"
Assistant
Thanks for confirming the format "2023-06-14 15:30:00.000".
The updated ParseSQLDateTime I gave you handles exactly that format by trimming off the milliseconds (.000) part — so it should work correctly.
Here's the function again just to be sure, tuned precisely for your datetime format:
vba
Function ParseSQLDateTime(s As String) As Variant
' Parses SQL Server datetime strings like "2023-06-14 15:30:00.000"
' Returns Date if parsing succeeds, else CVErr
Dim dt As Date
Dim datePart As String, timePart As String
Dim spacePos As Long
Dim dotPos As Long
On Error GoTo fail
s = Trim(s)
If s = "" Then GoTo fail
' Find space between date and time parts
spacePos = InStr(s, " ")
If spacePos = 0 Then
' No time part, treat entire string as date only
ParseSQLDateTime = DateValue(s)
Exit Function
End If
datePart = Left(s, spacePos - 1)
timePart = Mid(s, spacePos + 1)
' Remove milliseconds if present
dotPos = InStr(timePart, ".")
If dotPos > 0 Then
timePart = Left(timePart, dotPos - 1)
End If
dt = DateValue(datePart) + TimeValue(timePart)
ParseSQLDateTime = dt
Exit Function
fail:
ParseSQLDateTime = CVErr(xlErrValue)
End Function
How to use in your macro loop:
vba
Dim vEnd As Variant, vStart As Variant
Dim endDate As Date, startDate As Date
vEnd = ParseSQLDateTime(selRange.Cells(i, 1).Text)
vStart = ParseSQLDateTime(selRange.Cells(i + 1, 1).Text)
If Not IsError(vEnd) And Not IsError(vStart) Then
endDate = vEnd
startDate = vStart
If startDate > endDate Then
' Handle invalid interval
Else
' Call your GetValuesForDateInterval function here
End If
Else
' Handle invalid datetime strings
End If
Final notes:
Be sure to use .Text property on the cells (selRange.Cells(i,1).Text) so you get the actual text that looks like "2023-06-14 15:30:00.000".
If your imported datetime strings sometimes include trailing spaces or non-printable characters, Trim will handle that.
This parser will convert your format correctly into VBA Date.
If you still get errors after this, please share the exact VBA debugging output of Debug.Print "[" & selRange.Cells(i, 1).Text & "]" so I can see the exact cell content as VBA reads it.
Let me know if you want me to update the full macro including this date parsing!
User
Sorry i lied. i have format like this "24.06.2023 15:30:00.000"
Assistant
Thanks for the clarification — with the format "24.06.2023 15:30:00.000" (day.month.year), the previous parsing approach using DateValue won’t work directly because DateValue expects dates in the system locale format (usually mm/dd/yyyy or yyyy-mm-dd).
This is the problem:
Your day and month are separated by dots (.), like "24.06.2023".
VBA’s DateValue does not recognize dd.mm.yyyy format reliably.
You need to manually parse day, month, and year parts from the string and rebuild the VBA date.
How to handle "dd.mm.yyyy hh:mm:ss.000" format in VBA
We’ll write a custom parser that:
Splits the date part by dots (.),
Extracts day, month, year as integers,
Parses the time part (without milliseconds),
Combines into a Date variable.
Updated parser function for dd.mm.yyyy hh:mm:ss.fff:
vba
Not yet included in a published release.
Example how to use this function in a Sub, for instance reading dates from your parameter sheet and calling it on specific sheets:
vba
Sub TestGetValuesForDateInterval()
Dim paramSheet As Worksheet
Set paramSheet = ThisWorkbook.Worksheets("Sheet1") ' Parameter input sheet
Dim startDate As Date
Dim endDate As Date
startDate = paramSheet.Range("D1").Value
endDate = paramSheet.Range("E1").Value
If startDate > endDate Then
MsgBox "Start datetime is greater than end datetime. Please correct them."
Exit Sub
End If
Dim ws As Worksheet
Dim report As String
report = "Sheet: Value at max datetime <= End, Date and Value; Value at min datetime >= Start, Date and Value" & vbCrLf & vbCrLf
' Example: call function only for sheets named "Data1" and "Data2"
On Error Resume Next
Set ws = ThisWorkbook.Worksheets("Data1")
If Not ws Is Nothing Then
report = report & GetValuesForDateInterval(ws, startDate, endDate) & vbCrLf
End If
Set ws = ThisWorkbook.Worksheets("Data2")
If Not ws Is Nothing Then
report = report & GetValuesForDateInterval(ws, startDate, endDate) & vbCrLf
End If
On Error GoTo 0
MsgBox report, vbInformation, "Values from Specified Sheets"
End Sub
Summary
GetValuesForDateInterval is now a pure function working on one worksheet at a time.
You call it passing the sheet, start date, and end date.
You can then aggregate or display the results as you prefer.
If you'd like, I can also help you make it return a custom Type or output to cells instead of a string report. Just let me know!
Function GetValuesForDateInterval(ws As Worksheet, _
startDate As Date, _
endDate As Date) As String
Dim lastRow As Long
Dim i As Long
Dim currentDate As Date
Dim maxDateLEEnd As Date
Dim minDateGEStart As Date
Dim valForMaxDate As Variant
Dim valForMinDate As Variant
Dim foundMax As Boolean, foundMin As Boolean
foundMax = False
foundMin = False
maxDateLEEnd = 0
minDateGEStart = DateSerial(9999, 12, 31) ' very large date
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
For i = 2 To lastRow ' assuming headers in row 1
currentDate = ws.Cells(i, "A").Value
' Validate if cell contains date
If IsDate(currentDate) Then
If currentDate <= endDate Then
If (Not foundMax) Or (currentDate > maxDateLEEnd) Then
maxDateLEEnd = currentDate
valForMaxDate = ws.Cells(i, "B").Value
foundMax = True
End If
End If
If currentDate >= startDate Then
If (Not foundMin) Or (currentDate < minDateGEStart) Then
minDateGEStart = currentDate
valForMinDate = ws.Cells(i, "B").Value
foundMin = True
End If
End If
End If
Next i
Dim result As String
result = ws.Name & ": "
If foundMax Then
result = result & "MaxDate ≤ End: " & Format(maxDateLEEnd, "yyyy-mm-dd hh:mm:ss") & " Val: " & valForMaxDate & "; "
Else
result = result & "No date ≤ End found; "
End If
If foundMin Then
result = result & "MinDate ≥ Start: " & Format(minDateGEStart, "yyyy-mm-dd hh:mm:ss") & " Val: " & valForMinDate
Else
result = result & "No date ≥ Start found"
End If
GetValuesForDateInterval = result
End Function
Step 2: Create the macro to loop through the selected cells and process pairs
vba
Sub ProcessDateIntervalsFromSelection()
Dim selRange As Range
Dim wsData As Worksheet
Dim i As Long
Dim endDate As Date
Dim startDate As Date
Dim outputCell As Range
Dim result As String
' Set your data sheet name here
Set wsData = ThisWorkbook.Worksheets("Data") ' change to your data sheet name
' Get the selected cells
Set selRange = Selection
' Check if selection is at least two cells to process pairs
If selRange.Cells.Count < 2 Then
MsgBox "Select at least two cells vertically in one column containing datetime values.", vbExclamation
Exit Sub
End If
' Make sure selection is in one column (you said one column)
If selRange.Columns.Count > 1 Then
MsgBox "Please select cells in only one column.", vbExclamation
Exit Sub
End If
Application.ScreenUpdating = False
' Loop through selected cells' pairs:
' For rows from first cell to second last cell:
' - current cell as EndDate
' - next cell as StartDate
For i = 1 To selRange.Rows.Count - 1
' Read dates - validate if they are dates
If IsDate(selRange.Cells(i, 1).Value) And IsDate(selRange.Cells(i + 1, 1).Value) Then
endDate = selRange.Cells(i, 1).Value
startDate = selRange.Cells(i + 1, 1).Value
' Optional: validate the date order, if startDate > endDate swap or alert
If startDate > endDate Then
result = "Start date > End date - invalid interval"
Else
' Call your function for the data sheet
result = GetValuesForDateInterval(wsData, startDate, endDate)
End If
Else
result = "Invalid date(s) in selection"
End If
' Output adjacent to the StartDate cell (i+1 row, same row as startDate)
Set outputCell = selRange.Cells(i + 1, 1).Offset(0, 1) ' offset 1 column to the right (e.g. into column F if selected in E)
outputCell.Value = result
Next i
Application.ScreenUpdating = True
MsgBox "Processing complete.", vbInformation
End Sub
How to use
Select a vertical range of adjacent cells in one column (for example, E2:E10), where each cell contains a datetime.
These dates represent alternating EndDate (current cell) and StartDate (next cell) pairs:
E2 is End, E3 is Start -> Result in F3
E3 is End, E4 is Start -> Result in F4
etc.
Run macro ProcessDateIntervalsFromSelection.
The results will be written next to the Start Date cell in column F.
Notes & Adjustments
Make sure your "Data" worksheet is named exactly or change wsData = ThisWorkbook.Worksheets("Data") to your data sheet name.
Data worksheet should have the datetime in column A and associated value in column B.
The code currently expects selection in one column and expects at least 2 rows.
Output is written 1 column to the right of the selection (adjust .Offset(0,1) if you want a different output column).
It skips rows with invalid or missing dates.
You can modify the function to loop multiple sheets or pass different sheets as needed on each iteration.
If you want me to expand this to handle multiple data sheets or to automatically pick sheets excluding certain ones, just say so!
Function GetValuesForDateInterval(ws As Worksheet, _
startDate As Date, _
endDate As Date) As Double
Dim lastRow As Long
Dim i As Long
Dim currentDate As Date
Dim maxDateLEEnd As Date
Dim minDateGEStart As Date
Dim valForMaxDate As Variant
Dim valForMinDate As Variant
Dim foundMax As Boolean, foundMin As Boolean
foundMax = False
foundMin = False
maxDateLEEnd = 0
minDateGEStart = DateSerial(9999, 12, 31) ' very large date
valForMaxDate = 0
valForMinDate = 0
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
For i = 2 To lastRow ' assuming headers in row 1
currentDate = ws.Cells(i, "A").Value
If IsDate(currentDate) Then
If currentDate <= endDate Then
If (Not foundMax) Or (currentDate > maxDateLEEnd) Then
maxDateLEEnd = currentDate
valForMaxDate = ws.Cells(i, "B").Value
foundMax = True
End If
End If
If currentDate >= startDate Then
If (Not foundMin) Or (currentDate < minDateGEStart) Then
minDateGEStart = currentDate
valForMinDate = ws.Cells(i, "B").Value
foundMin = True
End If
End If
End If
Next i
' Validate the values are numeric, else treat as zero
If Not IsNumeric(valForMaxDate) Then valForMaxDate = 0
If Not IsNumeric(valForMinDate) Then valForMinDate = 0
' Return the sum of both values for example
GetValuesForDateInterval = CDbl(valForMaxDate) + CDbl(valForMinDate)
End Function
How to sum results from multiple sheets?
Now, if you want to combine results from multiple sheets, you can do this in your calling code, for example:
vba
Sub CombineResultsFromSheets()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim startDate As Date, endDate As Date
Dim totalResult As Double
Set ws1 = ThisWorkbook.Worksheets("Data") ' first data sheet
Set ws2 = ThisWorkbook.Worksheets("OtherData") ' second data sheet (example)
startDate = Worksheets("Sheet1").Range("E3").Value ' example start date
endDate = Worksheets("Sheet1").Range("E2").Value ' example end date
totalResult = 0
totalResult = totalResult + GetValuesForDateInterval(ws1, startDate, endDate)
totalResult = totalResult + GetValuesForDateInterval(ws2, startDate, endDate)
MsgBox "Total summed value = " & totalResult, vbInformation
End Sub
If you want this inside your ProcessDateIntervalsFromSelection macro so it sums multiple sheets for each date interval, here is an example snippet (modify as needed):
vba
Sub ProcessDateIntervalsSumMultipleSheets()
Dim selRange As Range
Dim wsData1 As Worksheet, wsData2 As Worksheet
Dim i As Long
Dim endDate As Date, startDate As Date
Dim outputCell As Range
Dim resultSum As Double
Set wsData1 = ThisWorkbook.Worksheets("Data")
Set wsData2 = ThisWorkbook.Worksheets("OtherData")
Set selRange = Selection
If selRange.Cells.Count < 2 Then
MsgBox "Select at least two cells vertically in one column containing datetime values.", vbExclamation
Exit Sub
End If
If selRange.Columns.Count > 1 Then
MsgBox "Please select cells in only one column.", vbExclamation
Exit Sub
End If
Application.ScreenUpdating = False
For i = 1 To selRange.Rows.Count - 1
If IsDate(selRange.Cells(i, 1).Value) And IsDate(selRange.Cells(i + 1, 1).Value) Then
endDate = selRange.Cells(i, 1).Value
startDate = selRange.Cells(i + 1, 1).Value
If startDate > endDate Then
resultSum = 0 ' or some error code/value
Else
resultSum = 0
resultSum = resultSum + GetValuesForDateInterval(wsData1, startDate, endDate)
resultSum = resultSum + GetValuesForDateInterval(wsData2, startDate, endDate)
' Add more sheets if you want here
End If
Else
resultSum = 0 ' or maybe write error indication if needed
End If
Set outputCell = selRange.Cells(i + 1, 1).Offset(0, 1)
outputCell.Value = resultSum
Next i
Application.ScreenUpdating = True
MsgBox "Processing complete.", vbInformation
End Sub
Summary:
Modify your function to return Double (number), not string.
Decide on numeric output logic (sum here, but adjust if needed).
Ensure you handle non-numeric values in data cells safely.
Sum the numeric results from multiple sheets in your calling macro/sub,
Output the numeric result in the desired cells.
If you'd like help customizing the numeric calculation (e.g., just maxDate val, or minDate val, or something else), just say!
' Set your data sheet name here
Set wsData = ThisWorkbook.Worksheets("INF10") ' change to your data sheet name
Set wsData1 = ThisWorkbook.Worksheets("INF11")
Set wsData2 = ThisWorkbook.Worksheets("INF12")
Set wsData3 = ThisWorkbook.Worksheets("INF13")
Set wsData4 = ThisWorkbook.Worksheets("INF14")
Set wsData5 = ThisWorkbook.Worksheets("INF15")
Set wsData6 = ThisWorkbook.Worksheets("INF16")
Set wsData7 = ThisWorkbook.Worksheets("INF17")
Set wsData8 = ThisWorkbook.Worksheets("INF18")
Set wsData9 = ThisWorkbook.Worksheets("INF19")
' Get the selected cells
Set selRange = Selection
' Check if selection is at least two cells to process pairs
If selRange.Cells.Count < 2 Then
MsgBox "Select at least two cells vertically in one column containing datetime values.", vbExclamation
Exit Sub
End If
' Make sure selection is in one column (you said one column)
If selRange.Columns.Count > 1 Then
MsgBox "Please select cells in only one column.", vbExclamation
Exit Sub
End If
Application.ScreenUpdating = False
' Loop through selected cells' pairs:
' For rows from first cell to second last cell:
' - current cell as EndDate
' - next cell as StartDate
For i = 1 To selRange.Rows.Count - 1
' Read dates - validate if they are dates
If IsDate(selRange.Cells(i, 1).Value) And IsDate(selRange.Cells(i + 1, 1).Value) Then
endDate = selRange.Cells(i, 1).Value
startDate = selRange.Cells(i + 1, 1).Value
' Optional: validate the date order, if startDate > endDate swap or alert
If startDate > endDate Then
result = "Start date > End date - invalid interval"
Else
' Call your function for the data sheet
result = GetValuesForDateInterval(wsData, startDate, endDate)
result = result + GetValuesForDateInterval(wsData1, startDate, endDate)
result = result + GetValuesForDateInterval(wsData2, startDate, endDate)
result = result + GetValuesForDateInterval(wsData3, startDate, endDate)
result = result + GetValuesForDateInterval(wsData4, startDate, endDate)
result = result + GetValuesForDateInterval(wsData5, startDate, endDate)
result = result + GetValuesForDateInterval(wsData6, startDate, endDate)
result = result + GetValuesForDateInterval(wsData7, startDate, endDate)
result = result + GetValuesForDateInterval(wsData8, startDate, endDate)
result = result + GetValuesForDateInterval(wsData9, startDate, endDate)
End If
Else
result = "Invalid date(s) in selection"
End If
' Output adjacent to the StartDate cell (i+1 row, same row as startDate)
Set outputCell = selRange.Cells(i + 1, 1).Offset(0, 1) ' offset 1 column to the right (e.g. into column F if selected in E)
outputCell.Value = result
Next i
Application.ScreenUpdating = True
MsgBox "Processing complete.", vbInformation
End Sub
Sub ProcessDateIntervalsFromSelection()
Dim selRange As Range
Dim wsData As Worksheet
Dim wsData1 As Worksheet, wsData2 As Worksheet, wsData3 As Worksheet, wsData4 As Worksheet
Dim wsData5 As Worksheet, wsData6 As Worksheet, wsData7 As Worksheet, wsData8 As Worksheet, wsData9 As Worksheet
Dim i As Long
Dim endDate As Date
Dim startDate As Date
Dim outputCell As Range
Dim result As Double ' <-- Change from String to Double
Set wsData = ThisWorkbook.Worksheets("INF10") ' adjust as needed
Set wsData1 = ThisWorkbook.Worksheets("INF11")
Set wsData2 = ThisWorkbook.Worksheets("INF12")
Set wsData3 = ThisWorkbook.Worksheets("INF13")
Set wsData4 = ThisWorkbook.Worksheets("INF14")
Set wsData5 = ThisWorkbook.Worksheets("INF15")
Set wsData6 = ThisWorkbook.Worksheets("INF16")
Set wsData7 = ThisWorkbook.Worksheets("INF17")
Set wsData8 = ThisWorkbook.Worksheets("INF18")
Set wsData9 = ThisWorkbook.Worksheets("INF19")
Set selRange = Selection
If selRange.Cells.Count < 2 Then
MsgBox "Select at least two cells vertically in one column containing datetime values.", vbExclamation
Exit Sub
End If
If selRange.Columns.Count > 1 Then
MsgBox "Please select cells in only one column.", vbExclamation
Exit Sub
End If
Application.ScreenUpdating = False
For i = 1 To selRange.Rows.Count - 1
If IsDate(selRange.Cells(i, 1).Value) And IsDate(selRange.Cells(i + 1, 1).Value) Then
endDate = selRange.Cells(i, 1).Value
startDate = selRange.Cells(i + 1, 1).Value
If startDate > endDate Then
' If you want to write an error message as text, you need a separate variable
result = 0
Set outputCell = selRange.Cells(i + 1, 1).Offset(0, 1)
outputCell.Value = "Start date > End date - invalid interval"
Else
' Sum the values properly as Double
result = 0
result = result + GetValuesForDateInterval(wsData, startDate, endDate)
result = result + GetValuesForDateInterval(wsData1, startDate, endDate)
result = result + GetValuesForDateInterval(wsData2, startDate, endDate)
result = result + GetValuesForDateInterval(wsData3, startDate, endDate)
result = result + GetValuesForDateInterval(wsData4, startDate, endDate)
result = result + GetValuesForDateInterval(wsData5, startDate, endDate)
result = result + GetValuesForDateInterval(wsData6, startDate, endDate)
result = result + GetValuesForDateInterval(wsData7, startDate, endDate)
result = result + GetValuesForDateInterval(wsData8, startDate, endDate)
result = result + GetValuesForDateInterval(wsData9, startDate, endDate)
Set outputCell = selRange.Cells(i + 1, 1).Offset(0, 1)
outputCell.Value = result
End If
Else
Set outputCell = selRange.Cells(i + 1, 1).Offset(0, 1)
outputCell.Value = "Invalid date(s) in selection"
End If
Next i
Application.ScreenUpdating = True
MsgBox "Processing complete.", vbInformation
End Sub
Bonus: If you want to output error strings, use a Variant or separate variables:
Since result stores the sum (a number), but your macro also outputs error string messages, you cannot store both in result (which is a Double).
Good practice:
Use a Variant for the output or
Write error messages directly to the output cell and skip writing result there.
I showed above how to write the error message directly to output cell and keep result numeric only.
Summary:
Change Dim result As String → Dim result As Double
When error message is needed, output it directly to output cell outside numeric variable
Do numeric addition with result as Double
Let me know if you'd like me to refactor further or wrap this in error handling!
Check the Immediate Window (Ctrl+G) in VBA editor to see output.
Expected correct numeric date VarType value is 7 (Double). If it’s something else, need to convert or fix.
4. Try explicit date conversion with error handling
If dates come as strings, try to convert with CDate wrapped in error handler:
vba
Function IsValidDate(val As Variant) As Boolean
On Error Resume Next
Dim d As Date
d = CDate(val)
IsValidDate = (Err.Number = 0)
On Error GoTo 0
End Function
Then in your main loop:
vba
If IsValidDate(selRange.Cells(i, 1).Value) And IsValidDate(selRange.Cells(i + 1, 1).Value) Then
endDate = CDate(selRange.Cells(i, 1).Value)
startDate = CDate(selRange.Cells(i + 1, 1).Value)
'...
Else
' not dates
End If
Quick fix snippet to test (replace your date check):
vba
Function SafeGetDate(cell As Range) As Variant
On Error Resume Next
SafeGetDate = CDate(Trim(cell.Text)) ' or cell.Value
If Err.Number <> 0 Then
SafeGetDate = CVErr(xlErrValue) ' error
End If
On Error GoTo 0
End Function
Sub YourMacro()
Dim date1 As Variant, date2 As Variant
'...
For i = 1 To selRange.Rows.Count - 1
date1 = SafeGetDate(selRange.Cells(i, 1))
date2 = SafeGetDate(selRange.Cells(i + 1, 1))
If Not IsError(date1) And Not IsError(date2) Then
' dates are valid
endDate = date1
startDate = date2
' continue your code
Else
' invalid dates
End If
Next i
End Sub
Summary
Ensure your date cells truly contain dates, not text.
Use Trim() to remove spaces.
Debug with Debug.Print.
Use a safe date conversion function instead of direct IsDate() on .Value.
Convert with CDate after validation.
If you want, I can help you finalize your macro with this robust date handling included!
Usage example in your macro:
Replace your date checking like this:
vba
Dim v1 As Variant, v2 As Variant
v1 = ParseSQLDateTime(selRange.Cells(i, 1).Text)
v2 = ParseSQLDateTime(selRange.Cells(i + 1, 1).Text)
If Not IsError(v1) And Not IsError(v2) Then
endDate = v1
startDate = v2
' proceed...
Else
' dates invalid
End If
Approach 2: Convert your SQL datetimes to Excel-recognized dates BEFORE running VBA
If you use Power Query or import wizard, set the column type to DateTime.
If you paste from SQL Server Management Studio (SSMS), sometimes it pastes as text, so convert in Excel by:
Using Data → Text to Columns → Finish (this forces Excel to parse text to dates)
Or create helper column with formula =DATEVALUE(LEFT(A2,10)) + TIMEVALUE(MID(A2,12,8))
Approach 3: Use CDate with error handling directly
CDate can parse many date formats, but if SQL date format is not recognized, parse manually as in Approach 1.
Summary
SQL Server datetime strings are often not recognized by IsDate in VBA.
Manual parsing of the datetime string to VBA Date is usually necessary.
Use the ParseSQLDateTime function above to reliably convert the strings.
Update your main processing macro to use this parsing function before using the dates.
Final note
If you show me a sample of how your datetime appears in Excel — e.g., "2023-06-14 15:30:00" in cell, or a variant like 2023-06-14T15:30:00 — I can tailor the parser even better.
Let me know if you want me to help fully integrate this parsing function into your macro!
Function ParseSQLDateTime(s As String) As Variant
' Parses SQL Server datetime strings like:
' "2023-06-14 15:30:00", "2023-06-14T15:30:00", "2023-06-14 15:30:00.000"
' Returns Date if ok, else CVErr
Dim dt As Date
Dim datePart As String, timePart As String
Dim spacePos As Long
Dim dotPos As Long
On Error GoTo fail
s = Trim(s)
If s = "" Then GoTo fail
' Find space or T separator between date and time
spacePos = InStr(s, " ")
If spacePos = 0 Then spacePos = InStr(s, "T")
If spacePos = 0 Then
' No time part, just date
ParseSQLDateTime = DateValue(s)
Exit Function
Else
datePart = Left(s, spacePos - 1)
timePart = Mid(s, spacePos + 1)
End If
' Remove milliseconds if present in time part (e.g., "15:30:00.000" -> "15:30:00")
dotPos = InStr(timePart, ".")
If dotPos > 0 Then
timePart = Left(timePart, dotPos - 1)
End If
' Parse and combine
dt = DateValue(datePart) + TimeValue(timePart)
ParseSQLDateTime = dt
Exit Function
fail:
ParseSQLDateTime = CVErr(xlErrValue)
End Function
Step 3: Use this function in your processing macro (example)
vba
Dim v1 As Variant, v2 As Variant
v1 = ParseSQLDateTime(selRange.Cells(i, 1).Text)
v2 = ParseSQLDateTime(selRange.Cells(i + 1, 1).Text)
If Not IsError(v1) And Not IsError(v2) Then
endDate = v1
startDate = v2
' proceed...
Else
' invalid dates handle here
End If
Step 4: Additional tip — convert pasted strings in Excel to real datetime
If you want a one-time fix, you can convert all pasted SQL Server datetime strings in Excel into proper VBA-recognized dates with this quick macro:
vba
Sub ConvertSQLDateStringsToDates()
Dim c As Range
For Each c In Selection
If Not IsEmpty(c) Then
Dim dt As Variant
dt = ParseSQLDateTime(c.Text)
If Not IsError(dt) Then
c.Value = dt
c.NumberFormat = "yyyy-mm-dd hh:mm:ss"
End If
End If
Next c
End Sub
Run this after you paste your SQL data into Excel, selecting the datetime cells first. It will overwrite the text with real dates.
Summary:
Use updated ParseSQLDateTime which handles milliseconds.
Check the exact format of your pasted datetime strings with debugging output.
Optionally convert strings to real dates in Excel with macro.
Then your main automation VBA using these parsed dates will work fine.
If you want, share a sample exact datetime string copied from your sheet, and I’ll help adapt code precisely!
Function ParseCustomDateTime(s As String) As Variant
' Parses datetime strings like "24.06.2023 15:30:00.000"
' Returns Date if parse succeeds, else CVErr
Dim dtDate As Date
Dim dtTime As Date
Dim parts() As String
Dim datePart As String, timePart As String
Dim dayPart As Integer, monthPart As Integer, yearPart As Integer
Dim spacePos As Long
Dim dotPos As Long
On Error GoTo fail
s = Trim(s)
If s = "" Then GoTo fail
' Split date/time by space
spacePos = InStr(s, " ")
If spacePos = 0 Then
' No time part; try only date parse assuming dd.mm.yyyy
parts = Split(s, ".")
If UBound(parts) <> 2 Then GoTo fail
dayPart = CInt(parts(0))
monthPart = CInt(parts(1))
yearPart = CInt(parts(2))
dtDate = DateSerial(yearPart, monthPart, dayPart)
ParseCustomDateTime = dtDate
Exit Function
End If
datePart = Left(s, spacePos - 1)
timePart = Mid(s, spacePos + 1)
' Remove milliseconds from time like 15:30:00.000 -> 15:30:00
dotPos = InStr(timePart, ".")
If dotPos > 0 Then
timePart = Left(timePart, dotPos - 1)
End If
' Parse date part dd.mm.yyyy
parts = Split(datePart, ".")
If UBound(parts) <> 2 Then GoTo fail
dayPart = CInt(parts(0))
monthPart = CInt(parts(1))
yearPart = CInt(parts(2))
dtDate = DateSerial(yearPart, monthPart, dayPart)
dtTime = TimeValue(timePart)
ParseCustomDateTime = dtDate + dtTime
Exit Function
fail:
ParseCustomDateTime = CVErr(xlErrValue)
End Function
How to use it:
Replace your previous calls to ParseSQLDateTime with ParseCustomDateTime:
vba
Dim vEnd As Variant, vStart As Variant
Dim endDate As Date, startDate As Date
vEnd = ParseCustomDateTime(selRange.Cells(i, 1).Text)
vStart = ParseCustomDateTime(selRange.Cells(i + 1, 1).Text)
If Not IsError(vEnd) And Not IsError(vStart) Then
endDate = vEnd
startDate = vStart
' Proceed with your logic...
Else
' Handle invalid dates
End If
Additional tips:
Make sure you are using .Text property to read the exact text from the cell.
This parser assumes all dates come exactly in "dd.mm.yyyy hh:mm:ss.fff" format.
If your data varies in format, you will need additional validation.
Summary
Your SQL Server datetime in dd.mm.yyyy hh:mm:ss.fff is not standard VBA format.
VBA’s DateValue does not parse this properly.
You need a custom parser like ParseCustomDateTime above.
Use it to get VBA Date values and then run your macros.
If you want, I can integrate this fully into your existing code with error handling!