Creating a Macro in VBA to make pivot table from selected data - vba

I am new to VBA and I am trying to create a macro to which I will make a button out of to make a Pivot Table from data that I paste into a certain sheet.
The code below is from a macro that I tried to produce step-by-step of how I want the code to run.
I am selecting certain data (Columns A:G), then pasting that data into another sheet and then creating a blank table.
My code:
Sub Macro2()
'
' Macro2 Macro
'
'
Cells.Select
Range("A672198").Activate
Application.CutCopyMode = False
Selection.Copy
Application.CutCopyMode = False
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sheet2!R1C1:R1048576C7", Version:=xlPivotTableVersion15).CreatePivotTable _
TableDestination:="Sheet11!R3C1", TableName:="PivotTable6", DefaultVersion _
:=xlPivotTableVersion15
Sheets("Sheet11").Select
Cells(3, 1).Select
End Sub
The issue comes from:
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sheet2!R1C1:R1048576C7", Version:=xlPivotTableVersion15).CreatePivotTable _
TableDestination:="Sheet11!R3C1", TableName:="PivotTable6", DefaultVersion _
:=xlPivotTableVersion15
with an error message of:
Run-time error '5': invalid procedure call or argument
I have tried researching how to make a basic macro to create a blank pivot table of my data but I can't seem to figure it out.
I have also looked at many posts from this site and nothing really helped. I tried referencing this post but no luck.
I am using Microsoft Excel 2013*

Give this a shot - this will take columns A:G from Sheet1 and create a new sheet (named whatever), paste all the data into columns A:G on that sheet, then create a third sheet and create a new pivot table based on the data from sheet 2.
Option Explicit
Sub Test()
Dim sht1 As Worksheet, sht2 As Worksheet, sht3 As Worksheet
Dim lastrow As Long
Set sht1 = ThisWorkbook.Worksheets("Sheet1")
lastrow = sht1.Cells(sht1.Rows.Count, "A").End(xlUp).Row
Set sht2 = Sheets.Add(After:=Sheets(Sheets.Count))
Set sht3 = Sheets.Add(After:=Sheets(Sheets.Count))
sht2.Range("A1:G" & lastrow).Value = _
sht1.Range("A1:G" & lastrow).Value
ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
sht2.Name & "!R1C1:R" & lastrow & "C7", Version:=6).CreatePivotTable TableDestination:= _
sht3.Name & "!R3C1", DefaultVersion:=6
End Sub

Try this:
Sub create_pivot()
Dim mysourcedata, mydestination As String
Dim lr As Long
lr = Sheets("Sheet1").Range("A1").End(xlDown).Row '' find your last row with data
mysourcedata = "Sheet1!R1C1:R" & lr & "C5"
mydestination = "Sheet2!R1C1"
Sheets("Sheet2").Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, sourcedata:= _
mysourcedata, Version:=6).CreatePivotTable TableDestination:= _
mydestination, TableName:="PivotTable1", DefaultVersion:=6
End Sub

Related

TableDestination:="Sheet2!R1C1"

Sub Macro1()
Sheet2.Select
ActiveWindow.SmallScroll Down:=-69
Cells.Select
Selection.Delete Shift:=xlUp
Range("A1").Select
Dim Endrow&
Endrow = Sheet3.Range("H1").End(xlDown).Row
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
Sheet3.Name & "!R1C8:R" & Endrow & "C21", Version:=6).CreatePivotTable _
**TableDestination:=Sheets("Sheet2").Cells(1, 1)**, TableName:= _
"PivotTable1", DefaultVersion:=6
I tried to make this Pivot Tables Macro insert into Sheet2!R1C1 (which is an existing worksheet), instead of creating a new worksheet. However, I receive Run-time error
5: Invalid Procedure call or argument.
I have tried to following methods
TableDestination:=Sheets("Sheet2").Cells(1, 1)
TableDestination:="Sheet2!R1C1"
TableDestination:=Sheet2.name & "!R1C1"
but all failed. How can I make this right?
Your code works on the assumption that there are worksheets with the Code Name (not names!) of Sheet2 and Sheet3. Could it be that you're referring to the sheet's object name which possibly has changed? This works … if you have a Sheet2 and Sheet3
Sub Macro1()
Sheet2.Select
ActiveWindow.SmallScroll Down:=-69
Cells.Select
Selection.Delete Shift:=xlUp
Range("A1").Select
Dim Endrow&
Endrow = Sheet3.Range("H1").End(xlDown).Row
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
Sheet3.Name & "!R1C8:R" & Endrow & "C21", Version:=6).CreatePivotTable _
TableDestination:=Sheets("Sheet2").Cells(1, 1), TableName:= _
"PivotTable1", DefaultVersion:=6
End Sub
Perhaps check that when you refer to Sheet2 and Sheet3 that they still exists.
Public Sub ListSheetNames()
Dim vSheet As Worksheet
For Each vSheet In Worksheets
Debug.Print "Code Name/Sheet Name: " & vSheet.CodeName & " / " & vSheet.Name
Next
End Sub
Maybe change Sheet2 reference to the below … and similarly for Sheet3
sheets("Sheet2")

