vlookup in VBA using selection.currentregion in another sheet - excel

i'm new to both macros and vba
I have a pivot table in sheet FR Pivot and a table in sheet Final. I want to pick up the pivot table data and use vlookup to fill in values in my table in the Final sheet. The issue is that the pivot table can be dynamic. So I'm trying the following:
Dim Range1 As Range
With Sheets("FR Pivot")
'Select cell - You can change as per your requirement
.Range("E4").Select
'Selects the current region
Selection.CurrentRegion.Select
Set Range1 = Selection
End With
Sheets("Final").Select
Range("J7").Select
ActiveCell.FormulaR1C1 = _
"=IFNA(VLOOKUP([#[Row Labels]],Range1,2,0),""NA"")"
I think I'm going wrong with the named range part but unable to figure out how to fix it. For the macro, I'm recording my actions and then modifying code to make it dynamic which is why there are so many selects.

Without any selections:
Dim addr
addr = Sheets("FR Pivot").Range("E4").Currentregion.Address()
Sheets("Final").Range("J7").Formula = _
"=IFNA(VLOOKUP([#[Row Labels]], 'FR Pivot'!" & addr & ",2,0),""NA"")"

Related

Is it possible to directly reference the Source Data of a Pivot Table?

I have a large table of data on Sheet1 and a pivot table on Sheet2 that is based on Sheet1. I would like to be able to jump from a selected PivotItem on Sheet2 directly to the cell on Sheet1 that the data is from. So far I just use
EID = ActiveCell.PivotTable.PivotFields(1).DataRange.Cells(ActiveCell.PivotCell.PivotRowLine.Position, 1).Text
Set rTarget = Sheet1.Columns(1).Find(EID, lookat:=xlWhole, MatchCase:=True)
Sheet1.activate
rTarget.activate
Which is a little messy because my current strategy to locate the data is the unique identifier in PivotFields(1) but I want to allow the user to select any cell along the Row. So I have to reference the cell address in PivotFields(1) in the same row and then search for it in Sheet1.
I would prefer to avoid using Cells.Find and was wondering if there was a method or property that might allow me to do something like:
set rTarget = Activecell.PivotItem.SourceDataRange
Where SourceDataRange would return the Range of the cell in Sheet1 that is supplying the data for the pivotitem. PivotTable.SourceData returns the entire range. I am looking for the range of an individual pivotitem.
Does such a method exist?

Copy a range of cells from one worksheet to another using VBA

I'm new to using VBA and need to copy data from a range of cells on one worksheet to another worksheet. I need to copy a column of cells and paste it into a row of cells e.g. A1:A4 to A1:D1. This is the code i'm using but it doesn't work the way i need it too.
Sub Draft()
Worksheets("Material Check").Range("B3:B6").Copy _
Destination:=Worksheets("Archive").Range("A2:D2")
End Sub
Also I need the data thats being copied over to be added to the bottom of the table on the archive sheets and i'm not sure how to do this.
Without Excel Tables
This is a bit of an odd way to do it but if you have a lot of cells to do, it's possibly faster than copy/paste special:
ThisWorkbook.Worksheets("Archive").Range("A2:D2").Formula = "=INDEX('Material Check'!$B$3:$B$6,Column())"
ThisWorkbook.Worksheets("Archive").Range("A2:D2").Value = ThisWorkbook.Worksheets("Archive").Range("A2:D2").Value
The first line populates the destination range with a formula that pulls the data from the source, using INDEX/COLUMN to transpose the result.
The second line simply converts the formula to hard values.
EDIT - Solution to copy the values to the bottom of the list
Using Excel Table
To do this you will need to go to "Insert" --> "Table".
''Get a reference to your destination table
Dim Tbl1 As ListObject
Set Tbl1 = ThisWorkbook.Sheets("Archive").ListObjects("Table1") ''Change these to your destination sheet/table names
''add a new row to the table
Dim Newrow As ListRow
Set Newrow = Tbl1.ListRows.Add
''populate the new row
With Newrow
.Range(Tbl1.ListColumns("Column1").Index) = ThisWorkbook.Worksheets("Material Check").Range("B3") ''change these to your destination column name and your source sheet/ranges
.Range(Tbl1.ListColumns("Column2").Index) = ThisWorkbook.Worksheets("Material Check").Range("B4")
.Range(Tbl1.ListColumns("Column3").Index) = ThisWorkbook.Worksheets("Material Check").Range("B5")
.Range(Tbl1.ListColumns("Column4").Index) = ThisWorkbook.Worksheets("Material Check").Range("B6")
End With

VBA how to copy to second last cell in table?

