Referencing other sheets in loop not working - excel

Hoping someone can help me figure out what's missing from my code. I have a validation list on one sheet, and I'm attempting to loop that list on a different sheet and change the filter on pivot table on that different sheet. The loop works through the validation list if I run the macro on the sheet with that validation cell, but on the sheet with my pivot table it only loops through the cells on that sheet. Consequently, if I'm on the sheet with the validation list, the loop works correctly through that validation list, but the pivot table filter doesn't change. I'm sure I'm missing something simple but I can't figure out what it is. Thanks in advance.
Sub Addvalidationlist() ' there's no problems with this macro, not the most elegant code but it works
Dim wb As Workbook
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim lastline As Long, newlastline As Long
Dim rng As Range
Dim rng2 As Range
Dim rng3 As Range
Set wb = ThisWorkbook
Set sh1 = wb.Sheets("qry_FB_forecast_file_NEW")
With sh1
lastline = sh1.Range("A" & Rows.Count).End(xlUp).Row
Set rng = sh1.Range("H1:H" & lastline)
rng.Copy Range("X:X")
sh1.Range("X:X").RemoveDuplicates Columns:=1, Header:=xlYes
newlastline = sh1.Range("X" & Rows.Count).End(xlUp).Row
Set rng2 = sh1.Range("X2:X" & newlastline)
Set rng3 = sh1.Range("Y1")
With rng3.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Formula1:="='" & sh1.Name & "'!" & rng2.Address
End With
End With
' end of validation list sub
**Public Sub exportbybrand()** *This is the one I'm having trouble with *
Dim wb As Workbook
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim lastline As Long, newlastline As Long
Dim rng As Range
Dim rng2 As Range
Dim rng3 As Range
Dim valcell As Range
Dim valcellsource As Range
Dim Family As String
Set wb = ThisWorkbook
Set sh1 = wb.Worksheets("qry_FB_forecast_file_NEW")
Set valcell = ThisWorkbook.Worksheets("qry_FB_forecast_file_NEW").Range("Y1")
Set valcellsource = Evaluate(valcell.Validation.Formula1)
Set sh2 = wb.Worksheets("MR Front Edit")
On Error Resume Next
With sh1
For Each valcell In valcellsource
valcell.Value = valcell.Value
Family = valcell
MsgBox Family
With sh2
sh1.PivotTables("PivotTable1") _
.PivotFields("FamilyId").CurrentPage = Family
End With
Next
End With
End Sub

Related

Trying to get Macro to automatically adjust DataRange for Pivot Table

I'm sorry if this is basic but I can't seem to figure this out .
Long story short my file has several tabs with lot's of data and each tab has a pivot table. What I need is a Macro that adjusts the data range of the Pivot table to the data in current sheet. I have it now set with a bigger range giving me Blanks which drives me nuts.
Here is my code :
Dim Data_Sheet As Worksheet
Dim Pivot_Sheet As Worksheet
Dim StartPoint As Range
Dim DataRange As Range
Dim PivotName As String
Dim NewRange As String
Dim LastCol As Long
Dim lastRow As Long
'Set Pivot Table & Source Worksheet
Set Data_Sheet = ThisWorkbook.Worksheets("1")
Set Pivot_Sheet = ThisWorkbook.Worksheets("1")
'Enter in Pivot Table Name
PivotName = "PivotTable1"
'Defining Staring Point & Dynamic Range
Data_Sheet.Activate
Set StartPoint = Data_Sheet.Range("V2")
LastCol = StartPoint.End(xlToRight).Column
DownCell = StartPoint.End(xlDown).Row
Set DataRange = Data_Sheet.Range(StartPoint, Cells(DownCell, LastCol))
NewRange = Data_Sheet.Name & "!" & DataRange.Address(ReferenceStyle:=xlR1C1)
ActiveSheet.PivotTables("PivotTable1").ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:=NewRange _
, Version:=6)
Now when I try this I get the "Run time error -2147024809" error stating that The pivottable name is invalid .
This updates all the sheets that have 1 pivot table
Sub Update()
Dim wb As Workbook, ws As Worksheet
Dim rng As Range, cell As Range, newrange As String
Set wb = ActiveWorkbook
For Each ws In wb.Sheets
With ws
If .PivotTables.Count = 1 Then
Set cell = .Range("V2").End(xlToRight).End(xlDown)
Set rng = .Range("V2", cell)
newrange = "'" & ws.Name & "'!" & rng.Address(ReferenceStyle:=xlR1C1)
.PivotTables(1).ChangePivotCache _
wb.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:=newrange, Version:=6)
End If
End With
Next
End Sub

Filter Workbook Column based on data found in another Workbook

