I have an excel spreadsheet with 50000 rows of business hours data (in every conceivable format):
THU 4P-9P F 9A-9P SAT,SUN 9A-6P
WED & THU 10A - 3P FRI 10A - 1P
MON - FRI 6P - 10P
M - SA 9A - 9P
SUN-SAT 9-5
SU - SA 8A- 10P
TUE - FRI 10A - 6P SAT 12P - 4P
MON - FRI 730A-4P / SAT 9A-12P
SUN 6A-5P / M-F 6A-9P / SAT 5A-9P
I need to convert it to something like:
Days Open A Week: 2
Hours Open a Week: 15
I thought of doing:
Business Hours Sunday
WED 1P - 5P THU - SA BY APPT =ISNUMBER(SEARCH("Sun",A1)) # returns True.
for each day, but I'm wondering if there is an easier way to clean this data other than hard coding every possibility.
Thank you!
Here's some VBA that worked on the sample data provided. It almost certainly won't work on a larger sample, but it's a start.
Public Function DaysAndHours(ByVal sInput As String)
Dim vaTokens As Variant
Dim i As Long, j As Long
Dim vaSeps As Variant
Dim dtTime As Date, dtStart As Date, dtEnd As Date
Dim dHours As Double, dTodayHours As Double
Dim lStartDay As Long, lEndDay As Long
Dim bThrough As Boolean
Dim dcDay As Scripting.Dictionary
Dim vItem As Variant
Set dcDay = New Scripting.Dictionary
'These are all the characters that split the data
'as you discover more characters, add them here
vaSeps = Split("- , / &")
'If the data has times like 730, Excel can't tell it's a time
'so this adds a colon before 30 and 15 assuming it's unlikely
'anyone would open or close on other than a quarter hour
'then if there was already a colon there, it would be doubled
'so remove double colons
sInput = Replace(sInput, "30", ":30")
sInput = Replace(sInput, "15", ":15")
sInput = Replace(sInput, "::", ":")
'Some separators have spaces around them and some don't. This changes
'all separators so they have spaces. This is so our split creates
'proper tokens
For j = LBound(vaSeps) To UBound(vaSeps)
sInput = Replace(sInput, vaSeps(j), Space(1) & vaSeps(j) & Space(1))
Next j
'If the separators already had spaces around them, they would be
'doubled. Trim removes double spaces
sInput = Application.Trim(sInput)
vaTokens = Split(sInput, Space(1))
'Assume the first token is a day, and put it in the
'dictionary at zero hours
lStartDay = GetDayFromInit(vaTokens(LBound(vaTokens)))
dcDay.Add lStartDay, 0
For i = LBound(vaTokens) + 1 To UBound(vaTokens)
'Some separators are "through" meaning that all the days in between
'the two days are included. Other separators just list discrete days
If IsSep(vaTokens(i), vaSeps) Then
Select Case vaTokens(i)
Case "-"
bThrough = True
Case Else
bThrough = False
End Select
Else
'Excel won't convert a straight number to a time, so this
'adds :00 to make it look like a time
If IsNumeric(vaTokens(i)) Then
vaTokens(i) = vaTokens(i) & ":00"
End If
'Try to change the token into a time. If it
'works, we're dealing with times, otherwise days
On Error Resume Next
dtTime = TimeValue(vaTokens(i))
On Error GoTo 0
If dtTime > 0 Then 'the current token is a time
If dtStart > 0 Then 'we've already converted a time, so this must be the end time
dtEnd = dtTime
If dtEnd < dtStart Then dtEnd = dtEnd + TimeSerial(12, 0, 0) 'make sure the end time is after the start time
dTodayHours = dtEnd - dtStart 'compute the hours open
'For every day that we haven't filled a time, put this time
For j = 0 To dcDay.Count - 1
If dcDay.Items(j) = 0 Then
dcDay.Item(dcDay.Keys(j)) = dTodayHours
End If
Next j
dtStart = 0: dtEnd = 0: dtTime = 0 'reset
bThrough = False 'reset
Else 'We haven't already filled a time, so this must be the start time
dtStart = dtTime
End If
Else 'the current token isn't a time, it must be day
'we've encountered a through separator, so we've alreay got a start day
'and this token is the end day
If bThrough Then
lEndDay = GetDayFromInit(vaTokens(i))
'If the days are in the right order, just add them
'in order to the dictionary
If lStartDay < lEndDay Then
For j = lStartDay To lEndDay
If Not dcDay.Exists(j) Then
dcDay.Add j, 0
End If
Next j
Else 'Days are in the wrong order (where Sunday = 1)
For j = 1 To lEndDay
If Not dcDay.Exists(j) Then
dcDay.Add j, 0
End If
Next j
For j = lStartDay To 7
If Not dcDay.Exists(j) Then
dcDay.Add j, 0
End If
Next j
End If
Else 'We haven't encountered a through operator, so this is a lone day or the first of a range
lStartDay = GetDayFromInit(vaTokens(i))
If Not dcDay.Exists(lStartDay) Then
dcDay.Add lStartDay, 0
End If
End If
End If
End If
Next i
DaysAndHours = dcDay.Count & " days, " & Application.Sum(dcDay.Items) * 24 & " hours"
End Function
Public Function GetDayFromInit(ByVal sInit As String) As Long
Dim vaDays As Variant
Dim i As Long
vaDays = Split("SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY")
For i = 0 To 6
If UCase(sInit) = Left$(vaDays(i), Len(sInit)) Then
GetDayFromInit = i + 1
Exit For
End If
Next i
End Function
Public Function IsSep(ByVal sChar As String, ByRef vSeps As Variant) As Boolean
IsSep = InStr(1, Join(vSeps), sChar)
End Function
Related
I need to automatically calculate a Start Date (aka QRT_START) which is 5 years of Quarters back. A Quarter is 3 months. For example, there are 4 Quarters in a Year: March 31st, June 30th, September 30th and December 31st.
Since we are currently in November 16th 2022, the Start Date would be December 31st 2017. So depending on whatever the current date is, the Start Date needs to go back 5 years worth of Quarters.
I also need to automatically calculate the most recent End Date (aka QRT_END). So since, we are in November 16th 2022, the End Date would be the previous quarter end before today which is September 30th 2022. I have the VBA code written below, please help me fix.
Private Function getQRT_END() As String
Dim endmonth As Variant
Dim endyear As Variant
Dim Day As Variant
endmonth = Month(Date) - 1
If endmonth = 0 Then
endyear = Year(Date) - 1
endmonth = 12
day = 31
Else
endyear = Year(Date)
If endmonth = 3 Then
day = 31
Else
day = 30
End if
endmonth = “0” & endmonth
End If
getQRT_END = endyear & endmonth & day
End Function
Private Function getQRT_START() As String
Dim startmonth As Variant
Dim startyear As Variant
Dim Day As Variant
startyear = Year(Date) - 5
startmonth = Month(Date) + 2
If startmonth <10 Then
If startmonth = 3 Then
day = 31
Else
day = 30
End if
startmonth = “0” & startmonth
Else
day = 30
End If
getQRT_START = startyear & startmonth & day
End Function
Function GetQuartal(years, data)
d = DateAdd("yyyy", years, data)
q = (Month(d) + 2) \ 3
qstart = DateSerial(Year(d), (q - 1) * 3 + 1, 1)
qend = DateSerial(Year(d), q * 3 + 1, 1) - 1
GetQuartal = Array(data, d, qstart, qend)
End Function
Sub test()
Debug.Print "Date", "Date-5Y", "QY-5 Start", "QY-5 End"
For Each d In Array(Date, #2/29/2000#, #12/1/2021#, #5/5/1992#)
q = GetQuartal(-5, d)
Debug.Print q(0), q(1), q(2), q(3)
Next
End Sub
Date Date-5Y QY-5 Start QY-5 End
17.11.2022 17.11.2017 01.10.2017 31.12.2017
29.02.2000 28.02.1995 01.01.1995 31.03.1995
01.12.2021 01.12.2016 01.10.2016 31.12.2016
05.05.1992 05.05.1987 01.04.1987 30.06.1987
You can use two functions found in my library at GitHub: VBA.Date.
? DateThisQuarterUltimo(DateAdd("yyyy", -5, Date))
2017-12-31
? DatePreviousQuarterUltimo(DateAdd("yyyy", -5, Date))
2017-09-30
They are simple high-level functions:
' Returns the ultimo date of the quarter of the date passed.
'
' 2016-01-13. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function DateThisQuarterUltimo( _
ByVal DateThisQuarter As Date) _
As Date
Dim Interval As String
Dim Number As Double
Dim ResultDate As Date
Number = 0
Interval = IntervalSetting(DtInterval.dtQuarter)
ResultDate = DateIntervalUltimo(Interval, Number, DateThisQuarter)
DateThisQuarterUltimo = ResultDate
End Function
' Returns the ultimo date of the quarter preceding the quarter of the date passed.
'
' 2016-01-13. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function DatePreviousQuarterUltimo( _
ByVal DateThisQuarter As Date) _
As Date
Dim Interval As String
Dim Number As Double
Dim ResultDate As Date
Number = -1
Interval = IntervalSetting(DtInterval.dtQuarter)
ResultDate = DateIntervalUltimo(Interval, Number, DateThisQuarter)
DatePreviousQuarterUltimo = ResultDate
End Function
Haven't tested it completely
You can use DateSerial, DateAdd and DatePart to achieve what you want...
Option Explicit
Sub Sample()
Dim D As Date
Dim prevD As Date
D = DateSerial(2022, 11, 16)
'~~> Date 5 years years ago
prevD = DateAdd("q", -(4 * 5), D)
'~~> Last date of the quarter for a specific date
Debug.Print DateAdd("q", DatePart("q", prevD), DateSerial(Year(prevD), 1, 1)) - 1
'OUTPUT : 31-12-2017
'~~> Last date of previous quarter for a specific date
Debug.Print DateAdd("q", DatePart("q", D) - 1, DateSerial(Year(D), 1, 1)) - 1
'OUTPUT : 30-09-2022
End Sub
Changed string part to a proper date.
I am aware that this question has been asked in many different forms, but I would like to show my case as I have not found the perfect solution for it.
So, what I need to do is divide every month in 4 or 5 weeks, and type it into the corresponding cells.
Example :
I have tried this sample code written by User : danieltakeshi in this thread :
https://stackoverflow.com/a/47393516/11969596
But it has a flaw in it, for example if you type a date from October 2021 the result outputs 6 weeks which is impossible :
Sub WeeksInMonth()
Dim MonthYear As String, txt As String
Dim InputDate As Date, MonthYearDay As Date
Dim i As Long, intDaysInMonth As Long, j As Long
Dim MyArray As Variant
Dim arr As New Collection, a
ReDim MyArray(0 To 31)
j = 0
InputDate = ("1 / 10 / 2021") ' Date from October
MonthYear = Month(InputDate) & "/" & Year(InputDate)
intDaysInMonth = Day(DateSerial(Year(MonthYear), Month(MonthYear) + 1, 0))
For i = 1 To intDaysInMonth
MonthYearDay = DateSerial(Year(InputDate), Month(InputDate), i)
MyArray(j) = Application.WorksheetFunction.WeekNum(MonthYearDay)
j = j + 1
Next i
ReDim Preserve MyArray(0 To j - 1)
On Error Resume Next
For Each a In MyArray
arr.Add a, CStr(a)
Next
For i = 1 To arr.Count
Debug.Print arr(i)
Next
End Sub
Please help me find a solution, or tell me how I can adapt it to my current situation.
Cordially,
This routine checks for the first and last workingday (monday to friday) and then gives the calendar weeks for that date range
Option Explicit
Public Sub test_getWeeknumbersForMonth()
Dim arr As Variant
arr = getWeekNumbersForMonth("1.10.2021")
Debug.Print "1.10.2021: ", Join(arr, " - ")
arr = getWeekNumbersForMonth("1.1.2022")
Debug.Print "1.1.2022: ", Join(arr, " - ")
End Sub
Public Function getWeekNumbersForMonth(inputDate As Date) As Variant
Dim datStart As Date
datStart = getFirstWorkingDayOfMonth(inputDate)
Dim datEnd As Date
datEnd = getLastWorkingDayOfMonth(inputDate)
Dim arrWeekNumbers As Variant
ReDim arrWeekNumbers(1 To 6) 'max 6 weeks can be returned
Dim i As Long: i = 1
Dim dat As Date
dat = datStart
While dat <= datEnd
arrWeekNumbers(i) = getCalendarWeek(dat)
i = i + 1
dat = DateAdd("ww", 1, dat)
Wend
ReDim Preserve arrWeekNumbers(i - 1)
getWeekNumbersForMonth = arrWeekNumbers
End Function
Private Function getFirstWorkingDayOfMonth(inputDate As Date) As Date
Dim datToCheck As Date: datToCheck = DateSerial(Year(inputDate), Month(inputDate), 1) - 1
Dim isWorkingday As Boolean
Do
datToCheck = datToCheck + 1
isWorkingday = Weekday(datToCheck, vbMonday) <= 5
Loop Until isWorkingday = True
getFirstWorkingDayOfMonth = datToCheck
End Function
Private Function getLastWorkingDayOfMonth(inputDate As Date) As Date
Dim datToCheck As Date: datToCheck = DateSerial(Year(inputDate), Month(inputDate) + 1, 1)
Dim isWorkingday As Boolean
Do
datToCheck = datToCheck - 1
isWorkingday = Weekday(datToCheck, vbMonday) <= 5
Loop Until isWorkingday = True
getLastWorkingDayOfMonth = datToCheck
End Function
Private Function getCalendarWeek(inputDate As Date) As Long
'european iso week - CW 1 = week with first thursday
getCalendarWeek = Application.WorksheetFunction.IsoWeekNum(inputDate)
'use weeknum-function -adjust second parameter to your needs
'https://support.microsoft.com/en-us/office/weeknum-function-e5c43a03-b4ab-426c-b411-b18c13c75340
'getCalendarWeek = Application.WorksheetFunction.WeekNum(inputDate, 2)
End Function
First, some months have dates in six weeks.
Next, VBA natively can't return the correct ISO 8601 weeknumbers:
How to get correct week number in Access
Finally, week numbers don't care about workdays or weekends. If you wish to exclude weeks that don't include specific weekdays, filter on the dates of these.
I'm still getting the hang of more complex formulas in VBA.
I'm wanting to create a system that can calculate the worked hours for a certain projects. For example, say my shift hours are 6AM-330PM. I start a project at 7AM on 11/14 and end it at 9AM on 11/16.
How would I go about making calculations so that the returned value will be the hours I worked while on the clock, and not a rolling 24-hour calculation? (While also skipping weekends if possible?)
Thanks!! Heres the code that Im trying to use....
Public Function NetWorkHours(dteStart As Date, dteEnd As Date) As Integer
Dim StDate As Date
Dim StDateD As Date
Dim StDateT As Date
Dim EnDate As Date
Dim EnDateD As Date
Dim EnDateT As Date
Dim WorkDay1Start As Date
Dim WorkDay1end As Date
Dim WorkDay2Start As Date
Dim WorkDay2end As Date
Dim Result As Integer
Dim MinDay As Integer
StDate = CDate(dteStart)
EnDate = CDate(dteEnd)
WorkDay1Start = DateValue(StDate) + TimeValue("08:00:00")
WorkDay1end = DateValue(StDate) + TimeValue("17:00:00")
WorkDay2Start = DateValue(EnDate) + TimeValue("08:00:00")
WorkDay2end = DateValue(EnDate) + TimeValue("17:00:00")
If (StDate > WorkDay1end) Then
StDate = DateAdd("d", 1, WorkDay1Start)
End If
If (StDate < WorkDay1Start) Then
StDate = WorkDay1Start
End If
If (EnDate > WorkDay2end) Then
EnDate = DateAdd("d", 1, WorkDay2Start)
End If
If (EnDate < WorkDay2Start) Then
EnDate = WorkDay2Start
End If
StDateD = CDate(Format(StDate, "Short Date"))
EnDateD = CDate(Format(EnDate, "Short Date"))
If StDateD = EnDateD Then
Result = DateDiff("n", StDate, EnDate, vbUseSystemDayOfWeek)
Else
MinDay = (8 * 60) 'Number of minutes of a working day. Change this if you change the start and end times.
'Extract the time from the two timestamps
StDateT = Format(StDate, "Short Time")
EnDateT = Format(EnDate, "Short Time")
'
'Calculate the minutes of the first day and the second one. Don't know what to do yet if the start is after 5pm or the end is before 8am
Result = DateDiff("n", StDateT, TimeValue("17:00:00"), vbUseSystemDayOfWeek)
Result = Result + DateDiff("n", TimeValue("08:00:00"), EnDateT, vbUseSystemDayOfWeek)
'Check if there was a break on both days or not.
If DateDiff("n", StDateT, TimeValue("17:00:00"), vbUseSystemDayOfWeek) > (5 * 60) Then
Result = Result - 60
End If
If DateDiff("n", TimeValue("08:00:00"), EnDateT, vbUseSystemDayOfWeek) > (5 * 60) Then
Result = Result - 60
End If
'Add 1 day to start date. This is to start the loop to get all the days between both dates.
StDateD = DateAdd("d", 1, StDateD)
Do Until StDateD = EnDateD
'If the date is not a saterday or a sunday we add one day.
If (Weekday(StDateD) > 1) And (Weekday(StDateD) < 7) Then
Result = Result + MinDay
'Check for the holiday. If the date is a holiday, then we remove one day
If Not IsNull(DLookup("[HolDate]", "Holidays", "[HolDate] = #" & Int(StDateD) & "#")) Then
Result = Result - MinDay
End If
End If
StDateD = DateAdd("d", 1, StDateD)
Loop
End If
NetWorkHours = Result
End Function
You can use DateDiff to calculate the difference between dates (and times). The following should get you pretty close to what you want to do:
Dim datStart As Date
Dim datEnd As Date
Dim sngShiftStart As Single
Dim sngShiftEnd As Single
Dim sngShiftDuration As Single
Dim lngMinutesWorked As Long
Dim lngOfftime As Long
Dim sngHoursWorked As Single
' Calculate shift length
sngShiftStart = 6
sngShiftEnd = 15.5
sngShiftDuration = sngShiftEnd - sngShiftStart
' Set start and end times
datStart = CDate("11/07/19 7:00")
datEnd = CDate("11/09/19 8:30")
lngMinutesWorked = DateDiff("n", datStart, datEnd)
lngOfftime = ((24 - sngShiftDuration) * 60) * (DateDiff("d", datStart, datEnd))
sngHoursWorked = (lngMinutesWorked - lngOfftime) / 60
MsgBox sngHoursWorked
This does not take into account weekends but you should be able to easily add that. You can check, using the Weekday function, if the Weekday of the Start date is smaller than the End date. In that case, subtract 2 * sngShiftDuration from sngHoursWorked. If your project lasts more than a week, you can look for that and subtract more weekends:
' Remove weekends
Dim sngWeekendHours As Single
If Weekday(datStart) > Weekday(datEnd) Then
' Weekend included
sngWeekendHours = (2 * sngShiftDuration) * (DateDiff("w", datStart, datEnd) + 1)
End If
sngHoursWorked = ((lngMinutesWorked - lngOfftime) / 60) - sngWeekendHours
Problem
The following [mcve] will output an array of arrays of week numbers between two dates. It works when both dates are on the same year, however, some years have 52 weeks and start within the last days of the last year. And others have 53 weeks.
An example of 52 weeks is the 2020 calendar:
Where the first week begins on Dec 30.
And the example of 53 weeks is the 2016 calendar:
That begins only on Jan 4th.
Code
The following code is commented and outputs an array of arrays with the week numbers.
Sub w_test()
Dim Arr() As Variant, ArrDateW() As Variant
'Initial Date
DateI = DateSerial(2015, 5, 5)
'Final Date
DateF = DateSerial(2017, 9, 20)
'Difference in weeks between DateI and DateF
weekDif = DateDiff("ww", DateI, DateF) + k - 1
i = Weekday(DateI)
d = DateI
'If not Sunday, go back to last week, to start the loop
If i <> 1 Then
d = DateAdd("d", -(i - 1), d)
End If
ReDim ArrDateW(weekDif)
ReDim Arr(2)
'Loop on all weeks between two dates to populate array of arrays
For i = 0 To weekDif
'Date
Arr(0) = d
'Trying to solve problem with New Year
If Application.WorksheetFunction.WeekNum(d) = 53 Then
flag = True
End If
If flag = False Then
Arr(1) = Application.WorksheetFunction.WeekNum(d)
Else
Arr(1) = Application.WorksheetFunction.WeekNum(DateSerial(Year(d) + 1, 1, 1))
flag = False
End If
'Year
Arr(2) = Year(d)
'Populate array of arrays
ArrDateW(i) = Arr
'Next Week Number
d = DateAdd("ww", 1, d)
Next i
'To stop with Ctrl+F8
Debug.Print d
End Sub
Question
2015 had 53 weeks, however the program outputs the following:
And between 2016 and 2017, the output is a mess:
How to fix the program to output these week numbers correctly?
I went about it somewhat differently, relying on built-in VBA functions to correctly calculate the week numbers. Read about ISO week numbers is this answer and see how I'm using the DataPart function -- though you can substitute your own version of Ron de Bruin's ISO week number function if you feel it's warranted.
A couple of quick side notes:
Always use Option Explicit
Try to use more descriptive variable names. YOU know what you're talking about NOW. In a few months, you'll struggle to remember what d and Arr mean (even if it seems obvious now). It's just a good habit and makes the code self-documenting.
My example below breaks the logic into a separate function with an optional parameter (just for fun) that would allow the caller to change the start of the week to a different day.
Code module:
Option Explicit
Sub w_test()
Dim initialDate As Date
Dim finaldate As Date
initialDate = #5/5/2015#
finaldate = #9/29/2017#
Dim weeks As Variant
weeks = WeekNumbers(initialDate, finaldate)
Debug.Print "There are " & UBound(weeks, 1) & " weeks between " & _
Format(initialDate, "dd-mmm-yyyy") & " and " & _
Format(finaldate, "dd-mmm-yyyy")
End Sub
Private Function WeekNumbers(ByVal initialDate As Date, _
ByVal finaldate As Date, _
Optional ByVal weekStart As VbDayOfWeek = vbSunday) As Variant
Dim numberOfWeeks As Long
numberOfWeeks = DateDiff("ww", initialDate, finaldate, weekStart, vbFirstFullWeek)
Dim startOfWeek As Date
If Weekday(initialDate) <> vbSunday Then
Dim adjustBy As Long
If Weekday(initialDate) > weekStart Then
adjustBy = Weekday(initialDate) - weekStart
Else
adjustBy = (Weekday(initialDate) + 7) - weekStart
End If
startOfWeek = DateAdd("d", -adjustBy, initialDate)
End If
Dim allTheWeeks As Variant
ReDim allTheWeeks(1 To numberOfWeeks)
Dim weekInfo As Variant
ReDim weekInfo(1 To 3)
Dim i As Long
For i = 1 To numberOfWeeks
weekInfo(1) = startOfWeek
weekInfo(2) = DatePart("ww", startOfWeek, weekStart, vbFirstFourDays)
weekInfo(3) = Year(startOfWeek)
allTheWeeks(i) = weekInfo
startOfWeek = DateAdd("ww", 1, startOfWeek)
Next i
WeekNumbers = allTheWeeks
End Function
I have two workbooks, A and B, and two sheets, 1 and 2, in both the workbooks.I need to compare and find the match based on time.In workbook B in sheet 1 I have hh:mm:ss 24 hrs time format.But in workbook A I have the time from and to in number format like 600 and 800 etc. I have changed the time format in workbook 1 to hh:mm:ss but the problem I am getting after running for the first time is that the time has changed to 06:00:00 and again in the second run it is changed to 00:00:00.
Dim rCell As Range
Dim iHours As Integer
Dim iMins As Integer
Dim lrow As Long
Dim rn As Range
lrow = Sot.Range("d" & Rows.Count).End(xlUp).Row
Sot.Activate
Set rCell = Sot.Range(Cells(5, 4), Cells(lrow, 5))
For Each rn In rCell
If IsNumeric(rn.Value) And Len(rn.Value) > 0 Then
iHours = rn.Value \ 100
iMins = rn.Value Mod 100
rn.Value = (iHours + iMins / 60) / 24
rn.NumberFormat = "h:mm:ss"
End If
Next
For i = 5 To eRowplan
Time_from = Sotplan.Range("D" & i).Value
Time_To = Sotplan.Range("E" & i).Value
Time_from = TimeSerial(Hour(Time_from), Minute(Time_from),
Second(Time_from))
Time_To = TimeSerial(Hour(Time_To), Minute(Time_To), Second(Time_To))
If B_Time > "24:00" Then B_Time = "23:59"
B_Time = TimeSerial(Hour(B_Time), Minute(B_Time), Second(B_Time))
I tried with above codes
You can do it with the following if you want a VBA solution for e.g. 600 = 600 minutes
Dim c
For Each c In Selection
c.Value2 = c / (24 * 60)
c.NumberFormat = "hh:mm"
Next c
Or just use = A1 / (24 * 60) and format as Time
Update after comments
For 600 = 06:00:00 you can use the following
Dim c, tmpTime As Variant
For Each c In Selection
' Test if number
If IsNumeric(c.Value2) Then
' Split into character array, the Len(c.Value2) limits the size of the array otherwise
' an additional empty element is created
tmpTime = Split(StrConv(c.Value2, vbUnicode), Chr$(0), Len(c.Value2))
' Write results back and format
With c.Offset(0, 1)
.Value2 = Join(tmpTime, ":")
.NumberFormat = "hh:mm:ss"
End With
End If
Next c