I have a pivot table with data, I need to copy and past all of the data except for the last row, which I need to delete as it is a sum of totals. The amount of data entries vary by week so I cannot just put the set numbers in. Currently my code looks like this;
Worksheets("Mobile Summary").Range("A4:F482").Copy
Worksheets("Sheet1").Range("A1:F479")
However I need to copy and paste more data from a different pivot table directly under this. Therefore I couldn't just set the rows to 3000 for example. I know there is a code to find the last row, although I'm coming up short as to how to go about solving this problem.
To find a pivot table by its name and remove the last row of the table use the Range.Resize property. This is useful if there is more than one pivot table on a worksheet.
Option Explicit
Sub CopyPivotTableWithoutLastRow()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Tabelle3")
Dim i As Long
For i = 1 To ws.PivotTables.Count 'loop throug all pivot tables
If ws.PivotTables(i).name = "PivotTable1" Then 'determine pivot table by its name
With ws.PivotTables(i).TableRange1 '= full table
.Resize(RowSize:=.Rows.Count - 1).Copy 'resize to remove last row then copy
End With
End If
Next i
End Sub

How to count multiple values in one single cell using Pivot Tables in Excel?

I have this table in a Excel sheet:
I would like to create a Pivot Table to have this outcome:
Do you have any idea how to do it?
If you're okay with using helper columns, use text to columns to split up your third column into individual columns by using commas as the delimiter. Get everything in one column and then create your pivot table on the resulting data.
EDIT:
Select C2:C5 and go to the data tab and select "Text to Columns" bringing up a dialogue box. Choose delimited and then check the comma box on the next screen as well as the space option to get rid of the spaces and hit finish. You should have each item in its own cell.
Next, we need to get everything in one column. There's not a great way to do this without VBA (VBA is required if you have a lot of data) but what you can do for smaller data sets is copy the entire row, right click at the top of an empty column, choose Paste Special and check the Transpose option. This will take the row of data that you copied and paste it in the destination as a column, or vice versa if you copied a column. Repeat for all rows of data until you have one nice column of all the fruits (including duplicates).
It sounded like you have a grasp of pivot tables so I won't go into detail on that, but I can if you need me to.
EDIT2:
Here's a link to some options for converting tables to one column other than copy and paste. I'd recommend using the following code:
Sub ConvertRangeToColumn()
'Updateby20131126
Dim Range1 As Range, Range2 As Range, Rng As Range
Dim rowIndex As Integer
xTitleId = "KutoolsforExcel"
Set Range1 = Application.Selection
Set Range1 = Application.InputBox("Source Ranges:", xTitleId, Range1.Address, Type:=8)
Set Range2 = Application.InputBox("Convert to (single cell):", xTitleId, Type:=8)
rowIndex = 0
Application.ScreenUpdating = False
For Each Rng In Range1.Rows
Rng.Copy
Range2.Offset(rowIndex, 0).PasteSpecial Paste:=xlPasteAll, Transpose:=True
rowIndex = rowIndex + Rng.Columns.Count
Next
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
You can solve this problem even without pivot table. I solved my same problem by this way.
I supposed in second table, "Item" is in A1 and "Count of Table" is in B1;
and first table is in "Sheet1" and second table is in "Sheet2"
You can also add a new column for the amount of fruit which bought by a customer. This is in Sheet1, D1 column.
You can put such a formula under "Count of Item" Column for each row:
(You just write this formula for once and extend to bottom as usual)
=SUMIF(Sheet1!$C$2:$C$5;"*"&A2&"*";Sheet1!$D$2:$D$5).

Specify a specific range in pivot table

This is the macro I got when i recorded for pivot table creation.
ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:= _
"Sheet1!R2C1:R278C35").CreatePivotTable TableDestination:="", TableName:= _
"PivotTable1", DefaultVersion:=xlPivotTableVersion10
These macro creates a new worksheet for pivot table report but i want the pivot table to be created in the specified sheet say
activeworkbook.sheets(2)
I was guessing TableDestionation is the path where you have to give the sheet name for pivot table creation but I dont know how to set the path over there
and I'm also Unable to figure it out how to specify a specific range in the pivot table
SourceData:= "Sheet1!R2C1:R278C35" ' how to specify a range using variables
I have to specify these range
Sheet1.range("A2:AI" & last_row)
here it takes defualt range like these
"Sheet1!R2C1:R278C35"
I'm So confused with the RC notation , Please help me with these Thanks
You can use ConvertFormula, from application, for example
Dim StrAddress As String
StrAddress = "sheet1!" & Application.ConvertFormula(Range("A1:Z300").Address, xlA1, xlR1C1)
Debug.Print StrAddress
In sample range A1:Z300 is converted in R1C1 notation, R is a row and C a column, A1 for example is ROW 1 COLUMN 1 and Z300 is ROW 300 COLUMN 26.
Use StrAddress to create your pivot.

Resources