Excel在当前工作表上运行宏,即使代码另有指定

时间:2016-08-05 13:44:39

标签: excel vba excel-vba macros autofilter

我有以下代码:

Sheets("Booked").Range("$A$1:$H$379").AutoFilter Field:=8, Criteria1:= _
        ">=" & StartDat
Sheets("Booked").Range("$A$1:$H$379").AutoFilter Field:=9, Criteria1:= _
        "<=" & EndDat
CorBookCol = Worksheets("Booked").Cells.Find("Booked Impressions").Address

BookAnswer = Worksheets("Booked").Application.WorksheetFunction.Subtotal(9, Range(CorBookCol, Range(CorBookCol).End(xlDown)))
MsgBox (BookAnswer)
Debug.Print "------------------"
Debug.Print BookAnswer & " - Booked Answer"

目标是让宏从我的&#34; Booked&#34;中获取一个列的子总和。工作表并将该数字与我当前工作表中的其他数字结合使用。但是,即使我已经指定宏从&#34; Booked&#34;中找到了子总数。工作表,它只会找到&#34; BookedCorCol&#34;的小计。我当前的工作表上的地址。任何帮助都将非常感谢

2 个答案:

答案 0 :(得分:1)

您需要完全限定您的范围。您是否在Range对象之前看到.(点)?如果您不这样做,则范围将引用ActiveSheet

With Worksheets("Booked")
    BookAnswer = .Application.WorksheetFunction.Subtotal(9, _
                 .Range(CorBookCol, .Range(CorBookCol).End(xlDown)))
End With

答案 1 :(得分:1)

您忘了限定传递给小计功能的两个Range来电。

With Sheets("Booked")
   .Range("$A$1:$H$379").AutoFilter Field:=8, Criteria1:=">=" & StartDat
   .Range("$A$1:$H$379").AutoFilter Field:=9, Criteria1:="<=" & EndDat
   CorBookCol = .Cells.Find("Booked Impressions").Address

    BookAnswer = Application.WorksheetFunction.Subtotal(9, .Range(CorBookCol, .Range(CorBookCol).End(xlDown)))
End With
MsgBox (BookAnswer)
Debug.Print "------------------"
Debug.Print BookAnswer & " - Booked Answer"