I have two Workbooks and I’m trying to filter “Wbk2” Column A based on the data found in Column C of “Wbk1” There are a few hundred cells in “Wbk1”Column C that I’m trying to match up with “Wbk2” Column A and filter based on that.
It works just fine when you set to a single cell. I’m trying to add the entire column as a filter and cannot seem to get it to filter based on that criteria.
sub filter()
Dim Wbk1 As Workbook
Dim Wbk2 As Worksheet
Dim Wksht As Worksheet
Dim Filter As Range
Set Wbk1 = Workbooks(“DataToUseForFiltering.xlsm”)
Set Wksht = Wbk1.Worksheets(“Sheet1”)
Set Wbk2 = ActiveSheet
With Wksht
Set Filter = .Range(“C2”)
End With
With Wbk2
With .Range("A1:Z1" & Cells(.Rows.Count, "A").End(xlUp).Row)
.AutoFilter
.AutoFilter Field:=1, Criterial:=Filter
End With
End With
End Sub
Code builds on my earlier comments and has been tested.
Option Explicit
Sub NewFilter()
Dim Wbk1 As Workbook
Dim Wksht1 As Worksheet
Dim Wksht2 As Worksheet
Dim rngFilter As Range
Dim aryFilter()
Dim i As Long
Set Wbk1 = Workbooks("DataToUseForFiltering.xlsm")
Set Wksht1 = Wbk1.Worksheets("Sheet1")
Set Wksht2 = ActiveSheet
With Wksht1
Set rngFilter = .Range("C2:C" & .UsedRange.Rows.Count)
End With
ReDim aryFilter(1 To rngFilter.Cells.Count)
For i = 1 To rngFilter.Cells.Count
aryFilter(i) = rngFilter.Cells(i).Value
Next i
Wksht2.Rows(1).AutoFilter _
Field:=1, _
Criteria1:=aryFilter, _
Operator:=xlFilterValues
End Sub

VBA Copy value to another worksheet with autofilter

