0

在下面的代码中,我在名为“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

此外,我可以对多个输入求和:

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

问题是每个新输入都会覆盖nextCell.Value,而我想跟踪每个输入。我尝试使用=t1+t2第一个代码示例中公开的公式 (),但双击不会产生任何结果。


编辑

我正在尝试制作秒表。我的目标是计算在一项任务上花费的时间。为了让事情更清楚,这是我正在尝试做的事情,一步一步:

  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. 等等...
4

3 回答 3

2

我终于发现问题出在我正在使用的特定语言上。我只是替换FormulaFormulaLocal,现在它可以工作了!另外,(Time - .Value) * 1允许将经过的时间转换为相应的十进制值。非常感谢大家:)

于 2013-02-01T09:25:42.253 回答
1

Excel 中的日期在内部存储为自 1900 年 1 月 1 日以来的天数。
因此 1 天 = 1。
因此 1 小时 = 1/24。
因此,要将您的时间以十进制秒为单位,请将其乘以 24 * 60 * 60


编辑:当您引用单元格的值时,
我会引用nextCell.Value而不是引用,例如nextCell.FormulanextCell.Formula = nextCell.Formula & "+" & (Time - .Value)

于 2013-01-31T10:01:09.313 回答
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
        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
每个值都是自上次双击后的秒数。

于 2013-01-31T17:18:25.087 回答