VBA: Creating a Pivot Table - vba

I've been able to create Pivot Tables in code before but that was adding to a new worksheet. I'm now trying to add a Pivot Table to an existing worksheet and am getting error message "Run-time error 1004: The PivotTable field name is not valid". The code is below, my error begins in the last segment beginning with ActiveWorkbook and ending with xlPivotTableVersion14. Any help would be much appreciated.
Public Sub AlliedPT()
Dim AlliedData As String
Dim SAProw As Long
Dim PivotSheet As String
Sheets("Sheet1").Select
SAProw = Cells(Rows.Count, "A").End(xlUp).Row
Sheets("Sheet1").Select
ActiveWorkbook.Names.Add Name:="AlliedData", RefersTo:= _
"=Sheet1!$A$1:$N$" & SAProw
Sheets("PivotSheet").Select
PivotSheet = ActiveSheet.Name
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"AlliedData", Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:=PivotSheet & "!R3C6", TableName:="PivotTable18",
DefaultVersion _
:=xlPivotTableVersion14
End Sub

I think you should check your Row 1 Columns A-N in SHeet 1 and make sure there is a unique, non-blank column name for each column in your source data. The first row contains the pivot table field names.

Related

VBA: How to change a blank value returned using a Vlookup into a Space " "

I'm using VBA to Vlookup information from one table into another. The information that I'm trying to return for Column I is only available for some of the rows. The reference number is found, but the column where the information is being pulled from is blank. Is there a way to turn these blank returns into a space " " with VBA. Again, I have more code relying on these blanks to show as spaces: Any help would be appreciated. This is what I used to try to turn them into blanks that did not work:
Sub Macro10 ()
Dim Lastrow As Long
Dim i As Long
Lastrow = Cells(Rows.Count, "C").End(xlUp).Row
Range("I5").Select
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(C[-7],Sheet1!C4:C13,4,0),"" "")"
Selection.AutoFill Destination:=Range("I5:I" & Lastrow)
End Sub
ActiveCell.FormulaR1C1 = _
"=IF(IFERROR(VLOOKUP(C[-7],Tabelle1!C4:C13,4,0),"" "")="""","" "",IFERROR(VLOOKUP(C[-7],Tabelle1!C4:C13,4,0),"" ""))"

In VBA (Excel) how can Column A insert an ID header followed by 1-X UNTIL it reaches the empty cell representing the highest row with data?

I am trying to create a macro that will insert a column, which is to be the first column in the spreadsheet (A) while shifting all original columns over 1 column to the right.
I then need this first column to create the header "ID" with each one numerically counting the rows:
[A]
ID
1
2
3
I only want the numbering to stop once it has reached the last relevant row in the spreadsheet. I was able to generate the following VBA by doing what I would normally do to accomplish this task while recording the macro and ended up with this:
Sub InsertID()
'
' InsertID Macro
' Add first column to be 1-##
'
' Keyboard Shortcut: Ctrl+Shift+N
'
Columns("A:A").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("A1").Select
ActiveCell.FormulaR1C1 = "ID"
Range("A2").Select
ActiveCell.FormulaR1C1 = "1"
Range("A3").Select
ActiveCell.FormulaR1C1 = "2"
Range("A2:A3").Select
Selection.AutoFill Destination:=Range("A2:A522")
Range("A2:A522").Select
Range("A1").Select
End Sub
Obvoiusly, this doesn't work for my situation. The template I was using only had 521 rows. This number is going to be a variable which can usually be determined by the number of rows in the original column A (Which is now column be after running this macro).
I have extensively looked into how to create a variable for number of rows in a specific column but have been unable to find a question that has similar enough parameters even though it seems so simple.
Thanks in advance
Try this...
Sub CreateIDColumn()
lr = ActiveSheet.UsedRange.Rows.Count
Columns(1).Insert
Range("A1").Value = "ID"
Range("A2:A" & lr).Formula = "=ROW()-1"
Range("A2:A" & lr).Value = Range("A2:A" & lr).Value
End Sub
I believe the following code will do what you want to do. It declares variables (in case Option Explicit is declared - which it should be), inserts the column, finds the last row (if there is one), and inserts relevant data.
Private Sub InsertID()
Dim lastrow, i As Integer 'declaring variables
'adding column
Range("A1").EntireColumn.Insert
'getting last row #
If Application.WorksheetFunction.CountA(Cells) <> 0 Then
lastrow = Cells.Find(What:="*", _
After:=Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
lastrow = 1
End If
'setting value of cell A1
Cells(1, 1) = "ID"
'setting value for the rest of the cells in column A
For i = 2 To lastrow
Cells(i, 1) = i - 1
Next
End Sub

VBA Delete Range Content Error

I want to clear the contents of column B from line 2 to the last filled cell. As I am working with several open workbooks at the same time I need to make sure the correct Range gets deleted.
When I use this code I'm getting the error 1004 - run time error:
Workbooks("BO_Settings.xlsm").Activate
intLastRow = _
Workbooks("BO_Settings.xlsm") _
.Worksheets(strCurrentSheet).UsedRange.Rows.Count
Workbooks("BO_Settings.xlsm") _
.Worksheets(strCurrentSheet).Range( _
Cells(2, 2) _
, Cells(intLastRow, 2) _
).ClearContents
What am I doing wrong?
You need to specify which cell you are using inside the range.
Dim wS as worksheet
Set wS = Workbooks("BO_Settings.xlsm").Worksheets(strCurrentSheet)
Range(wS.Cells(2,2), wS.Cells(intLastRow,2)).ClearContents

VBA; Invalid procedure or argument error

A little background;
I have to run a weekly reports for my job on Monday for the previous week, however I need to consolidated the material, I did and made a pivot table and I have to do this for multiple worksheets. However I decided to create a macro to do this redundant task. Created it now I seem get this error message "Invalid Procedure or Argument". I can't get it to open in my in a new work sheet, t his is my code >>
Sub weekmaster()
'
' weekmaster Macro
' Macro for the week
'
' Keyboard Shortcut: Ctrl+t
'
Cells.Select
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"weekmaster!R1C1:R1048576C62", Version:=xlPivotTableVersion12). _
CreatePivotTable TableDestination:="Sheet9!R3C1", TableName:="PivotTable1" _
, DefaultVersion:=xlPivotTableVersion12
Sheets("Sheet9").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Order ID")
.Orientation = xlRowField
.Position = 1
End With
It appears you're missing one argument. CreatePivotTable takes the following arguments:
expression.CreatePivotTable(TableDestination, TableName, ReadData, DefaultVersion)
TableDestination Required Variant The cell in the upper-left corner of the PivotTable report’s destination range (the range on the worksheet where the resulting PivotTable report will be placed). The destination range must be on a worksheet in the workbook that contains the PivotCache object specified by expression.
TableName Optional Variant The name of the new PivotTable report.
ReadData Optional Variant True to create a PivotTable cache that contains all of the records from the external database; this cache can be very large. False to enable setting some of the fields as server-based page fields before the data is actually read.
DefaultVersion Optional Variant The default version of the PivotTable report.
Subsequently, you'll probably want to add 'true' between your TableName and DefaultVersion.
Cheers, LC
You'll get an error if you run the macro more than once, or if Sheet9 already exists (because the macro tries to create the same pivot table with the same name on the same sheet). If I am to assume that you a new PivotTable in a new worksheet to be generated every time you go to your data sheet and run the macro, you can update your code with the following:
Dim myRange as Range
dim myNewSheet as Worksheet
' Stores all continuous data on the sheet in the myRange variable
Set myRange = Range("A1").CurrentRegion
' Adds a new sheet and stores it in the myNewSheet variable
Set myNewSheet = Sheets.Add
' Use the variables to create the new pivot table
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
myRange, Version:=xlPivotTableVersion12).CreatePivotTable _
TableDestination:=myNewSheet.Cells(3, 1), DefaultVersion _
:=xlPivotTableVersion12
' Select your Order ID field
With myNewSheet.PivotTables(1).PivotFields("Order ID")
.Orientation = xlRowField
.Position = 1
End With

How to split data in a column into two separate columns?

In Excel, I have a column of names in the format "FirstName LastName". I'd like to split that entire column into two columns, with one containing all of the first names and the other containing all of the last names.
My code so far:
'Splitting the Traveler Display Name column
Dim SplitPoint As Long
'L2 is the column containing names to be split
Range("L2").Select
Do Until IsEmpty(ActiveCell)
'Search for position of space within the cell
SplitPoint = InStrRev(ActiveCell, " ", -1, vbTextCompare)
'Put the last name in the column next to the source column
ActiveCell.Offset(0, 1) = Trim(Left(ActiveCell, SplitPoint))
'Replace the source column with the first name
ActiveCell.Offset(0, 0) = Trim(Mid(ActiveCell, SplitPoint))
Loop
The solutions I have found so far have required that the cells be selected manually, which was unreasonable for the amount of data I am working with. I found this solution, but I get the following error: Invalid Procedure call or argument.
NON VBA Method
Why not use Data~~>Text To Columns?
VBA Method
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim LastRow As Long, i As Long
Dim tmpArray() As String
'~~> This is the relevant sheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
LastRow = .Range("L" & .Rows.Count).End(xlUp).Row
For i = 2 To LastRow
If InStr(1, .Range("L" & i).Value, " ") Then
tmpArray = Split(.Range("L" & i).Value, " ")
.Range("M" & i).Value = tmpArray(0)
.Range("N" & i).Value = tmpArray(1)
End If
Next i
End With
End Sub
Private Sub Sample()
Dim myRng As Range
Dim LastRow As Long
LastRow = Sheets("Sample1").UsedRange.Rows.Count
With Sheets("Sample1")
Set myRng = Sheets("Sample1").Range("A2:A" & LastRow)
End With
myRng.TextToColumns _
Destination:=Range("B2:C2"), _
DataType:=xlDelimited, _
Tab:=False, _
Semicolon:=False, _
Comma:=False, _
Space:=True, _
Other:=False
End Sub
I know that this question is quite old, but sharing an answer for anyone who might encounter the same issue in the future.
I have stumbled across this question as I am searching for answers on how to split a column. I tried the looping method but it takes a long time to process.
I have tried the literal translation of the Text to Columns to VBA. The processing time is almost instant, as it is the same as clicking the TextToColumns.
In my solution above, I set the column A with data (i.e., FirstName & LastName) for splitting as a Range. In the Destination, I placed the Range where I want the splitted data to appear (i.e., Column B for First Name, Column C for Last Name). The delimiter is a space.
It is working fine for me. So far, I have tested the code in a 2000 rows data.
I am quite new to VBA so apologies if the code might be poorly formatted or written.