Find a date in a range which has been calculated from a formula and is formatted with UK date formatting - excel

I would like to return the cell in which a date resides. There is one incidence of each date in column B, formatted dd/mm/yyyy. This is calculated from the cell two above (e.g. using =B3+7).
I have managed to retrieve the date using application.vlookup so I know it's "there". The immediate window gives the correct date using ? activecell.value
I cannot get the range.find function to return anything. If I enter a string with a USA date format such as 09/23/2014 into the column then range.find returns a value, but for UK formatted dates (=23/09/2014) it returns Nothing
Is the range.find function only capable of handling US dates?
Sub columnfind()
Dim DateRow, correctCell As Range
Set DateRow = ActiveSheet.Range("a1:B1000")
Dim strCurrentDate As String
Dim IntDate As Long
IntDate = CLng(CDbl(Now()))
strCurrentDate = Format(Now, "mm/dd/yyyy")
Set correctCell = DateRow.Find(IntDate, LookIn:=xlValues, lookat:=xlPart)
Set correctCell = DateRow.Find(strCurrentDate)
Set correctCell = DateRow.Find(Date)
cell = Application.VLookup(IntDate - 1, ActiveSheet.Range("B1:B1000"), 1, 1)'verify existence of date for my sanity
End Sub
. .

You can use something like:
Range("A1").Select
Application.FindFormat.Clear
Application.FindFormat.NumberFormat = "dd/mm/yy;#"
Set h = Range("A1:A4").Find("21/03", , , , , , , , True)
MsgBox h.Address
You define the format for the date, after use the bool SearchFormat option in the Find method.

If Find() does not work with certain formats, just don't use it:
Sub ColumnFind()
Dim bRng As Range, r As Range
Set bRng = Range("B1:B1000")
For Each r In bRng
If r.Text = "23/9/2014" Then
MsgBox r.Address(0, 0)
End If
Next r
End Sub
or
Sub ColumnFind()
Dim bRng As Range, r As Range
Dim sDate As String
sDate = Format(Date, "dd/m/yyyy")
Set bRng = Range("B1:B1000")
For Each r In bRng
If r.Text = sDate Then
MsgBox r.Address(0, 0)
End If
Next r
End Sub

This is my workaround now, if it is true that range.find doesn't work with non-US dates.
Sub columnfind()
Dim DateCol, correctCell As Range
Set DateCol = ActiveSheet.Range("B1:B1000")
Dim strCurrentDate As String
DateCol.NumberFormat = "mm/dd/yy;#"
strCurrentDate = Format(Now, "mm/dd/yy")
DateCol.Find(strCurrentDate).Select
DateCol.NumberFormat = "m/d/yyyy"
End Sub

Related

Find row where date is between start and end date

First post/question so feel free to let me know if I need to add anything.
In VBA(Excel) I'm trying to find the row where my date variable falls between the start (Column A) and end dates (Column B).
The dates are contiguous, no gaps or overlaps and are all in date format (dd/mm/yyyy) therefore, I should only get one row.
The final row has an end date of 31/12/9999
StartDate
EndDate
01/04/2022
03/04/2022
04/04/2022
02/10/2022
03/10/2022
03/10/2022
04/10/2022
21/02/2023
22/02/2023
31/12/9999
If my date variable was 03/10/2022, I would get row 3. If it was 22/09/2022 I would get row 2.
In SQL I would just do
WHERE date BETWEEN StartDate AND EndDate
How do I do this in VBA?
Sub getrow()
' fails on the if statement
Dim myrow As Integer
Dim myDate As Date
myDate = "01/05/2022"
If myDate >= Sheet9.Range("A:A").Value And myDate <= Sheet9.Range("B:B").Value Then
'i have hardcoded 99 but need it to show the row number where the date falls between column a and b
myrow = 99
Else
myrow = -1
End If
'putting it in a cell for now to see output
Sheet9.Range("c15").Value = myrow
End Sub
Something like this.
Sub BetweenDates()
Dim aCell As Range, bCell As Range
Dim Start
Dim Off
On Error GoTo ErrorHandler
Start = CDate(InputBox("Start:"))
Set aCell = Columns(1).Find(DateValue(Start), LookIn:=xlFormulas)
If aCell Is Nothing Then GoTo ErrorHandler
Off = CDate(InputBox("End:"))
Set bCell = Columns(1).Find(DateValue(Off), LookIn:=xlFormulas)
If bCell Is Nothing Then GoTo ErrorHandler
Worksheets("Sheet2").Cells.ClearContents
Rows(aCell.Row & ":" & bCell.Row).Copy Worksheets("Sheet2").Range("A1")
End
ErrorHandler:
Beep
MsgBox "Not valid Date!"
End Sub
Before:
Enter '1/1/2012' and '1/10/2012'
After:
I got it to work, there is probably a better way to do it.
Sub getrow()
Dim myrow As Integer
Dim myDate As Date
Dim rownum As Integer
myDate = #1/23/2023#
For rownum = 2 To 12
If myDate >= Cells(rownum, 1).Value And myDate <= Cells(rownum, 2).Value Then
myrow = rownum
End If
Next rownum
MsgBox myrow
End Sub
If the data is definitely as you've posted you could use Application.Match.
Sub getrow()
Dim myDate As Date
Dim myrow As Variant
myDate = #1/23/2030#
myrow = Application.Match(CDbl(myDate), Range("A2:A20"), 1)
MsgBox myrow
End Sub

