如何只为一张纸设置vba代码?

时间:2018-06-08 10:32:02

标签: excel vba excel-vba

我目前无法尝试构建一个运行sumifs宏的按钮。我正在尝试在Sheet1中构建按钮,并在Sheet2上执行sumif。我现在拥有的是:

Option Explicit

Sub Sumifs()
    Dim Sht2 As Worksheet
    Dim EndRow As Long
    Dim i As Integer
    Dim SumRange As Range
    Dim CrtA As Range
    Dim CrtB As Range

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

    Set Sht2 = Worksheets("Sheet2")
    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
        sht2.Cells(i, 4) = WorksheetFunction.SumIfs(SumRange, crtA, Range("G" & i), crtB, Range("B" & i))
    Next i
End Sub

我已尝试使用alt + F8运行它并且只要我在Sheet2就可以正常运行,如果我尝试在Sheet1上运行它,则没有任何反应。

另外,有没有办法将sumifs标准链接到单独的工作表?具体来说,我想将Range ("B" & 1)J5:J10上的单元格Sheet3相关联。目前,每当我尝试

时,我都会收到类型错误
worksheets("sheet3").range ("B" & 1)

非常感谢您提供的任何建议。 感谢

1 个答案:

答案 0 :(得分:6)

将代码放入模块中:

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

这个想法是提及" Parent-Worksheet"这是一个很好的做法。范围。否则,它将采用ActiveSheet(如果在模块中)或代码所在的worksheet

每当你使用这样的结构时:

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

您需要告诉VBA以某种方式引用Sht1。这是通过点在这里完成的:

enter image description here

否则它需要父工作表,即ActiveSheet或代码所在的工作表(如果不在模块中)。