I want to copy the value from current sheet to another workbooks with auto filter by creating new one, once I run the code I got the error:
Object variable or with block variable not set
Here's the code:
Sub copyvaluetoanothersheet()
Dim selectrange As Range
Dim wb As Workbook
Dim Dsheet As Worksheet
Dim Lastrow As Long
Application.ScreenUpdating = False
Set wb = Workbooks.Add
Set Dsheet = wb.Worksheets(1)
Lastrow = Sheet2.Range("A" & Rows.Count).End(xlUp).Row
selectrange = Sheet2.Range("A2:BP" & Lastrow)
With Worksheets("Production data")
.AutoFilterMode = False
selectrange.AutoFilter field:="Branch", Criteria1:="Direct Response"
selectrange.SpecialCells(xlCellTypeVisible).EntireRow.Copy
End With
Dsheet.PasteSpecial xlPasteValues
Application.ScreenUpdating = True
End Sub
Many thanks
You must use Set when assigning object variables (you've done it elsewhere).
Set selectrange = Sheet2.Range("A2:BP" & Lastrow)
Note too that your mixture of sheet code names, tab names, and indexes is confusing, and that your code will error if nothing is visible.
Try following
Sub cpVisible()
Dim MyProdName As String
Dim FilteredRange As Range
Dim myArr As Variant
Sheets("Production Data").Range("$A$2:$BP$50000").AutoFilter Field:="Branch", Criteria1:="Direct Response"
Set FilteredRange = Sheets("Production Data").Range("$A$2:$BP$50000").SpecialCells(xlCellTypeVisible)
FilteredRange.Copy Sheets("Dsheet").Range("A1")
End Sub

Paste from advanced filter

I am stuck on a line and don´t know how to solve the error. I´m dividing the lines in a list by filtering different names with an advanced filter and copying the data in individual sheets, but got stuck on a line, the last one before the Next: "newWS.Range("A1").Paste". I get error 1004 from debugging:
Private Sub loopfilter()
Dim thisWB As Workbook
Dim filterws As Worksheet
Dim howto As Worksheet
Dim advfilter As Range
Dim Postenws As Worksheet
Dim VersandRange As Range
Dim rng As Range
Dim Name As String
Set thisWB = ThisWorkbook
Set filterws = thisWB.Sheets("Filtro")
Set howto = thisWB.Sheets("How to")
Set advfilter = filterws.Range("A1:AK2")
Set Postenws = thisWB.Sheets("Alle gemahnten Posten (2)")
Set VersandRange = howto.Range("J2", Cells(Rows.Count, "j").End(xlUp))
Dim newWS As Worksheet
For Each rng In VersandRange
filterws.Range("AK2") = rng.Value
Application.CutCopyMode = False
Postenws.Range("A1").CurrentRegion.AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=advfilter, _
CopyToRange:=filterws.Range("A5"), _
Unique:=False
filterws.Range("a5").CurrentRegion.Copy
Set newWS = thisWB.Sheets.Add
newWS.Name = rng.Value
newWS.Range("A1").Paste
Next
End Sub
Any idea why its not working?
Thanks
Try this (also made a sheet reference to your definition of Versandrange). Paste is not a method of the range object.
Private Sub loopfilter()
Dim thisWB As Workbook
Dim filterws As Worksheet
Dim howto As Worksheet
Dim advfilter As Range
Dim Postenws As Worksheet
Dim VersandRange As Range
Dim rng As Range
Dim Name As String
Set thisWB = ThisWorkbook
Set filterws = thisWB.Sheets("Filtro")
Set howto = thisWB.Sheets("How to")
Set advfilter = filterws.Range("A1:AK2")
Set Postenws = thisWB.Sheets("Alle gemahnten Posten (2)")
Set VersandRange = howto.Range("J2", howto.Cells(Rows.Count, "j").End(xlUp))
Dim newWS As Worksheet
For Each rng In VersandRange
filterws.Range("AK2").value = rng.Value
Application.CutCopyMode = False
Postenws.Range("A1").CurrentRegion.AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=advfilter, _
CopyToRange:=filterws.Range("A5"), _
Unique:=False
Set newWS = thisWB.Sheets.Add
newWS.Name = rng.Value
filterws.Range("a5").CurrentRegion.Copy newWS.Range("A1")
filterws.Range("a5").CurrentRegion.clearcontents
Next
End Sub

VBA-Excel -- Variable in Cells.Find

I have two spreadsheets (wb1 and wb2). The goal is to select each value in column D of wb1, find the value in column C of wb2, then copy a range of cells (same row as the search value) back to wb1.
Here's the code I've managed to pull together thus far:
Dim rng1 As Range, rng2 As Range
Dim cell as Variant
Dim cell_val as String
Dim wb1 as Workbook, wb2 as Workbook
Dim sh1 as Worksheet, sh2 as Worksheet
Sub Find_Copy_Paste()
set wb1 = Workbooks.Open("c:\explicit\path\to\wb1.xlsm") <---This fails
set wb2 = Workbooks.Open("c:\explicit\path\to\wb2.xlsm") <---This fails
Set sh1 = wb1.Open("Inventory")
set sh2 = wb2.Open ("Sheet1")
set rng1 = wb1.sh1.Range("D6:D1702")
set rng2 = wb2.sh2.Range("C2:C3132")
For Each cell In rng1
ActiveCell.Select
cell_val = Selection.Copy
Windows(wb2).Activate
Cells.Find(What:=(cell_val), After:=ActiveCell,
LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows,
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Offset (0,1).Range("A1:AH1").Select
Application.CutCopyMode = False
Selection.Copy
Windows(wb1).Activate
ActiveCell.Offset(0,1).Range("A1").Select
ActiveSheet.Paste
cell_val=""
Next
End Sub
Unfortunately, I'm hitting a challenge, and I suspect it has to do with two things: 1) wb1 and wb2 variables and how I've assigned them, and 2) the variable in the Cells.Find part of my code (but I'm still fairly new to VBA, so my suspicions might be way off).
Try this below, I have simulated your goal with only 1 workbook. If the macro & path is not trusted, you may have issue opening the xlsm files. Here I only have one of them in ReadOnly mode (Workbook 2).
Sub Find_Copy_Paste()
Dim wb1 As Workbook, wb2 As Workbook
Dim sh1 As Worksheet, sh2 As Worksheet
Dim rng1 As Range, rng2 As Range
Dim cell As Range, FoundCells As Range
Set wb1 = Workbooks.Open(Filename:="c:\explicit\path\to\wb1.xlsm",ReadOnly:=False)
Set wb2 = Workbooks.Open(Filename:="c:\explicit\path\to\wb2.xlsm",ReadOnly:=True)
Set sh1 = wb1.Worksheets("Inventory")
Set sh2 = wb2.Worksheets("Sheet1")
Set rng1 = sh1.Range("D6:D1702")
Set rng2 = sh2.Range("C2:C3132")
For Each cell In rng1
If Not IsEmpty(cell) Then
Set FoundCells = rng2.Find(cell.Value)
If Not FoundCells Is Nothing Then
Debug.Print """" & cell.Value & """ found at " & FoundCell.Worksheet.Name & "!" & FoundCell.Address
' Copy Found cell to one column on right of cell being searched for
FoundCells.Copy Destination:=cell.Offset(0, 1)
End If
End If
Next
Set rng1 = Nothing
Set rng2 = Nothing
Set sh1 = Nothing
Set sh2 = Nothing
Set wb1 = Nothing
Set wb2 = Nothing
End Sub
There are many good place to start learning VBA, for Excel 2010, check out the Excel Developer Reference.

Resources