I was wondering if anyone could help me with this. I have to create a pivot table from a worksheet named as “raw”. Unfortunately, sometimes the name of the worksheet can be some other names such as test or even experiment.
My code is as follow to use a macro to create a pivot table.
Range("A1:Z1048576").Select
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"raw!R1C1:R1048576C12", Version:=xlPivotTableVersion12 _
).CreatePivotTable TableDestination:="Sheet1!R3C1", TableName:= _
"PivotTable1", DefaultVersion:=xlPivotTableVersion12
As you can see, my ‘SourceData:= raw’ which is the name of the worksheet. As I have explained earlier that this raw can be any name by the user it self, so i was wondering if it is possible to create a pivot table from a worksheet that has names that user that uses the macro, self defined its name.
I have also tried using rename coding, but i have to know the worksheet name before i can do anything else..
Follow up:
My GUI has an open and start button to start the whole thing.
Private Sub testFinder_Click()
'Open button
Dim fileToOpen
fileToOpen = Application _
.GetOpenFilename("Text Files (*.txt), *.txt")
If fileToOpen = False Then Exit Sub
TextBox1.Value = fileToOpen
End Sub
Private Sub CommandButton2_Click()
'start button
Application.ScreenUpdating = False
Workbooks.OpenText Filename:=TextBox1.Value, Origin:=437, _
StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:=False _
, Space:=False, Other:=False, FieldInfo:=Array(1, 1), TrailingMinusNumbers:=True
End Sub
Then after that, will be the code for the pivot table.
You can use ActiveSheet from the macro but that might give you undesired results if the active sheet is not the actual sheet which has the data. Here is an alternative. Why not let the user select the Pivot range? You can then use that range in your code?
FOLLOWUP
DISCLAIMER: I always test my code before posting but in the absence of the Text File in the current scenario, I cannot test the below code. Also I have not done any error handling so do let me know if you get any errors and we will take it from there.
Button1 Code remains unchanged. I have changed the 2nd Button code slightly and added the 3rd button. Also note that I am not using hard coded numbers like 1048576. No point taking all rows into consideration if your data is say only till 2000 🙂
TIP: When distributing the application to your user, remember to include error handling. Users often don’t behave like the way you expect them to behave. For example what if the user clicks on the 2nd button before clicking on the 1st button OR what if the user clicks on the 3rd button before clicking on the 1st or the 2nd button 🙂
CODE
FOLLOWUP
TRIED AND TESTED
HTH
Sid