简体   繁体   中英

Excel vba - logic failure

I have a spreadsheet(x4) that add up total hours worked by several employees. One employee's total comes to 24hrs. In my function, due to how Excel represents hours internally, that equates to 1. Based on the value of 'hours' it then formats the cell to show total hours:min for each person. I've checked - typename(hours)= double. I cannot see why hours>=1 doesn't equate to 'True' when hours = 1. If I add 1 minute to the spreadsheet values for that person, it works as expected?

Public Function format_hours(hours As Variant) As Variant   
If hours >= 1 Then
     format_hours = Application.Text(hours, "[hh]:mm")
ElseIf hours > 0 Then
     format_hours = Format(hours, "hh:mm")
Else
     format_hours = 0
End If
End Function

The problem is that the Hours as Variant is probably coming through as a String , and not a Date/Double. Since you never explicitly check/convert it to Date/Double then in your If hours >= 1 Then it's probably not doing the implicit conversions and comparision that you expect.

Solution: use explicit conversions and comparisons. Implicit ones suck because they inevitably produce mysterious bugs like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM