This code works, but I was wondering if there's a way to get excel to identify the date data more easily. This comes from an imported file where the date field(s) come in as text and in a European format.
Company specific information has been changed. the function FndLast
gets the last row of the data.
Sub FormatTheDates()
Dim rng As Range
Dim lstRow As Long
Dim StartRow As Long
Set rng = sheets("MySheet").Cells.Find("Keyfield")
If Not rng Is Nothing Then
With sheets("MySheet")
****Data starts one row below key field***
StartRow = rng.Row + 1
lstRow = FndLast(1, .Cells)
Set rng = .Range(.Cells(StartRow, 5).Address, .Cells(lstRow, 5).Address)
rng.NumberFormat = "m/d/yyyy"
rng.value = rng.value
End With
End If
Set rng = sheets("MySheet2").Cells.Find("Keyfield")
If Not rng Is Nothing Then
With sheets("MySheet2")
StartRow = rng.Row + 1
lstRow = FndLast(1, .Cells)
Set rng = .Range(.Cells(StartRow, 7).Address, .Cells(lstRow, 7).Address)
rng.NumberFormat = "m/d/yyyy"
rng.value = rng.value
End With
End If
End Sub
The fndlast
function takes a 1,2, or 3 as a parameter and finds the last row, column or cell on a sheet. I use this as opposed to usedrange as it returns the last one with data.
Function FndLast(choice As Long, rng As Range)
' 1 = last row
' 2 = last column
' 3 = last cell
Dim lrw As Long
Dim lCol As Long
Select Case choice
Case 1:
On Error Resume Next
FndLast = rng.Find(What:="*", _
After:=rng.Cells(1), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
Case 2:
On Error Resume Next
FndLast = rng.Find(What:="*", _
After:=rng.Cells(1), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
Case 3:
On Error Resume Next
lrw = rng.Find(What:="*", _
After:=rng.Cells(1), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
On Error Resume Next
lCol = rng.Find(What:="*", _
After:=rng.Cells(1), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
On Error Resume Next
FndLast = rng.Parent.Cells(lrw, lCol).Address(False, False)
If Err.Number > 0 Then
Last = rng.Cells(1).Address(False, False)
Err.Clear
End If
On Error GoTo 0
End Select
End Function
As I said, all of this works, and fairly quickly, but it feels like the Range.value = range.value
seems unnecessary. Is it, or is this just an Excel quirk that I need to work around in order for my code to work?