Range.Find unable to find Timestamp

I think I've tried literally everything including converting the Timestamp back into date using CDate
The code is a test I'm running to get the Range.Find to work in the first place. The file in which i look up the time stamp is formatted as special dd.mm.yyyy hh:mm for example 01.01.2019 00:00 whereas in the formula bar it is 01.01.2019 00:00:00
EDIT : Removed the quotes around sDate, a copy and paste mistake
Sub trial()
Dim r As Range
Dim sDate As String
Dim find As Range
Dim col As Long
Set r = ThisWorkbook.Worksheets("INPUT_WIND").Range("d11")
col = ThisWorkbook.Worksheets("INPUT_WIND").Range("d11").Column
sDate = Format(r.Offset(, -col + 2), "dd.mm.yyyy hh:mm")
Debug.Print sDate
Set find = Workbooks("FINO raw-010119-310819").Worksheets(1).Range("A:A").find(sDate, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=True)
If Not find Is Nothing Then
Debug.Print find.Offset(, 1)
Else
MsgBox "nicht gefunden"
End If
End Sub
Try this fix
Sub trial()
Dim r As Range
Dim sDate As String
Dim find As Range
Dim col As Long
Set r = Range("d11")
col = Range("d11").Column
sDate = r.Offset(, -col + 2)
Debug.Print sDate
Set find = Worksheets(1).Range("A:A").find(CDate(sDate), LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False, SearchFormat:=True)
If Not find Is Nothing Then
Debug.Print find.Offset(, 1)
Else
MsgBox "nicht gefunden"
End If
End Sub

Change "dd.mm.yyyy" to "mm/dd/yyyy" VBA

I know "dd.mm.yyyy" is not formatted as date within Excel, and this conversion part is what is getting to me. I have "31.3.2019" within .cell("C5") and want it to convert within the same cell (replace it) with a new formatting of "3/31/2019". I keep on getting an 'out of range' error and I am not sure where my mistake is.
Below is what I have tried:
Sub DivestitureTemplate_ChangeDateFormat()
Application.ScreenUpdating = False
Dim rng As Range
Dim str() As String
Set rng = Range("C5:C3000")
With Worksheets("Divestiture Template")
For Each rng In Selection
str = Split(rng.Value, ".")
rng.Value = DateSerial(2000 + str(4), str(2), str(0))
Next rng
Selection.NumberFormat = "mm/dd/yyyy"
Application.ScreenUpdating = True
End With
End Sub
Change format of ("C5:C3000") from 31.3.2019 to 3/31/2019 -- it can be continuous, but starting at "C5" as this is an automated report and this is below a specified header. I think I have been looking at this, scripting all day and loosing my head over this for no reason.
To get real dates in the column, try:
Sub DivestitureTemplate_ChangeDateFormat()
Dim cell As Range, rng As Range, d As Date
Set rng = Worksheets("Divestiture Template").Range("C5:C3000")
For Each cell In rng
With cell
arr = Split(.Text, ".")
.Value = DateSerial(arr(2), arr(1), arr(0))
.NumberFormat = "m/dd/yyyy"
End With
Next cell
End Sub
EDIT#1:
Sub DivestitureTemplate_ChangeDateFormat()
Dim cell As Range, rng As Range, d As Date
Dim arr
Set rng = Worksheets("Divestiture Template").Range("C5:C3000")
For Each cell In rng
With cell
arr = Split(.Text, ".")
.Value = DateSerial(arr(2), arr(1), arr(0))
.NumberFormat = "m/dd/yyyy"
End With
Next cell
End Sub

Convert selection to Leading zero format

