VBA: On worksheet change, convert number into time

FryGirl

Well-known Member
Joined
Nov 11, 2008
Messages
1,364
Office Version
  1. 365
  2. 2016
Platform
  1. Windows
Hello all,

I have this working on column F to convert the value entered into time. So, for example, if the user enters 210, it's converting it to 3:30.

This is working good, but two questions if I could.

1) Is this the most efficient way to do this?
2) What can I do to validate that a number was entered?

VBA Code:
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range: Set rng = Target.Parent.Range("F:F")
    If Target.CountLarge > 1 Then Exit Sub
    If Target.Row < 2 Then Exit Sub
    If Intersect(Target, rng) Is Nothing Then Exit Sub
    Dim x As Variant: x = Target.Value
    
    With Application
        .EnableEvents = False
        .ScreenUpdating = False
        .Undo
    End With
    
    Target.Value = x / 1440
    Target.NumberFormat = "[h]:mm"
    
    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With
    
End Sub
 

Excel Facts

What is =ROMAN(40) in Excel?
The Roman numeral for 40 is XL. Bill "MrExcel" Jelen's 40th book was called MrExcel XL.
I'm not 100% sure. I was crafting this off of another thread, so may have not realized I didn't need it.

I thought I needed it to capture the user's input so I could then do the conversion afterwards.
 
Upvote 0
I can't advise on whether it is the most efficient way but in terms of whether it is a number the following will give you a true if it is a number.
VBA Code:
IsNumeric(Target)
 
Upvote 0
Solution

Forum statistics

Threads
1,215,045
Messages
6,122,830
Members
449,096
Latest member
Erald

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top