简体   繁体   中英

Tallying a value into a variable conditionally based on cell inputs

I am working on a task where I am running tests at different temperatures but the test isn't always run in order so I've been tracking the temperature and the time overall time in the test. Afterwards I go back and manually check how much time was spent at each temperature. The code below shows how far I've gotten thus far but I'm not sure how to handle the empty cells that occur during the weekends when I am not able to tell record the time.

In my example attached, for 'Test 1' I expect to get total of 123 for 'Ambient' from (13-0)+(61-13)+(221-203)+(265-221), however it's outputting 358. Looking for some input on where I'm going wrong here. Thanks in advance!

Here's the code I've written so far:

Sub Calculate_Time_at_Temp()

Dim ambient As Double, cold_neg_20 As Double, humidity As Double, hot_60 As Double, cold_neg_30 As Double, hot_80 As Double, rng As Range, cell As Range

Sheets("Sheet1").Activate
Set rng = Range("X5")
For Each cell In Sheets("Sheet1").Range("C8:W8")
    'If IsNumeric(cell.Offset(-3, 0).Text) Then
        If cell.Value = "Ambient" Then
        ambient = ambient + (cell.Offset(-3, 0).Value - cell.Offset(-3, -1).Value)
        rng.Value = ambient
       
    End If
    'End If
   Next
   
End Sub

在此处输入图像描述

I just added a shift value to get the previous column: -3 if Saturday / Sunday, -1 else. Assuming your dates are located in 1rst row (Cells(1,x)). I'm unable to test it without your file.

Sub Calculate_Time_at_Temp()

    Dim ambient As Double, cold_neg_20 As Double, humidity As Double, hot_60 As Double, cold_neg_30 As Double, hot_80 As Double, rng As Range, cell As Range
    Dim iShift As Integer
    Dim rRangeDate As Range
    Sheets("Sheet1").Activate
    Set rng = Range("X5")
    For Each cell In Sheets("Sheet1").Range("C8:W8")
        Set rRangeDate = Sheets("Sheet1").Cells(1, cell.Column)
        iShift = IIf(Weekday(CDate(rRangeDate.Value), vbMonday) > 5, 3, 1)
        If cell.Value = "Ambient" Then
            ambient = ambient + (cell.Offset(-3, 0).Value - cell.Offset(-3, -iShift).Value)
            rng.Value = ambient
        End If
    Next
   
End Sub

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