I am trying to build a simple macro that converts a selected range with numeric values to a "0000" format (e.g. 50,75,888, 1000 would be 0050,0075, 0888, 1000) i.e. it picks up each value in each cell and and returns a string value back to the sheet which can then be manipulated in Excel
Almost there (I think..) I just need help with the the $format function
Sub LeadingZero()
Dim RngSelected As Range
Dim R As String
Dim RCell As Range
Dim Rrng As Range
Dim RevNum As Long
On Error Resume Next
Set RngSelected = Application.InputBox("Please select a range of cells you want to convert to 0000 format", _
"SelectRng", Selection.Address, , , , , 8)
R = RngSelected.Address
Set Rrng = Range(R)
For Each RCell In Rrng.Cells
RCell.Value = Format$(RCell, "0000") 'this is the line I want to work!
'RCell.Value2 = Format$(RCell, "0000") doesn't seem to work either
Next RCell
End Sub
Thanks
Did you specifically want to do it with formatting? If you actually want to convert the value (useful for lookup and the like) then this function will do what you want.
Function FourDigitValues(InputString As String)
Dim X As Long, MyArr As Variant
MyArr = Split(InputString, ",")
For X = LBound(MyArr) To UBound(MyArr)
MyArr(X) = Right("0000" & MyArr(X), 4)
Next
FourDigitValues = Join(MyArr, ",")
End Function
Sub LeadingZero()
Dim RngSelected As Range
Dim R As String
Dim RCell As Range
Dim Rrng As Range
Dim RevNum As Long
On Error Resume Next
Set RngSelected = Application.InputBox("Please select a range of cells you want to convert to 0000 format", _
"SelectRng", Selection.Address, , , , , 8)
R = RngSelected.Address
Set Rrng = Range(R)
For Each RCell In Rrng.Cells
RCell.NumberFormat = "000#"
Next RCell
End Sub
Thanks to Assaf and Dan Donoghue:
Sub LeadingZero2()
'Takes a range with numbers between 1 and 9999 and changes them to text string with "0000" format
Dim RngSelected As Range
Dim RCell As Range
Dim Rrng As Range
On Error Resume Next
Set RngSelected = Application.InputBox("Please select a range of cells you want to convert to 0000 format", _
"SelectRng", Selection.Address, , , , , 8)
Set Rrng = Range(RngSelected.Address)
For Each RCell In Rrng.Cells
RCell.NumberFormat = "#"
RCell = CStr(Array("000", "00", "0")(Len(RCell) - 1) & RCell)
Next RCell
End Sub

Range.Find on Dates with custom number format

Here's the relevant parts of my code I'm having trouble with.
Sub Find_Target()
Dim DayNum As Long
Dim TargetName As String
Dim TargetDay As Range
Dim found As Variant
DayNum = Cells(1, 9)
Set TargetDay = ActiveWorkbook.Sheets("3-2015").Range("A1:B440")
TargetDay.Activate
Set found = TargetDay.Find(DayNum, LookIn:=xlValues)
If found Is Nothing Then
MsgBox "Nothing found!"
Else
TargetDay.Select
End If
End Sub
Column A contains a mix of merged and unmerged cells. Cells(1, 9) contains a date in general format. Periodically in column A/B will be a merged cell containing that same number, but in custom number format "dddd". The find command works if I change the number format to general, but otherwise found is Nothing.
I've tried playing with the FindFormat option, but didn't have any luck there.
A bit unclear from the question, so I'm assuming that you have a number in cell I1 and you want to find the first cell with on the same day of the month. Assuming that's the case, you can just loop through the range and compare against the day directly:
Sub Find_Target()
Dim DayNum As Long
Dim TargetDay As Range
Dim found As Range
DayNum = Cells(1, 9)
Set TargetDay = ActiveWorkbook.Sheets("3-2015").Range("A1:B440")
Dim row As Long, col As Long
For row = 1 To TargetDay.Rows.Count
For col = 1 To TargetDay.Columns.Count
If IsDate(TargetDay.Cells(row, col).Value) Then
If Day(CDate(TargetDay.Cells(row, col).Value)) = DayNum Then
Set found = TargetDay.Cells(row, col)
Exit For
End If
End If
Next col
If Not found Is Nothing Then Exit For
Next row
If found Is Nothing Then
MsgBox "Nothing found!"
Else
found.Select
End If
End Sub
If I1 is something else, it should be trivial to modify - the key is explicitly treating the cell values as dates in VBA.
You need to .Find for LookAt:=xlFormulas and look for a Date type var, not a Long. Throw the following at your data.
Sub Find_Target()
Dim iDayNum As Long, sDayNum As String, dDayNum As Date
Dim foundI As Variant, foundS As Variant, foundD As Variant
Dim TargetDay As Range
iDayNum = Cells(1, 9)
sDayNum = Format(Cells(1, 9), "mm/dd/yyyy")
dDayNum = Cells(1, 9) 'I might even use CDate(Cells(1, 9).Value) as a reminder
Set TargetDay = ActiveWorkbook.Sheets("3-2015").Range("A1:B440")
Set foundI = TargetDay.Find(iDayNum, LookIn:=xlFormulas, LookAt:=xlWhole)
Set foundS = TargetDay.Find(sDayNum, LookIn:=xlFormulas, LookAt:=xlWhole)
Set foundD = TargetDay.Find(dDayNum, LookIn:=xlFormulas, LookAt:=xlWhole)
If foundI Is Nothing Then
MsgBox "As a Long - Nothing found!"
Else
MsgBox "As a Long - Found!"
End If
If foundS Is Nothing Then
MsgBox "As a String - Nothing found!"
Else
MsgBox "As a String - Found!"
End If
If foundD Is Nothing Then
MsgBox "As a Date - Nothing found!"
Else
MsgBox "As a Date - Found!"
End If
End Sub
You should have no problem finding the matching date var no matter whether it is formatted as dddd or anything else.

Resources