Search code examples
excelvbaworksheetnamed-rangesselect-case

Using Select Case to reference all rows in Named Range


I have the below worksheet change code. The current iteration I would specify the the row numbers manually in each Case which works fine.

The number or rows for each case is changing dynamically by another macro which will insert or delete rows inside the 2 Named ranges "TotalAcc" & "TotalRate".

Is there a way for me to modify this so that the case will reference all the rows or cells in a Named range?

Thank you in advance.

Private Sub Worksheet_Change(ByVal Target As Range)
Dim A As Range, Inte As Range, r As Range

Dim ws1 As Worksheet, ws2 As Worksheet
Set ws1 = ThisWorkbook.Worksheets(1)
Set ws2 = ThisWorkbook.Worksheets(2)

Set A = Range("TotalAcc", "TotalRate")
Set Inte = Intersect(A, Target)
If Inte Is Nothing Then Exit Sub
If Target.Columns.Count > 1 Then Exit Sub

Application.EnableEvents = False
    For Each r In Inte
        Select Case Target.Row
        Case 10, 11, 12, 13, 14, 15
            Range("A" & r.Row).Offset(0, 3).Value = Application.WorksheetFunction.SumIfs(ws2.Range("Y:Y"), ws2.Range("D:D"), ws1.Range("A" & r.Row), ws2.Range("AB:AB"), ws1.Range("B" & r.Row), ws2.Range("M:M"), ws1.Range("C" & r.Row))
            Range("A" & r.Row).Offset(0, 5).Value = Application.WorksheetFunction.SumIfs(ws2.Range("P:P"), ws2.Range("D:D"), ws1.Range("A" & r.Row), ws2.Range("AB:AB"), ws1.Range("B" & r.Row), ws2.Range("M:M"), ws1.Range("C" & r.Row))
        Case 18, 19, 20, 21
            If Range("E" & r.Row).Value <> "" Then
                Range("C" & r.Row).Value = Application.WorksheetFunction.SumIfs(ws2.Range("Y:Y"), ws2.Range("V:V"), ws1.Range("E" & r.Row))
                Range("E" & r.Row).Offset(0, -1).Value = "CONTRACTS@"
                Range("E" & r.Row).Offset(0, 1).Value = Application.WorksheetFunction.Product(Range("C" & r.Row), Range("E" & r.Row))
            Else:
                Range("C" & r.Row).Value = ""
                Range("E" & r.Row).Offset(0, -1).Value = ""
                Range("E" & r.Row).Offset(0, 1).Value = ""
            End If
        End Select
    Next r


Application.EnableEvents = True

Solution

  • Simpler like this:

    For Each r In Inte
        If not Application.Intersect(r, Range("TotalAcc")) Is Nothing Then
            'is in TotalAcc
        Else
             'is in TotalRate
        End if
    Next r
    

    FYI in your posted code:

    Select Case Target.Row
    

    if there are multiple cells in Target this only looks at the first one. Should be

    Select Case r.Row