Range.Find on a Date That is a Formula
I receive a workbook that contains information about the processing volumes of a call center team. I have no way of modifying the format or layout of the workbook upstream.
One sheet contains information about processing errors.
(team members' user IDs redacted)
Each date is represented by a merged 1x3 range with the date in question formatted as "dd-mmm" e.g. "01-Jun"
That date is pulled via formula from another sheet with the same layout. The formula for one such range reads: ='QA Scores'!K2:M2
I attempted to use Range.Find
to locate the first day of a given month and an end date in that same month (based on user input) - e.g. June 1 through June 15.
Set rngMin = .Find(What:=DateValue(minDate), _
LookIn:=xlFormulas, _
LookAt:=xlWhole)
In other uses, I located a date in this manner, but the added complexity of the value coming from a formula seems to be the issue here.
UPDATE:
I have written the following based on Ron Rosenfeld's answer:
Dim UsedArr As Variant: UsedArr = SrcWS.UsedRange
blFound = False
For i = LBound(UsedArr, 1) To UBound(UsedArr, 1)
For j = LBound(UsedArr, 2) To UBound(UsedArr, 2)
If UsedArr(i, j) = MinDate Then
blFound = True
Exit For
End If
Next
If blFound = True Then Exit For
Next
Dates are tricky to find with the Range.Find
method. One of the issues is that in VBA, dates are of the Date
data type, but the worksheet does not have that data type. Rather the data type is a number that is formatted to look like a date.
One solution, if you can be certain of the format of the date on the worksheet, is to search for the string equivalent. Given your example, something like this will work:
Option Explicit
Sub GetDates()
Const findDate As Date = #5/11/2017#
Dim findStr As String
Dim R As Range, WS As Worksheet
Set WS = Worksheets("Sheet1")
findStr = Format(findDate, "dd-mmm")
With WS
Set R = .Cells.Find(what:=findStr, LookIn:=xlValues, lookat:=xlWhole)
If Not R Is Nothing Then MsgBox findDate & " found in " & R.Address
End With
End Sub
but it is not very robust since, in many cases, the user can change the format.
Another method that is more robust, would be to loop through the existing cells, looking for the numeric representation of the date (using the Value2
property):
Sub GetDates2()
Const findDate As Date = #5/11/2017#
Dim R As Range, C As Range, WS As Worksheet
Set WS = Worksheets("sheet1")
Set R = WS.UsedRange
For Each C In R
If C.Value2 = CDbl(findDate) Then MsgBox findDate & " found in " & C.Address
Next C
End Sub
If you have a large range to search, this can be sped up by a factor of ten by reading the range into a VBA array and looping through the array.
@KOstvall,, I would like to suggest this simple find method, since you are trying to get the Date.
Set rng = Sheet1.Range("A:A").Find("1/1/2017", LookIn:=xlValue, LookAt:=xlWhole)