在Excel 2007中用VBA写一个总和公式(= t1 + t2 + tN)

在下面的代码中,我捕获了一系列名为“chrono”的单元格上的双击事件。 如果目标单元格包含值,则将其与已应用于右侧下一个单元格的公式中已包含的值连接。 我想获得像=0,1+0,1 ,但单元格保持空白。

 Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) On Error Resume Next Dim rng As Range Set rng = Range("chrono") If Target.Count > 1 Then Exit Sub If Not Intersect(Target, rng) Is Nothing Then Application.EnableEvents = False Cancel = True 'stop the edit mode With Target If .Value = "" Then .Value = Time Else: Dim nextCell As Range Set nextCell = ActiveCell.Offset(0, 1) If nextCell.Formula = "" Then nextCell.Formula = "=" & ((Time - .Value) * 24 * 60 * 60) Else: nextCell.Formula = nextCell.Formula & "+" & ((Time - .Value) * 24 * 60 * 60) End If .Value = "" End If End With End If Application.EnableEvents = True End Sub 

编辑

我很抱歉不清楚,我的英语不太好。 我想计算两次双击之间的经过时间(所以没有现有的数据)。 我能够完成这个任务:

 nextCell.Value = Time - .Value 

此外,我可以这样做总结多个input:

 If nextCell.Value = "" Then nextCell.Value = Time - .Value Else: nextCell.Value = nextCell.Value + Time - .Value 

问题是,每个新的input都会越过nextCell.Value而我想跟踪每一个input。 我试图使用公式( =t1+t2 )在第一个代码示例中暴露,但双击不会产生任何结果。


编辑

我正在试着build立一个秒表。 我的目标是计算花费在任务上的时间。 为了使事情更加清晰,下面是我正在努力的一步一步:

  1. 两个单元格:A1和B1
  2. 双击A1
  3. A1值:当前时间
  4. 双击A1
  5. B1公式:“=”&(当前时间 – A1值)
  6. A1值:空
  7. 重复2,3,4
  8. B1公式:B1公式&“+”&(当前时间 – A1值)
  9. 重复2,3,4
  10. 等等…

我终于明白,问题出在我工作的具体语言上。 我简单地用FormulaLocalreplaceFormula ,现在它工作! 另外, (Time - .Value) * 1允许将经过的时间转换为相应的十进制值。 非常感谢大家:)

Excel中的date在内部存储为自1/1/1900以来的天数。
所以1天= 1。
因此1小时= 1/24。
所以要用十进制秒表示你的时间,乘以24 * 60 * 60


编辑:
我会引用nextCell.Value而不是nextCell.Formula当你引用单元格的值,就像nextCell.Formula = nextCell.Formula & "+" & (Time - .Value)

现在仍然很难理解你在做什么,但是这是一个尝试…

以下版本设置一个基准时间,随后每双击一次显示自此以后的累计时间。

 Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) On Error Resume Next Dim rng As Range Set rng = Range("chrono") If Target.Count > 1 Then Exit Sub If Not Intersect(Target, rng) Is Nothing Then Application.EnableEvents = False Cancel = True 'stop the edit mode With Target Dim nextCell As Range Set nextCell = ActiveCell.Offset(0, 1) If .Value = "" Then nextCell.Formula = "" .Value = Time Else: If nextCell.Formula = "" Then nextCell.Formula = "=" & Round((Time - .Value) * 24 * 60 * 60, 2) Else: nextCell.Formula = nextCell.Formula & "+" & _ Round(((Time - .Value) * 24 * 60 * 60) - nextCell.Value, 2) End If ' .Value = "" 'this commented line can be deleted - we'll use the base time End If End With End If Application.EnableEvents = True End Sub 

一旦设置了基准时间,它不会改变。 然后nextCell公式只是附加增量时间差。
恩。 = 2 + 4 + 1 + 0 + 7
每个值都是自上次双击之后的秒数。