Question

I am pretty new to VBA, so please excuse me if this is a simple question! I have created a template report (titled "Client_Name") that I want populated for each client - in essence all this involves is selecting the client in the PivotTable's report filter and copying the PivotTable's data values to the template. In order to automate this, I have created the following code to duplicate the template and rename it for the client currently selected in the PivotTable:

Sheet_Name_To_Create = Sheets("Pivot").Range("B1").Value
Sheets("Client_Name").Select
Sheets("Client_Name").Copy After:=Sheets(Sheets.Count)
Sheets(ActiveSheet.Name).Name = Sheet_Name_To_Create

My next step would be to go back to the PivotTable ("Pivot" worksheet) and copy the data to the newly created client worksheet. However, the worksheet's name will obviously change differ for each client. Is there a way to reference the VBA code to select the worksheet whose name is the same as the client currently shown in the PivotTables's report filter?

Was it helpful?

Solution

Sheets(ActiveSheet.Name) is an inconvenient way of saying ActiveSheet.

Just capture ActiveSheet in a variable after copying.

Dim CopiedSheet as Worksheet
Set CopiedSheet = ActiveSheet

You don't need sheet's name when you have the sheet itself.

Recommended reading: How to avoid using Select in Excel VBA macros

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top