在excel vba中对时间格式化的单元格进行计算

时间:2013-01-27 19:22:46

标签: vba excel-vba excel

我有三个单元IN,OUT和amp; OverTime全部格式化为[h]:mm, OT小区有这个论坛,

=ROUND(IF(((D10-C10)+(D11-C11))*24>7,((D10-C10)+(D11-C11))*24-7,0)/24*96,0)/96 

将OT计算为1/4小时

8 C D E F 
9   IN      OUT      O/T  C/T
10 7:30 AM 12:15 PM 1:45
11 1:00 PM 5:00 PM

当员工当天工作时,我想要以下内容 要运行的代码;

Dim CT As Date
Title = "Add to CompTime from OverTime"
If Range("E10") > 0 Then
CT = InputBox("Add Hours to CompTime?", Title)
If CT > 0 Then Range("F10").Value = ("E10" - CT)
Else: Range("F10").Value = " "
End If
End Sub
除了;外出似乎有效; 如果CT> 0然后范围(“F10”)。值=(“E10” - CT) 我知道这是格式化问题,但我无法解决问题。

1 个答案:

答案 0 :(得分:0)

始终尝试对范围进行显式引用,无论它们是在工作表还是模块上。使用对象的适当属性 - 在您的情况下,您的范围E10 不合格。假设您正在使用表1:

Option Explicit
'--Beginning of your Subroutine...
Dim Title as String '-- assuming
Dim CT As Date '-- are you sure you want to have a date here?

Title = "Add to CompTime from OverTime"

  If Sheets(1).Range("E10").Value > 0 Then '-- assuming it's a valid date here...
    CT = InputBox("Add Hours to CompTime?", Title)
    '-- assume your CT = 2:45 and OT = 75:30
    '-- use the following as mentioned in my comment
    If CT > 0 Then 
       Application.Text( Sheets(1).Range("F10").Value ,"[h]:mm")  = 
       Application.Text(Sheets(1).Range("E10").Value, "[h]:mm") - Application.Text(CT, "[h]:mm") 
    Else
       Sheets(1).Range("F10").Value = " "
    End If
  End If
End Sub

PS:如果你想计算小时数,你可能只是用VBA来完成整个计算.. =)