Forum Discussion
VBA coding to auto a sheet using Pivot Tables
Hello, I am having an issue with my sheet when I un the following code:
Option Explicit
Sub philautofill()
'
'
Dim wsNew As Worksheet
Dim rng As Range
Dim ShName As String
Dim dataws As Worksheet
Dim templatews As Worksheet
Dim pvtTbl As PivotTable
Dim x, a, b, c, d, e, f, g, h As Integer
Dim rw As Range
Application.ScreenUpdating = False
Set dataws = ThisWorkbook.Sheets("Pivot Table") 'pivot table worksheet
Set templatews = ThisWorkbook.Worksheets("MEGGER SHEET") 'template worksheet
Set pvtTbl = Worksheets("Pivot Table").PivotTables("PivotTable1") 'or access by name
Set rng = pvtTbl.DataBodyRange
a = -3
b = -2
c = -1
d = 0
e = 1
f = 2
g = 3
h = 4
For x = 1 To rng.Rows.Count
Debug.Print ShName
templatews.Copy Before:=templatews
Set wsNew = Sheets(templatews.Index - 1)
wsNew.Name = "MG" + Worksheets("Pivot Table").Range("A5")
wsNew.Range("D21").Value = Worksheets("Pivot Table").Range("C5")
Next x
Application.ScreenUpdating = True
End Sub
I am trying to take information from the pivot table and for it to autofill a separate sheet. It runs fine when there is only one row of information present. Unfortunatley, once there is more than one row of information, I receive an error "1004" That name is already taken try a different one. It also create an extra blank sheet?
any help to debug this issue would be much appreciated.
6 Replies
- mtarlerSilver ContributorI think your problem is this line:
wsNew.Name = "MG" + Worksheets("Pivot Table").Range("A5")
You are trying to assign the name of the new sheet to be the same value each loop- PhildycheCopper ContributorYes, I see the issue.. is there a way to take this out of the loop? I still want the new worksheet created to be named after what is in cell A5.
- mtarlerSilver ContributorSo I really don't know exactly what you are doing and have to ask if maybe you should be using a completely different approach like a Pivot Table or Power Query or even just using some of the new functions with dynamic arrays like FILTER()