How to save as workbook with cell name in vba

I created MACRO in my order calculation template to deleted some unnecessary rows and save a sheet as workbook with "name". MACRO works great, but where is one annoying problem, I every time have change it this workbook name according to order number. So, I want to create/improve my MACRO to save sheet as workbook with cell name (this cell range "G1").
Could someone have ideas how to do this?
Sub Pirmoji()
'
' Pirmoji Macro
Sheets("Svorio Patvirtinimo dok").Select
ActiveSheet.Shapes.Range(Array("Column1")).Select
Sheets("Svorio Patvirtinimo dok").Copy
Rows("1:6").Select
Selection.Delete Shift:=xlUp
ActiveWindow.SmallScroll Down:=66
Dim LastRow As Long, myCell As Range, myRange As Range
Dim myCell1 As Range
LastRow = ActiveCell.SpecialCells(xlCellTypeLastCell).Row
Set myCell1 = Range("A" & LastRow)
Cells.Find(What:="• Praau atkreipti d?mes?:", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False).Activate
Set myCell = ActiveCell
Set myRange = Range(myCell, myCell1)
myRange.EntireRow.Delete
ActiveWindow.SmallScroll Down:=-78
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ActiveSheet.Copy
MsgBox "This new workbook will be saved as MyWb.xls(x)"
ActiveWorkbook.SaveAs ThisWorkbook.Path & "\MyWb", xlWorkbookNormal
MsgBox "It is saved as " & ActiveWorkbook.FullName & vbLf & "Press OK to close it"
ActiveWorkbook.Close False
End Sub
The code below will fix only the relevant part of your post, how to save "Svorio Patvirtinimo dok" sheet as a new workbook, and file name according to the value in "G1".
You can do a lot of improvements also in the upper section of your code, there are a lot of unnecessary Select, Selection and ActiveCell.
Read HERE why you should avoid using Select, Activate and other similar types.
Modified Code (relevant section only):
Dim Sht As Worksheet
Dim NewWBName As String
' set the worksheet object
Set Sht = ThisWorkbook.Sheets("Svorio Patvirtinimo dok")
MsgBox "This new workbook will be saved as MyWb.xls(x)"
' set the bnew name in same path and file name according to the value in "G1"
NewWBName = ThisWorkbook.Path & "\" & Sht.Range("G1").Value2 & ".xlsx"
'save sheet as workbook with the name in cell "G1"
Sht.SaveAs NewWBName, 51 ' save format 51 - .xlsx
MsgBox "It is saved as " & NewWBName & vbLf & "Press OK to close it"
ActiveWorkbook.Close False

Need help correcting a VBA/Macro code to combine multiple tabs into one

