简体   繁体   中英

Can I use VBA in excel to keep a cumulative total based on a letter in a cell and that cell being highlighted yellow?

I've trying to create a rota for shift workers and I can't really get my head around how to do it but some pointers would be much appreciated.

Basically, for each row in a table I would like to check if that cell is highlighted yellow and if it contains a E, L or D to add 8 to the total and if it contains a W to add 12 to the total.

I understand there's no way to use Excel to perform this function but there might be a way to do it in VBA.

Does anyone have any tips I could use please?

Many thanks

You can write the UDF below in Module and use it as the usual Excel function in cell formula [=TotalSum(A2:H2)]. But color change of cells will not fire recalculation. Press Shift+F9 to recalc the sheet or F9 (whole workbook) Also you san use this code in other sub not as UDF

Public Function TotalSum(rng As Range) As Double
    Application.Volatile    'recalculates with any calculation on the sheet
    
    Static a    ' static variables hold it's values between function call
    If IsEmpty(a) Then a = Split("E:8:L:8:D:8:W:12", ":")   'initially fill
    
    For Each cl In rng
        If cl.Interior.Color = vbYellow Then    ' check if color is yellow
            txt = cl.text
            For i = 0 To UBound(a) Step 2       ' check if text contains defined symbols
                If InStr(1, txt, a(i), vbTextCompare) > 0 Then
                    TotalSum = TotalSum + a(i + 1)  'if yes, add correspondent value
                End If
            Next
        End If
    Next
End Function

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