If I understand your problem statement correctly, this will fix it:
Sub SelectPromoter()
Dim wsAccountDetails As Worksheet
Set wsAccountDetails = ThisWorkbook.Worksheets("New Account Details - Name")
Dim a As String
a = Worksheets("Selection").Cells(3, 1).Value
On Error GoTo Data_NotFound
Dim pt As PivotTable
For Each pt In wsAccountDetails.PivotTables
With pt.PivotFields("Promoter code")
.ClearAllFilters
.CurrentPage = a
End With
GoTo Data_Found
Data_NotFound:
ActiveSheet.PivotTables("PivotTable4").PivotFields("Promotor code").CurrentPage = "(blank)"
Data_Found:
With wsAccountDetails
.PivotTables("PivotTable4").PivotFields("Milvus Account Name Change?").ClearAllFilters
.PivotTables("PivotTable4").PivotFields("Milvus Account Name Change?").CurrentPage = "(All)"
.PivotTables("PivotTable4").PivotFields("Milvus Account Name Change?").PivotItems("N").Visible = False
End With
Next pt
End Sub
The relevant line here is GoTo Data_Found
. If you don't include that line, the code under the label Other:
will be executed regardless of if an error occurs or not. That's why you need to "jump over it". GoTo-labels are not if-statements, which means they have no direct impact on control flow, you have to implement that logic manually by using GoTo
. Although GoTo
-statements aren't considered best practice, they do have some (if very few) genuine use cases. You can read more on how they work here.
I'm not used to working with pivot tables, but I assume there's a way to check if a certain value is available. Handling these situations properly is preferable to simply letting errors be thrown and catching them, as you won't notice different errors when they occur. If you decide to stick to this approach, you should at least constrain it as much as possible:
Sub SelectPromoter()
Dim wsAccountDetails As Worksheet
Set wsAccountDetails = ThisWorkbook.Worksheets("New Account Details - Name")
Dim a As String
a = Worksheets("Selection").Cells(3, 1).Value
Dim pt As PivotTable
For Each pt In wsAccountDetails.PivotTables
On Error GoTo Data_NotFound
With pt.PivotFields("Promoter code")
.ClearAllFilters
.CurrentPage = a
End With
On Error GoTo 0
GoTo Data_Found
Data_NotFound:
ActiveSheet.PivotTables("PivotTable4").PivotFields("Promotor code").CurrentPage = "(blank)"
Data_Found:
With wsAccountDetails
.PivotTables("PivotTable4").PivotFields("Milvus Account Name Change?").ClearAllFilters
.PivotTables("PivotTable4").PivotFields("Milvus Account Name Change?").CurrentPage = "(All)"
.PivotTables("PivotTable4").PivotFields("Milvus Account Name Change?").PivotItems("N").Visible = False
End With
Next
End Sub
Please take a look at where I moved the lines regarding the error handling On Error ...
.
Please also take a look at How to avoid using Select in Excel VBA. You should generally avoid using .Select
and .Activate
as it's inefficient and error-prone. I provided a better approach with the code, namely using a Worksheet
object to address the sheet directly.