Excel VBA – 如果value> x,则加上sum

我有一个表与时间值。 如果在大于90分钟(1:30:00)的指定行中存在任何值,那么我需要在行的末尾添加差异(即,它的差距)。 所以,该框可以是空白的,可以只有一个单元格的值,或者可以添加多个值。 我已经有了For循环遍历每一个单元格。 我需要这个部分来总结这些值。 理想情况下,如果有一个嵌套循环为6行做6个单独的总和…

'Add break munutes fp.Activate Dim rng As Range For Each rng In Range("B3:F3") If rng.Value > TimeValue("1:31:00") Then End If Next rng 

在这里输入图像说明

很难说如果没有更多的信息,这是完全准确的,但这样的事情应该为你工作:

 Sub tgr() Dim aTimes As Variant Dim dTime As Double Dim aSumResults() As Double Dim lResultIndex As Long Dim i As Long, j As Long Dim bFirst As Boolean dTime = TimeValue("01:00:00") aTimes = ActiveSheet.Range("B3:F9").Value 'Change to the full table range ReDim aSumResults(1 To UBound(aTimes, 1) - LBound(aTimes, 1) + 1, 1 To 1) For i = LBound(aTimes, 1) To UBound(aTimes, 1) 'Each i represents a row of the data 'Go through each column and collect the conditional sums lResultIndex = lResultIndex + 1 bFirst = True 'Use bFirst to ignore first value greater than dTime For j = LBound(aTimes, 2) To UBound(aTimes, 2) If aTimes(i, j) > dTime Then If bFirst Then 'This if the first value found for the row, ignore it bFirst = False Else 'Not the first value found, include in sum aSumResults(lResultIndex, 1) = aSumResults(lResultIndex, 1) + aTimes(i, j) - dTime End If End If Next j Next i 'Output the results ActiveSheet.Range("G3").Resize(UBound(aSumResults, 1)).Value = aSumResults End Sub 

如果你想避免VBA,这实际上可以通过Excel公式来完成:

 =SUMIF($B$3:$B$9,">"&1.5/24)-COUNTIF($B$3:$B$9,">"&1.5/24)*1.5/24 

总计超过90分钟的所有值,然后从总计中减去已计数的每个值的90分钟。

在这里输入图像说明

如果这是一个选项,我会推荐Excel公式,因为VBA解决scheme的限制。

 =SUMPRODUCT((B$3:B9-1/16)*(B$3:B9>1/16)) 

或者使用数组公式input一段时间(使用Ctrl + Shift + Enterinput):

 =SUMIF(B$3:B9-1/16,">0") 

你说你想要连续的时间总和,但后来定义了B3:B9,所以我假设你是指一列中的时间总和。 尝试这个:

 Dim i As Integer Dim num1 As Date For i = 3 To 9 If Cells(i, 2).Value > TimeValue("1:30:00") Then num1 = Cells(10, 2).Value + Cells(i, 2).Value - TimeValue("1:30:00") Cells(10, 2).Value = num1 End If Next i 

我已经定义了总和放在单元格B10的位置。 你可以为每一列做一个类似的循环。 我试了一下,它为我工作。