How to set up vba code for only one sheet?

后端 未结 1 1028
花落未央
花落未央 2020-12-11 19:39

I am currently stuck trying to build a button that will run a sumifs macro. I am trying to build the button in Sheet1 and have the sumifs execute on Sheet

相关标签:
1条回答
  • 2020-12-11 19:55

    Put the code in a module:

    Option Explicit
    
    Sub SumIfS()
        Dim Sht1 As Worksheet
        Dim Sht2 As Worksheet
        Dim EndRow As Long
        Dim i As Integer
        Dim SumRange As Range
        Dim CrtA As Range
        Dim CrtB As Range
    
        Set Sht2 = Worksheets(2)
        Set Sht1 = Worksheets(1)
    
        With Sht1
            EndRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        End With
    
        Set SumRange = Worksheets("Sheet3").Range("L5:L10")
        Set CrtA = Worksheets("Sheet3").Range("C5:C10")
        Set CrtB = Worksheets("Sheet3").Range("K5:K10")
    
        For i = 5 To EndRow
            With Sht2
                .Cells(i, 4) = WorksheetFunction.SumIfS(SumRange, CrtA, .Range("G" & i), CrtB, .Range("B" & i))
            End With
        Next i
    
    End Sub
    

    The idea is that it is really a good practice to mention the "Parent-Worksheet" of the range. Otherwise it is taking either the ActiveSheet (if in a module) or the worksheet in which the code resides.

    Whenever you are using construction like this:

    With Sht1
        EndRow = Cells(Rows.Count, "A").End(xlUp).Row
    End With
    

    You need to tell VBA to refer somehow to the Sht1. This is done, through dots here:

    Otherwise it takes the Parent worksheet, which is either ActiveSheet or the one where the code is (if not in a module).

    0 讨论(0)
提交回复
热议问题