I am new to VBA and have primarily used it in conjunction with creating a macro. As you can see from the code below, I am trying to take tables from three different tabs and merge them into one. However, I am having a hard time understanding how to ensure that each table will paste directly underneath the previous table and not overwrite it (especially when each month new rows are created).
Thank you in advance for any help you can provide.
' Step_4_Combination_Tab Macro
Sheets("Past Data").Select
Range("A2:M2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Combination").Select
Range("A1").Select
ActiveSheet.Paste
Range("A1").Select
Selection.End(xlDown).Select
Range("A5483").Select
Sheets("Actual").Select
Range("A5:M5").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Combination").Select
Range("A5483").Select
ActiveSheet.Paste
Range("A5483").Select
Selection.End(xlDown).Select
Range("A8341").Select
Sheets("Forecast").Select
Range("A4:M4").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Combination").Select
ActiveSheet.Paste
Selection.End(xlUp).Select
End Sub
The following code might do what you want:
Sub mergeSheets()
Set targetSheet = Sheets("Combination")
For i = 1 To Sheets.Count
If Sheets(i).Name <> "Combination" Then
Last = LastRow(Sheets("Combination"))
Sheets(i).UsedRange.Copy targetSheet.Cells(Last + 1, 1)
End If
Next i
End Sub
Function LastRow(sh As Worksheet)
LastRow = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
End Function
some codebits taken from here https://www.exceltip.com/cells-ranges-rows-and-columns-in-vba/copy-the-usedrange-of-each-sheet-into-one-sheet-using-vba-in-microsoft-excel.html
You will need to find the last row that has data and paste you next table there.
LR = Sheets("Combination").Range("A" & Rows.Count).End(xlUp).Row
Pasterange = "A" & LR
Sheets("Combination").Range(Pasterange).Paste
I am guessing that you want to copy data from tabs "Past data", "Actual" and "Forecast" to "Consolidated". Am I right? And for some odd reason data in source worksheets begins in different rows. I would do it this way:
Sub AllToCons()
CopyToCons "Past data", 2
CopyToCons "Actual", 5
CopyToCons "Forecast", 4
End Sub
Sub CopyToCons(wsName As String, lRow As Long)
'wsName: name of sheet we are copying from
'lRow: number of row where data start
Dim ws As Worksheet
Dim wsCons As Worksheet
Dim rng As Range
Set wsCons = ThisWorkbook.Worksheets("Consolidated")
Set ws = ThisWorkbook.Worksheets(wsName)
With ws
Set rng = Range(.Range("A" & lRow), .Range("M" & .Cells.Rows.Count).End(xlUp))
End With
rng.Copy
With wsCons
.Range("A" & .Cells.Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial xlPasteAll
End With
If you want to paste values only, type xlPasteValues instead of xlPasteAll.
Hope it helped.

Autofilter in another sheet using VBA

I intend to filter values that begins with 314 in column F, and clear its contents(entire row). The workbook has 30,000+ rows and I think looping is not a good option when filtering in another sheet(sA). I recorded the following code below.
Sheets("sA").Select
Selection.AutoFilter
ActiveSheet.Range("$A$1:$AF$30436").AutoFilter Field:=6, Criteria1:="=314*" _
, Operator:=xlAnd
ActiveCell.Offset(-181, -2).Range("A1:AF30436").Select
ActiveCell.Activate
Selection.ClearContents
When I ran the code, a Runtime Error 1004 appears. I think because of the ActiveCell, because I ran the code in a different sheet(sB, where the button for filtering sheets in sA is found). What could be the possible fix to this? Any suggestions?
this should work ,
Sub filter()
Dim ws As Worksheet
Set ws = Sheets("sheet1")
ws.Range("$A$1:$AF$30436").AutoFilter Field:=6, Criteria1:="=314*" _
, Operator:=xlAnd
Dim LR As Long
LR = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
ws.Range("A2:AF" & LR).SpecialCells(xlCellTypeVisible).ClearContents
ws.AutoFilterMode = False
End Sub

VBA - Format Name

I am hoping someone can help me in my dilemma. Due to a system software limitation, I need to have all my code in one Macro.
1.) take Column Q which is a name in the format "last, first" and break it up using text to column (some names contain initials which is why I used text to column)
2.) include code to dismiss the message box that appears "Do you want to replace the contents of the destination cells?"
3.) delete all columns that are generated except the "last" & "first" name.
4.) concatenate the two columns so that they read Firstname Lastname
5.) auto fill down to the last row.
6.) copy paste special the values into an adjacent column and delete the old column with the function.
I tried recording the code but it seems that what I need can't be recorded and needs to be written.
Here's my shot at get those steps to work, pulled from code from my recorder as well as forums, and think I need a trained eye to sort through my mess:
Application.DisplayAlerts = False
Columns("Q:Q").Select
Selection.TextToColumns Destination:=Range("Q1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=True, _
Semicolon:=True, Comma:=True, Space:=True, Other:=False, FieldInfo:= _
Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1)), TrailingMinusNumbers:= _
True
Application.DisplayAlerts = False
Columns("U:U").Select
Selection.Delete Shift:=xlToLeft
Columns("S:T").Select
Selection.ClearContents
Range("S2").Select
ActiveCell.FormulaR1C1 = "=CONCATENATE(RC[-1], "" "", RC[-2])"
Range("S2").Select
Selection.AutoFill Destination:=Range("S2:500")
Range("S2:S42").Select
Columns("S:S").Select
Selection.Copy
Columns("T:T").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("T1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "Lead Recruiter"
Columns("Q:S").Select
Selection.Delete Shift:=xlToLeft
Thanks to Ron, I was able to get the msg box to dismiss. Right now it's break at the line:
Selection.AutoFill Destination:=Range("S2:500")
How can I update this to Autofill to the last row? The data is in column Q. Any insight is greatly appreciated.
My Assumptions
Data is in Column Q
There is no data after Column Q
The results needs to be generated in Column R. If you want to replace the values in Column Q then see CODE 2.
Here is the shortest code that I could think of.
CODE 1
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long
'~~> Change this to the relevant sheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
'~~> Find the last row in a column
lRow = .Range("Q" & .Rows.Count).End(xlUp).Row
'~~> Enter the formula in the complete column
.Range("R1:R" & lRow).Formula = "=IFERROR(MID(Q1,FIND("","",Q1,1)+2,FIND("" "",Q1,FIND("","",Q1,1)+2)-" & _
"(FIND("","",Q1,1)+2)),MID(Q1,FIND("","",Q1,1)+2,LEN(Q1)-FIND("","",Q1" & _
",1)+2+1)) & "" "" & LEFT(Q1,FIND("","",Q1,1)-1)"
'~~> Convert all formulas to values in one go
.Range("R1:R" & lRow).Value = .Range("R1:R" & lRow).Value
End With
End Sub
ScreenShot
CODE 2
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long
'~~> Change this to the relevant sheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
'~~> Find the last row in a column
lRow = .Range("Q" & .Rows.Count).End(xlUp).Row
'~~> Enter the formula in the complete column
.Range("R1:R" & lRow).Formula = "=IFERROR(MID(Q1,FIND("","",Q1,1)+2,FIND("" "",Q1,FIND("","",Q1,1)+2)-" & _
"(FIND("","",Q1,1)+2)),MID(Q1,FIND("","",Q1,1)+2,LEN(Q1)-FIND("","",Q1" & _
",1)+2+1)) & "" "" & LEFT(Q1,FIND("","",Q1,1)-1)"
'~~> Convert all formulas to values in one go
.Range("R1:R" & lRow).Value = .Range("R1:R" & lRow).Value
'~~> Delete Col Q so R moves to Q
.Columns(17).Delete Shift:=xlToLeft
End With
End Sub
Followup from Comments
Is this what you are trying?
Sub FormatPushReport()
Dim ws As Worksheet
Dim lRow As Long
'~~> Change this to the relevant sheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
.Range("R:R,U:U").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
.Range("R1").Value = .Range("Q1").Value
.Range("V1").Value = .Range("U1").Value
'~~> Find the last row in a column
lRow = .Range("Q" & .Rows.Count).End(xlUp).Row
'~~> Enter the formula in the complete column
.Range("R2:R" & lRow).Formula = "=IFERROR(MID(Q2,FIND("","",Q2,1)+2,FIND("" "",Q2,FIND("","",Q2,1)+2)-" & _
"(FIND("","",Q2,1)+2)),MID(Q2,FIND("","",Q2,1)+2,LEN(Q2)-FIND("","",Q2" & _
",1)+2+1)) & "" "" & LEFT(Q2,FIND("","",Q2,1)-1)"
.Range("V2:V" & lRow).Formula = "=IFERROR(MID(U2,FIND("","",U2,1)+2,FIND("" "",U2,FIND("","",U2,1)+2)-" & _
"(FIND("","",U2,1)+2)),MID(U2,FIND("","",U2,1)+2,LEN(U2)-FIND("","",U2" & _
",1)+2+1)) & "" "" & LEFT(U2,FIND("","",U2,1)-1)"
'~~> Convert all formulas to values in one go
.Range("R2:R" & lRow).Value = .Range("R2:R" & lRow).Value
.Range("V2:V" & lRow).Value = .Range("V2:V" & lRow).Value
.Columns(18).Replace What:="#VALUE!", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
.Columns(22).Replace What:="#VALUE!", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
.Range("Q:Q,U:U").Delete Shift:=xlToLeft
End With
End Sub
Screenshot