How to create Pivot from selection, in VBA, Excel - vba

I tried analyzing how Excel creates a pivot from a selection. It seems pretty simple. I select the entire range in my document and hit Create Pivot with that range. That produces the following code:
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Keyword report!R2C1:R643841C25", Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:="Sheet38!R3C1", TableName:="PivotTable2" _
, DefaultVersion:=xlPivotTableVersion15
I want to use this code in the future, but instead of using a fixed reference to a particular range, I want Excel to draw that data from the Selection. For some reason, that's not included by the Macro Record. I have no idea what "R2C1:R643841C25" is or how it is derived. My selection is: A1:Y643841.
The big question: How do I replace R2C1:R643841C25 in the code with the "Selection"?

An understanding of R1C1 notation would help you answer this.

Related

how to set range for a dynamic area and pasting with filters on in vba

I'm having some trouble with a 2 step problem.
The first part is setting a range to constantly changing data. I've been trying to categorize claims on a worksheet that has data that is being added to the same sheet daily, so the last active cell keeps changing. For instance my issue with the specific line of code is as follows.
Columns(“D:D”).Select
Selection.End(xlDown).Select
ActiveCell.Offset(1).Select
ActiveCell.Offset(0, 91).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Columns(“D:D”).Select
Selection.End(xlDown).Select
ActiveCell.Offset(1).Select
ActiveSheet.Paste
ActiveSheet.Range("$A$1:$EE$3000”).AutoFilter Field:=22, Criteria1:= Array( _
"DUPLICATE PAID/CAPTURED CLAIM:MORE CURRENT REFILL EXISTS", _
"REFILL TOO SOON:CLAIM ALREADY PROCESSED FOR STORE, RX, DOS", _
"REFILL TOO SOON:DISPENSED TOO SOON"), Operator:=xlFilterValues
Columns(“A:A”).Select
Selection.End(xlDown).Select
Selection.Copy
ActiveCell.Offset(1).Select
ActiveSheet.Paste
But I'm now recognizing setting the end range to a value of $EE$2007 isn't working. The column of EE will always remain the same, however the row changes.
The second part has to do with filtering. There are around 56 different categories in a separate column, V which then get flagged with a keyword in column A. I've gotten as far as being able to do the filtering portion and copying from the next cell up, but I'm having trouble pasting that keyword down the next which is the next blank cell and down to the last active row, again which all happens in column A. Above is what I have so far.
And this is where I get stuck. I'm new to all this, and am hoping to learn if there is a better way to go about this.
I was able to get to the second part by changing the range from $EE$2007 to $EE$3000 which caused my data to go further, but it is a possibility.
Thanks in advance.

Avoid repeating selection when I have empty cells in range

I am a bit of a VBA novice so was hoping someone could help with the following.
I need to select (and clear the contents of) all cells in a workbook before pasting new data in. Problem is when I use the (xlToLeft) command it stops when it encounters an empty cell.
I have the code below (which works) but wanted to see if there is a better way, which I am sure there will be.
Sheets("TEST").Activate
Range("BB3").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Selection.ClearContents
Just for reference I have info in the cells to the right which I want to keep and the rows will change on each occasion I run the script.
Why not clear all cells instead of looking for the ones with something in them?
Sheets("TEST").Activate
Activesheet.cells.ClearContents
If you wish to clear a set range:
Worksheets("Test1").Range("A1:I60").ClearContents
If you wish to clear a range based on a value in a row (* is a wildcard, you can substitute it for a text string if required):
Dim lRow as Integer
lRow = Worksheets("Test1").Range("I:I").Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Worksheets("Test1").Range("A1:I" & lRow).ClearContents
Best practice is to avoid using .Select/.Activate and any other indirect reference to a workbook/worksheet/range/cell and provide a fixed reference. Using any non-fixed reference slows down code execution but also makes it hard to review the code at a future date.
first things first - you should avoid using Select altogether.
It's a rather bad coding habit in VBA that's going to do you more harm
than good in the long run. I'm not going to go into too much detail
here, but I'd recommend reading (thoroughly) this question here:
How to avoid using Select in Excel VBA
I've created the following procedure:
clear_til_empty(ByVal inrow as Long)
Finds last non-empty cell in a specified row (inrow) and removes the cells in their respective columns.
Private Sub clear_til_empty(ByVal inrow As Long)
' clears all the cell contents until it hits an empty cell
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
Dim lc As Long ' last empty column
lc = ws.Cells(inrow, Columns.Count).End(xlToLeft).Column
' ws.Range("1:" & lc).ClearContents // didn't work as expected
For i = 1 To lc
ws.Columns(i).ClearContents
Next i
End Sub
So for example, if we wanted to remove data from all columns, until an empty cell is hit in the first row, we would use the following invokation.
clear_til_empty(1)
Obviously, you can pass a variable to it instead.

