Help with VBA in Excel 2007

H

harwookf

I have the following VBA code which somebody helped me with earlier and I can
get it to work. However, when I save the spreadsheet and then go back into
it, it doesn't work again.
The VBA code is so that I can enter 1423 and it will change to 14:23 when
working, if it isn't it goes to 34152:00.
Any ideas where I have gone wrong? Ideally I would like the VBA code over
the workbook and not just the worksheet, but I don't know how to do this.

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
Dim TimeStr As String

On Error GoTo EndMacro
If Application.Intersect(Target, Range("C:D,F:G,J:J")) 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 1 ' e.g., 1 = 00:01 AM
TimeStr = "00:0" & .Value
Case 2 ' e.g., 12 = 00:12 AM
TimeStr = "00:" & .Value
Case 3 ' e.g., 735 = 7:35 AM
TimeStr = Left(.Value, 1) & ":" & _
Right(.Value, 2)
Case 4 ' e.g., 1234 = 12:34
TimeStr = Left(.Value, 2) & ":" & _
Right(.Value, 2)
Case 5 ' e.g., 12345 = 1:23:45 NOT 12:03:45
TimeStr = Left(.Value, 1) & ":" & _
Mid(.Value, 2, 2) & ":" & Right(.Value, 2)
Case 6 ' e.g., 123456 = 12:34:56
TimeStr = Left(.Value, 2) & ":" & _
Mid(.Value, 3, 2) & ":" & Right(.Value, 2)
Case Else
Err.Raise 0
End Select
.Value = TimeValue(TimeStr)
End If
End With
Application.EnableEvents = True
Exit Sub
EndMacro:
MsgBox "You did not enter a valid time"
Application.EnableEvents = True
End Sub



Thanks in advance.
 
S

Sheeloo

I tested out the code and it is working fine in Excel 2003... I will test in
2007 later and get back to you.

Are you sure macros are enabled when it does not seem to work?

I don't see any reason for it not to work...
 
H

harwookf

Yes my macros are enabled. In Excel 2007, you have to save spreadsheets as
macro enabled workbooks for them to work.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top