简体   繁体   中英

VBA Code works on one tab and not others

the code below only seems to run when I am on the 'Site' tab and no other tab. Can somebody explain why?

Sub GroupReport()

Dim vRegion As String

vRegion = Sheets("Region").Range("A3").Value

Sheets("Site").Cells.AutoFilter

Sheets("Site").Range("A1").AutoFilter Field:=1, Criteria1:=vRegion

Sheets("Site").Range("B2", Range("b2").End(xlDown)).Copy Destination:=Sheets("Region").Range("A8")

End Sub

As you can see in your code, you're running a procedure on the Site worksheet:

Sheets("Site")

You're applying filters and copying ranges but referencing this procedures only for:

Sheets("Site").Cells.AutoFilter

Sheets("Site").Range("A1").AutoFilter Field:=1, Criteria1:=vRegion

Sheets("Site").Range("B2", Range("b2").End(xlDown)).Copy Destination:=Sheets("Region").Range("A8")

If you want your macro to run on all worksheets or "tabs" use the ActiveSheet property .

Option Explicit

Sub GroupReport()

Dim vRegion As String

vRegion = Sheets("Region").Range("A3").Value

With ActiveSheet

    .Cells.AutoFilter
    .Range("A1").AutoFilter Field:=1, Criteria1:=vRegion
    .Range("B2", .Range("B2").End(xlDown)).Copy Destination:=Sheets("Region").Range("A8")

End With

End Sub

It's always a good practice to declare the sheet variables to hold the reference of the sheets the code is dealing with. Also, always qualify the range fully with the sheet reference.

Please give this a try...

Sub GroupReport()
Dim wsSite As Worksheet, wsRegion As Worksheet
Dim vRegion As String

Application.ScreenUpdating = False

Set wsSite = Sheets("Site")
Set wsRegion = Sheets("Region")

vRegion = wsRegion.Range("A3").Value

With wsSite
    .Cells.AutoFilter
    .Range("A1").AutoFilter Field:=1, Criteria1:=vRegion
    .Range("B2", wsSite.Range("B2").End(xlDown)).Copy Destination:=wsRegion.Range("A8")
End With

Application.ScreenUpdating = True
End Sub

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