PDA

View Full Version : Solved: Why does my date change ?



PerS
09-02-2008, 02:59 AM
I have a spreadsheet that calculates a duration eg.

Start End Duration
12-05-2008 09:00 23-05-2008 17:00 11,33

The 2 first columns are custom-formatet to "dd-mm-yyyy hh:mm"
Today I have to type the date/time exactly with "-" and ":" but I only want to type "1205080900" for the first date.
Therefore I have made the VBA code below. My problem is that the first date is being changed to "05-12-2008" (US format) in the statement " .Value = TimeStr". The second date is not changed properly because month no. 23 does not exist.
How do I solve this problem ?


Private Sub Worksheet_Change(ByVal Target As Excel.Range)
Dim TimeStr As String
On Error GoTo EndMacro
If Application.Intersect(Target, Range("A2:B999")) Is Nothing Then
Exit Sub
End If
If Target.Cells.Count > 1 Then
Exit Sub
End If
If Target.Value = "" Then
Exit Sub
End If

Application.EnableEvents = False
With Target
If .HasFormula = False Then
Select Case Len(.Value)
Case 10 ' e.g., 0204081200 = 02-04-2008 12:00:00
TimeStr = Left(.Value, 2) & "/" & _
Mid(.Value, 3, 2) & "/" & Mid(.Value, 5, 2) _
& " " & Mid(.Value, 7, 2) & ":" & _
Right(.Value, 2)
MsgBox "Timestr = " & TimeStr
Case Else
Err.Raise 0
End Select
.Value = TimeStr
MsgBox ".Value = " & .Value
End If
End With
Application.EnableEvents = True
Exit Sub
EndMacro:
MsgBox "Not a valid date/time."
Application.EnableEvents = True
End Sub

Bob Phillips
09-02-2008, 03:20 AM
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
Dim TimeStr As Date
On Error GoTo EndMacro
If Application.Intersect(Target, Range("A2:B999")) Is Nothing Then
Exit Sub
End If
If Target.Cells.Count > 1 Then Exit Sub
If Target.Value = 0 Then Exit Sub

Application.EnableEvents = False
With Target
If .HasFormula = False Then
Select Case Len(.Value)
Case 10 ' e.g., 0204081200 = 02-04-2008 12:00:00
TimeStr = DateSerial(Mid(.Value, 5, 2), _
Mid(.Value, 3, 2), Left(.Value, 2)) _
& " " & Mid(.Value, 7, 2) & ":" & _
Right(.Value, 2)
Case Else
Err.Raise 0
End Select
.Value = TimeStr
End If
End With
Application.EnableEvents = True
Exit Sub
EndMacro:
MsgBox "Not a valid date/time."
Application.EnableEvents = True
End Sub

PerS
09-02-2008, 04:27 AM
Thanks, small change great effect