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
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
I have Autofill Method Out of Range Class Error from some reason and I can't find why. I have lots of formulas in my code and I use it a lot and it is stops my code every time. this is the relavant part of my sub:
'U means union, M means main
'Advanced filter for visual worksheet
UnionWB.Worksheets("Union").ShowAllData
Dim ULR As Long, ULC As Long, MLR As Long
ULR = Cells(Rows.Count, "A").End(xlUp).Row
ULC = Cells(1, Columns.Count).End(xlToLeft).Column
With MainWB.Worksheets(sheet1)
MLR = .Cells(Rows.Count, "A").End(xlUp).Row
End With
MainWB.Worksheets("aheet2").Columns("A:Z").Clear
UnionWB.Worksheets("Union").Range(Cells(1, 1), Cells(ULR, ULC)).AdvancedFilter Action:=xlFilterInPlace, _
CriteriaRange:=MainWB.Worksheets("sheet1").Range("A1", "A" & MLR), Unique:=False
UnionWB.Worksheets("Union").Activate
Range("A1", "Y" & ULR).Select
Selection.Copy
MainWB.Worksheets("sheet2").Activate
Range("A1").PasteSpecial xlPasteValues
Range("AB2").Select
Selection.AutoFill Destination:=Range("AB2", "AB" & MLR)
If MLR > 2 Then
With MainWB.Worksheets("sheet1).Range("N2")
ActiveCell.FormulaR1C1 = _
"=IF(ISNUMBER(SEARCH(""sheet2"",RC[-9])),""yes"",""no"")"
Selection.AutoFill Destination:=Range("N2", "N" & MLR)
End With
End If
Selection.AutoFill Destination:=Range("AB2", "AB" & MLR)
Selection.AutoFill Destination:=Range("N2", "N" & MLR)
Change the 2 lines below:
Range("AB2").Select
Selection.AutoFill Destination:=Range("AB2", "AB" & MLR)
To:
Range("AB2").AutoFill Destination:=Range("AB2:AB" & MLR), Type:=xlFillDefault
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.
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