Denin Srmic
New Member
- Joined
- Apr 28, 2020
- Messages
- 19
- Office Version
- 365
- Platform
- Windows
Hello,
I have tried using few examples I found on web (please see bellow) reversing dates stored as string "20231201" into "01122023", but had no luck in contriving in getting the desired date string. They all render wrong results.
Can you please show me the way how to do this using loops only in VBA.
Many thanks in advance.
I have tried using few examples I found on web (please see bellow) reversing dates stored as string "20231201" into "01122023", but had no luck in contriving in getting the desired date string. They all render wrong results.
Can you please show me the way how to do this using loops only in VBA.
Many thanks in advance.
VBA Code:
Sub pasStringToF()
'Not working, result inaccurate in both functions!!!
Dim sDat As String
Dim vRslt As Variant
sDat = 19780623
'vRslt = ReverseDateExmpl1(sDat)
vRslt = ReverseDateExmple2(sDat)
Debug.Print vRslt
End Sub
Public Function ReverseDateExmpl1(ByVal dateStr As String) As String
Dim i As Integer
Dim reversedDate As String
For i = 1 To 8 Step 2
reversedDate = reversedDate & Mid(dateStr, i + 1, 1) & Mid(dateStr, i, 1)
Next i
ReverseDateExmpl1 = reversedDate
End Function
Function ReverseDateExmple2(dateString As String) As String
Dim reversedDate As String, i As Integer
ReverseDateExmple2 = ""
For i = 1 To Len(dateString)
ReverseDateExmple2 = Mid(dateString, i, 1) & ReverseDateExmple2
Next i
ReverseDateExmple2 = Mid(ReverseDateExmple2, 5, 4) & Mid(ReverseDateExmple2, 3, 2) & Mid(ReverseDateExmple2, 1, 2)
End Function
Sub ReverseDate1()
'NOT working
Dim strDate As String
Dim strNewDate As String
Dim i As Integer
strDate = "20231201"
strNewDate = ""
For i = 1 To Len(strDate) Step 2
strNewDate = Right(strDate, i Mod 2 + 1) & strNewDate
Next i
Debug.Print strNewDate
End Sub
Sub ReverseDate2()
'Not Working
Dim strDate As String
Dim strNewDate As String
Dim i As Integer
strDate = "20231201"
strNewDate = ""
For i = 1 To Len(strDate)
If i Mod 2 = 0 Then
strNewDate = strNewDate & Mid(strDate, i - 1, 2)
If i < Len(strDate) Then
strNewDate = strNewDate & "/"
End If
End If
Next i
Debug.Print strNewDate
End Sub
Sub ReverseDate3()
'NOT working
Dim strDate As String
Dim strNewDate As String
Dim i As Integer
strDate = "20231201"
strNewDate = ""
For i = 1 To Len(strDate)
If i = 5 Or i = 7 Then
strNewDate = strNewDate & "/"
End If
strNewDate = strNewDate & Mid(strDate, Len(strDate) - i + 1, 1)
Next i
Debug.Print strNewDate
End Sub