I'm working with the following code:
Option Explicit
Sub checkboxfilter()
Dim cb As CheckBox
Dim oWS As Worksheet
Dim oWB As Workbook
Dim oPvt As PivotTable
Dim oPvtField As PivotField
Dim oPvtFilter As PivotFilter
Set cb = oWS("Control").Controls("YTD Filter")
If cb.Value = True Then
For Each oWS In ThisWorkbook.Worksheets
For Each oPvt In oWS
With oPvtField
.CurrentPage.Name = "Yes"
End With
Next oPvt
Next oWS
End If
End Sub
the goal is to toggle each pivot table in the workbook by a yer-to-date filter via checkbox. The code hits a snag under set cb= as an object variable or with not set. What am I missing here to get this control working? I'm also avoiding the use of a slicer.
Thanks.
That kind of control has it's own event and you should use it. Therefore:
go to sheet where you have your checkbox
set Design mode on developer tab on
double click on you check box to ...
...see something like Private Sub CheckBox1_Click()
inside that sub call your subroutine:
Private Sub CheckBox1_Click()
call checkboxfilter
End Sub
I was able to revise based on adjusting the type of format the set cb = as a .Checkboxes and ensuring at each pivot fielt was accurately called as #KazimierzJawor pointed out. Additionally with this type the value needed to be a 0 or 1 rather than True or False. Corrected and final code below.
Private Sub checkboxfilter()
Dim cb As CheckBox
Dim oWS As Worksheet
Dim oWB As Workbook
Dim oPvt As PivotTable
Dim oPvtField As PivotField
Dim oPvtFilter As PivotFilter
Set cb = Sheets("Control").CheckBoxes("YTD Filter")
If cb.Value = 1 Then
For Each oWS In ThisWorkbook.Worksheets
For Each oPvt In oWS.PivotTables
With oPvt.PivotFields("YTD?")
.CurrentPage = "Yes"
End With
Next oPvt
Next oWS
Else
For Each oWS In ThisWorkbook.Worksheets
For Each oPvt In oWS.PivotTables
With oPvt.PivotFields("YTD?")
.CurrentPage = "(All)"
End With
Next oPvt
Next oWS
End If
End Sub
Sub PivotFilter()
Dim pvtF As PivotField
Dim pvtI As PivotItem
Dim StartDate As Date
Dim EndDate As Date
Dim pvtIVal As String
StartDate = DateValue("Jan 1, 2018")
EndDate = Application.WorksheetFunction.EoMonth(Date, 0)
ActiveSheet.PivotTables("PivotTable1").PivotFields("Create Month").ClearAllFilters
Set pvtF = ActiveSheet.PivotTables("PivotTable1").PivotFields("Create Month")
For Each pvtI In pvtF.PivotItems
If (pvtI <> "(blank)") Then
If DateValue(pvtI) >= StartDate And DateValue(pvtI) <= EndDate Then
pvtI.Visible = True
Else
pvtI.Visible = False
End If
Else
pvtI.Visible = False
End If
Next pvtI
End Sub
Related
I keep getting an error:
Run-time error '91; Object variable or with block variable not set.
My script runs fine and does what it needs to do but I can't figure out how to get rid of this error.
Thank you for the help.
Public Sub CommandButton1_Click()
Dim rng As Range
Set rng = Range("F24:I24")
rng.Select
If TextBox1.Text = "" Then
MsgBox ("Must insert Temperature you dingus!")
Else
rng = TextBox1.Text
Call GetCabinet1
End If
Unload Me
End Sub
Public Sub UserForm_Initialize()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
Set ws = Sheets("Executive Summary")
wb.Activate
ws.Select
UserForm1.Show
Unload Me
End Sub
remove all those Unload.Me from both your subs and place it in the sub calling that userform
place a Me.Hide by the end of CommandButton1_Click(), instead
finally remove UserForm1.Show from UserForm_Initialize since it'd make it repeat twice
so your "Main" sub would look like:
Sub main()
Dim UF As UserForm1
Set UF = New UserForm1
UF.Show
Unload UF ' unload the userform from here
End Sub
and your userform1 code like:
Private Sub CommandButton1_Click()
Dim rng As Range
Set rng = Range("F24:I24")
rng.Select
If TextBox1.Text = "" Then
MsgBox ("Must insert Temperature you dingus!")
Else
rng = TextBox1.Text
Call GetCabinet1
End If
Me.Hide
End Sub
Public Sub UserForm_Initialize()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
Set ws = Sheets("Executive Summary")
wb.Activate
ws.Select
End Sub
Simply replacing the unload me with me.hide fixed my problem... Thank you to all of those who gave their input....
I have created a Workbook that is used in various different computers.
Sometimes I add features to it and I would like to easily update it.
The idea is whenever I have a new version of it, I take it to a new computer, save in a temp file and copy the sheets where the data is stored.
Based on the answers I have edit my first draft to: (I didn't know that both workbooks needed to be opened at the same time)
Private Sub CommandButton1_Click()
Dim sh As Worksheet
Dim ws As Worksheet
Dim wb As Workbook
Dim wn As Workbook
Set wn = Workbooks("Reception")
Set wb = Workbooks("Reception2")
With wb
.Sheets("Pass").Range("A1") = "flh"
For Each ws In .Worksheets
Select Case .Name
Case "Formularios", "Coordenador", "LookupList", "Pass"
'Do nothing
Case Else
ws.Delete
End Select
Next ws
End With
With wn
For Each sh In .Worksheets
Select Case .Name
Case "Formularios", "Coordenador", "LookupList", "Pass"
'Do nothing
Case Else
sh.Copy After:=wb.Sheets(wb.Sheets.Count)
End Select
Next sh
End With
End Sub
Case at moment is not working and macro deletes every sheet no matter the name
Thank you all for the feedback
You can find the temp folder by using Environ("temp"), but from your code I'm not sure this is the folder you're using.
This code has a couple of functions to check if the workbook exists and is already open. One other bit of code I'd add is to disable any code in Reception.xlsm from firing when it's opened.
Public Sub MyProcedure()
Dim ws As Worksheet
Dim wb As Workbook
Dim wn As Workbook
Dim Rec1Path As String
Dim Rec2Path As String
Rec1Path = "c:\save\Reception.xlsm"
Rec2Path = "c:\temp\Reception2.xlsm"
'Open or set a reference to Reception.xlsm.
If WorkBookExists(Rec1Path) Then
If WorkBookIsOpen(Rec1Path) Then
'Don't need path for open workbook, just name.
'InStrRev finds last occurrence of "\" (same as InStr, but in Reverse).
Set wn = Workbooks(Mid(Rec1Path, InStrRev(Rec1Path, "\") + 1))
Else
Set wn = Workbooks.Open(Rec1Path)
End If
End If
'Open or set a reference to Reception2.xlsm.
If WorkBookExists(Rec2Path) Then
If WorkBookIsOpen(Rec2Path) Then
Set wb = Workbooks(Mid(Rec2Path, InStrRev(Rec2Path, "\") + 1))
Else
Set wb = Workbooks.Open(Rec2Path)
End If
End If
With wb
.Worksheets("Pass").Range("A1") = "flh"
For Each ws In .Worksheets
Select Case .Name
Case "Formularios", "Coordenador", "LookupList", "Pass"
'Do nothing
Case Else
'You don't really need the count of worksheets if you can guarantee
'you're not going to try and delete the last remaining sheet.
If .Worksheets.Count > 1 Then
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
End Select
Next ws
End With
With wn
'Re-using the ws variable.
For Each ws In .Worksheets
Select Case .Name
Case "Formularios", "Coordenador", "LookupList", "Pass"
'Do nothing
Case Else
ws.Copy After:=wb.Sheets(wb.Sheets.Count)
End Select
Next ws
End With
End Sub
Public Function WorkBookExists(sPath As String) As Boolean
WorkBookExists = Dir(sPath) <> ""
End Function
Public Function WorkBookIsOpen(FullFilePath As String) As Boolean
Dim ff As Long
On Error Resume Next
ff = FreeFile()
Open FullFilePath For Input Lock Read As #ff
Close ff
WorkBookIsOpen = (Err.Number <> 0)
On Error GoTo 0
End Function
Is the workbook open when you try to 'SET' it? If not you will need to open it as such:
Dim wb As Workbook
Set wb = Workbooks.Open("c:\temp\Reception.xlsm")
With some more googling I was able to craft the code that I wanted in the end.
Here is the answer for the curious or for other people looking to do the same:
Private Sub CommandButton1_Click()
Dim sh As Worksheet
Dim ws As Worksheet
Dim LastRow As Long
Dim LastCol As Long
Dim j As Long
Dim Rng As Range
Dim wb As Workbook
Dim wn As Workbook
Set wn = Workbooks("Reception")
Set wb = Workbooks("Reception2")
With wb
.Sheets("Pass").Range("A1") = "flh"
For Each ws In .Worksheets
Select Case ws.Name
Case "Formularios"
'Do nothing
Case "Coordenador"
'Do nothing
Case "LookupList"
'Do nothing
Case "Pass"
'Do nothing
Case Else
With ws
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
Set Rng = .Range(.Cells(2, 1), .Cells(LastRow, LastCol))
Rng.ClearContents
End With
End Select
Next ws
End With
With wn
For Each sh In .Worksheets
Select Case sh.Name
Case "Formularios"
'Do nothing
Case "Coordenador"
'Do nothing
Case "LookupList"
'Do nothing
Case "Pass"
'Do nothing
Case Else
For j = 1 To wb.Sheets.Count
If sh.Name = wb.Worksheets(j).Name Then
On Error Resume Next
sh.Range("A:J").Copy wb.Worksheets(j).Range("A1")
End If
Next j
End Select
Next sh
End With
Application.CutCopyMode = False
End Sub
Thanks to #Darren Bartrup-Cook for the help.
in WB1, I use the code above to display the opened workbook names in the Lisbox1 and their respective worksheets in listbox2 using a User form. But I would like to use Listview1 and Listview2 instead because I would like for every workbook and Worksheet name to show beside each one of them a checkbox, What changes should I do so it works in Listview1 and Listview2.
Option Explicit
Private Sub UserForm_Initialize()
Dim wb As Workbook
Me.Caption = "Workbooks and Sheets Detail"
For Each wb In Application.Workbooks
ListBox1.AddItem wb.Name
Next wb
End Sub
Private Sub ListBox1_Click()
Dim sWorkbookname As String
sWorkbookname = ListBox1.List(ListBox1.ListIndex)
ListWbWorksheets sWorkbookname
End Sub
Private Sub ListWbWorksheets(ByVal psWorkbookName As String)
Dim targetWb As Excel.Workbook
Dim n As Long
Set targetWb = Application.Workbooks(psWorkbookName)
ListBox2.Clear
For n = 1 To targetWb.Sheets.Count
ListBox2.AddItem targetWb.Sheets(n).Name
Next n
Set targetWb = Nothing
End Sub
It'll take some trial and error to learn how to use a Listview. This should give you a good start.
Private Sub ListView1_Click()
Dim ws As Worksheet
Dim item As ComctlLib.ListItem
ListView2.ListItems.Clear
For Each ws In Workbooks(ListView1.SelectedItem.Text).Worksheets
Set item = ListView2.ListItems.Add(Text:=ws.Name)
Next
End Sub
Private Sub UserForm_Initialize()
Dim wb As Workbook
Dim item As ComctlLib.ListItem
With ListView1
.View = lvwReport
.MultiSelect = False
.ColumnHeaders.Add Text:="Workbooks"
.ColumnHeaders.Add Text:="Paths"
End With
With ListView2
.View = lvwReport
.MultiSelect = False
.ColumnHeaders.Add Text:="Worksheets"
End With
For Each wb In Workbooks
Set item = ListView1.ListItems.Add(Text:=wb.Name)
item.SubItems(1) = wb.Path
Next
End Sub
Code Page 2Code Page 1I am trying to open the sheet with listbox selection. The code is as under. But it is showing an error. I am new to vba. Plz help
Public Sub AddData_Click()
Dim iRow As Long
Dim ws As Worksheet
Dim Sht As String
Sht.Text = ListBox1.SelectedItem.Tostring()
Worksheets(CStr(Sht)).Activate
Try this
Private Sub AddData_Click()
Dim i As Integer
Dim sht As String
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) Then
sht = ListBox1.List(i)
End If
Next i
If sht = "" Then
MsgBox "You didn't select an item in the listbox.", vbExclamation
Exit Sub
Else
Worksheets(sht).Activate
End If
End Sub
you could try this:
Private Sub AddData_Click()
With Me.ListBox1
If .ListIndex = -1 Then
MsgBox "No item selected!"
Else
Worksheets(.Value).Activate
End If
End With
End Sub
I want to Export large data stock from Access to Excel. I'm doing that with a form.
My code with "DoCmd.TransferSpreadsheet acExport..." works normally, but the program breaks off because of the large data stock.
Perhaps with queries I can solve this Problem, or what do you think?
I am thankful for each tip! =)
you can you use below code: this will copy the datesheet view in your form and copy paste it in to one excel file .For this you just drag one sub form control from tool box in to your form and set the property of this sub form's source data as your query name and replace the sub form name in the code
Private Sub Command48_Click()
On Error GoTo Command13_Click_Err
Me.subformName.SetFocus
'DoCmd.GoToControl "Policy Ref"
DoCmd.RunCommand acCmdSelectAllRecords
DoCmd.RunCommand acCmdCopy
Dim xlapp As Excel.Application
Set xlapp = CreateObject("Excel.Application")
With xlapp
.Workbooks.Add
.ActiveSheet.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:= _
False
.Cells.Select
.Cells.EntireColumn.AutoFit
.Visible = True
.Range("a1").Select
End With
Command13_Click_Exit:
Exit Sub
Command13_Click_Err:
MsgBox Error$
Resume Command13_Click_Exit
End sub
'=======================
you can you use below code: this will copy the datesheet view in your form and copy paste it in to one excel file .For this you just drag one sub form control from tool box in to your form and set the property of this sub form's source data as your query name and replace the sub form name in the code
Private Sub Command48_Click()
On Error GoTo Command13_Click_Err
Me.subformName.SetFocus
'DoCmd.GoToControl "Policy Ref"
DoCmd.RunCommand acCmdSelectAllRecords
DoCmd.RunCommand acCmdCopy
Dim xlapp As Excel.Application
Set xlapp = CreateObject("Excel.Application")
With xlapp
.Workbooks.Add
.ActiveSheet.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:= _
False
.Cells.Select
.Cells.EntireColumn.AutoFit
.Visible = True
.Range("a1").Select
End With
Command13_Click_Exit:
Exit Sub
Command13_Click_Err:
MsgBox Error$
Resume Command13_Click_Exit
End sub
'''PPT
Sub pptExoprort()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationAutomatic
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim PPApp As PowerPoint.Application
Dim PPPres As PowerPoint.Presentation
Dim slideNum As Integer
Dim chartName As String
Dim tableName As String
Dim PPTCount As Integer
Dim PPSlideCount As Long
Dim oPPTShape As PowerPoint.Shape
Dim ShpNm As String
Dim ShtNm As String
Dim NewSlide As String
Dim myChart As PowerPoint.Chart
Dim wb As Workbook
Dim rngOp As Range
Dim ro As Range
Dim p As Integer
Dim v, v1, v2, v3, Vtot, VcaGr
Dim ws As Worksheet
Dim ch
Dim w As Worksheet
Dim x, pArr
Dim rN As String
Dim rt As String
Dim ax
Dim yTbN As String
'Call InitializeGlobal
''start year offset
prodSel = shtSet.Range("rSelProd")
x = shtSet.Range("rngMap").Value
pArr = fretPrVal(x, prodSel)
TY = 11 'number of years in chart
ThisWorkbook.Activate
Set w = ActiveSheet
Set PPApp = GetObject("", "Powerpoint.Application") '******************
PPTCount = PPApp.Presentations.Count
If PPTCount = 0 Then
MsgBox ("Please open a PPT to export the Charts!")
Exit Sub
End If
Set PPPres = PPApp.ActivePresentation '******************
For j = 0 To UBound(pArr)
If j = 0 Then
rN = "janport"
slideNum = 3
yTbN = "runport"
Else
rN = "janprod" & j
slideNum = 3 + j
yTbN = "runprod" & j
End If
chartName = "chtSalesPort"
Set PPSlide = PPPres.Slides(slideNum) '**************
PPApp.ActiveWindow.View.GotoSlide PPSlide.SlideIndex
Set myChart = PPSlide.Shapes(chartName).Chart '******************
myChart.ChartData.Activate '********************
Set wb = myChart.ChartData.Workbook '***********
Set ws = wb.Worksheets(1) '**************
Set rngOp = w.Range(rN).Offset(0, 1).Resize(12, 6)
Set ro = rngOp
' v1 = ro.Offset(1, 22).Resize(Lc, 1)
'ws.ListObjects("Table1").Resize Range("$A$1:$B$" & Ty + 1)
'ws.ListObjects("Table1").Resize Range("$A$1:$" & Chr(Lc + 1 + 64) & "$" & Ty + 1)
ws.Range("B2:g13").ClearContents '***********
rngOp.Copy '**********
ws.Range("B2:g13").PasteSpecial xlPasteValues '******************
End Sub
Sub Picture62_Click()
Dim charNamel As String
Dim leftm As Integer
Dim toptm As Integer
charNamel = "Chart 1"
leftm = 35
toptm = 180
Call chartposition(leftm, toptm, charNamel)
End Sub
Sub chartposition(leftm, toptm, charNamel)
ActiveSheet.ChartObjects(charNamel).Activate
'First we declare the variables we will be using
Dim newPowerPoint As PowerPoint.Application
Dim activeSlide As PowerPoint.Slide
Dim cht As Excel.ChartObject
Dim activslidenumber As Integer
'Look for existing instance
On Error Resume Next
Set newPowerPoint = GetObject(, "PowerPoint.Application")
On Error GoTo 0
'Let's create a new PowerPoint
If newPowerPoint Is Nothing Then
Set newPowerPoint = New PowerPoint.Application
End If
'Make a presentation in PowerPoint
' If newPowerPoint.Presentations.Count = 0 Then
' newPowerPoint.Presentations.Add
' End If
'Show the PowerPoint
newPowerPoint.Visible = True
On Error GoTo endd:
activslidenumber = Str(GetActiveSlide(newPowerPoint.ActiveWindow).SlideIndex)
Set activeSlide = newPowerPoint.ActivePresentation.Slides(activslidenumber)
ActiveChart.ChartArea.Copy
On Error GoTo endddd:
activeSlide.Shapes.PasteSpecial(DataType:=ppPasteDefault).Select
'activeSlide.Shapes.PasteSpecial(DataType:=ppPasteMetafilePicture).Select
'activeSlide.Shapes.PasteSpecial(DataType:=ppPasteOLEObject, DisplayAsIcon:=msoFalse).Select
endddd:
newPowerPoint.ActiveWindow.Selection.ShapeRange.Left = leftm
newPowerPoint.ActiveWindow.Selection.ShapeRange.Top = toptm
GoTo enddddd:
endd:
MsgBox ("Please keep your PPT file opened")
enddddd:
End Sub