XLS - Copy & Paste in VBA - PasteSpecial Method Fails

I'm struggling with a nagging issue. I am trying to simply copy and paste a collection of cell forumlas in an XLS worksheet using VBA. The worksheet (wks1) is created and populated from an AccessDB and is working fine otherwise.
Error: "PasteSpecial Method of Range Class Failed"
wks1.Range("P5:S5").Copy
wks1.Range("P5:S10").PasteSpecial _
Paste:=xlPasteFormulas, _
Operation:=xlNone, _
SkipBlanks:=False, _
Transpose:=False
I've attempted a number of variations, but keep bumping into this err msg.
Any suggestions to get this working?
Do this instead:
wks1.Range("P5:S5").Autofill wks1.Range("P5:S10")
or
wks1.Range("P5:S10").formula = wks1.Range("P5:S5").Formula
For the paste special, it has been my experience that less is more:
wks1.Range("P5:S5").Copy
wks1.Range("P5:S10").PasteSpecial xlPasteFormulas
But when only values or formulas are wanted why include the clipboard? It is faster and cleaner to just assign them directly. So I would use the copy/paste when more than the values or formulas are wanted.

Using VBA macro to filter by variable

I have set up a template to pull data from another spreadsheet by filtering said spreadsheet on a variable established in my template.
I can not seem to get the macro to properly filter on my variable (it keeps filtering so that no data remains visible). The spreadsheet I am pulling from goes from column A to AM and has 20830 rows.
I need to utilize my variable to filter column B. Column B is currently set up as a VLOOKUP and I have tried paste valuing the column but to no avail. Any insight as to how I can accomplish this would be greatly appreciated! Please let me know if I need to specify anything more.
Below I have provided my current VBA script (any advice on improving it would also be appreciated). Again, thank you so much for your help!! (Variable to filter on is z, established in an earlier portion of the script)
'Below will grab the Holdings data
Workbooks.Open Filename:= _
"S:\Cashinvt\Audits\D&T" & v & "\PAM.allhold" & y & ".w.stat.xlsm", UpdateLinks:=0
Sheets("allhold").Select
'Here is where I start questioning my code, filtering on variable z
Columns("B:B").Select
ActiveSheet.Range("$B$1:$B$22001").AutoFilter Field:=2, Criteria1:="z"
'Here I am trying to copy the newly filtered data and paste it into another spreadsheet
Range("B1:AM20831").Select
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.Copy
Windows("Audit.Support.Template.xlsm").Activate
Sheets("Holdings").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Windows("S:\Cashinvt\Audits\D&T" & v & "\PAM.allhold" & y & ".w.stat.xlsm").Activate
Sheets("allhold").Select
Windows("S:\Cashinvt\Audits\D&T" & v & "\PAM.allhold" & y & ".w.stat.xlsm").Activate
ActiveWorkbook.Close SaveChanges:=False
Application.DisplayAlerts = True
Sheets("Cover Page").Select
Range("K1").Select
End Sub
ActiveSheet.Range("$B$1:$B$22001").AutoFilter Field:=2, Criteria1:=" & z & "
You are giving a range of only one column but stating Field:=2 try giving the range as the full table, ie
ActiveSheet.Range("$A$1:$AM$22001").AutoFilter Field:=2, Criteria1:=CInt(z)
Notes: i have also included Dougs comment regarding the criteria

Flipping an Excel spreadsheet to opposite axis programmatically

I have an Excel spreadsheet where the data is displayed in columns. For example:
I want to flip this spreadsheet so that the header cells are in Column A, and the data in Column B, C, and D. For example:
Is it possible to accomplish this through an Excel feature/programmatically? I'd rather not flip the data manually.
I am using Excel for Mac 2007, but a solution using any version would be greatly appreciated.
I have found that the simplest method to accomplishing this is using the Transpose feature, as suggested by chris neilsen in the comments.
Here are the steps to using Transpose using Office for Mac 2007:
Copy/Cut the Data --> Edit --> Paste Special... --> Transpose
This macro will create a new Sheet with the tranposed data:
Sub TransposeData()
'
' TransposeData Macro
'
'
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets.Add After:=Sheets(Sheets.Count)
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=True
End Sub
You need to be at the left upper corner of the data and then run the macro.