Filtering based on previous filter - vba

Using this code I have set up I am using Filters which work in correlation with userforms with checkboxes to choose what to filter. Currently if I filter on one variable like Utilities it Filters, but if I move to another filter say Clients and then I filter instead of giving me the clients associated with the specific utility previously filtered it clears everything and filters only on the clients.
I am thinking the solution may have to deal with the Method:
.SpecialCells(xlCellTypeVisible)
Private Sub Cancel_UF_Click()
UtilityFilter.Hide
Range("A1").Select
End Sub
Private Sub Confirm_UF_Click()
ActiveSheet.Unprotect ("UMC626")
ClearFilter
UpdateFilters
UtilityFilter.Hide
Application.ScreenUpdating = False
Range("A1").Select
ActiveSheet.Protect Password:="UMC626", _
DrawingObjects:=False, _
Contents:=True, _
Scenarios:=True
End Sub
Sub SelectAll_UF_Click()
If SelectAll = True Then
Electricty_UF.Value = True
Gas_UF.Value = True
NonUtility_UF.Value = True
SolarElectricity_UF.Value = True
SolarThermal_UF.Value = True
SolidWaste_UF.Value = True
Water_UF.Value = True
Else
Electricity_UF.Value = False
Gas_UF.Value = False
NonUtility_UF.Value = False
SolarElectricity_UF.Value = False
SolarThermal_UF.Value = False
SolidWaste_UF.Value = False
Water_UF.Value = False
End If
End Sub
Sub UpdateFilters()
Integer_UF = -1
If Electricity_UF.Value = True Then
Add_UF String_UF, "E"
Range("E6:E67").AutoFilter Field:=1, _
Criteria1:=String_UF, _
Operator:=xlFilterValues
End If
If Gas_UF.Value = True Then
Add_UF String_UF, "G"
Range("E6:E67").AutoFilter Field:=1, _
Criteria1:=String_UF, _
Operator:=xlFilterValues
End If
If NonUtility_UF.Value = True Then
Add_UF String_UF, "NU"
Range("E6:E67").AutoFilter Field:=1, _
Criteria1:=String_UF, _
Operator:=xlFilterValues
End If
If SolarElectricity_UF.Value = True Then
Add_UF String_UF, "SE"
Range("E6:E67").AutoFilter Field:=1, _
Criteria1:=String_UF, _
Operator:=xlFilterValues
End If
If SolarElectricity_UF.Value = True Then
Add_UF String_UF, "SE"
Range("E6:E67").AutoFilter Field:=1, _
Criteria1:=String_UF, _
Operator:=xlFilterValues
End If
If SolarThermal_UF.Value = True Then
Add_UF String_UF, "ST"
Range("E6:E67").AutoFilter Field:=1, _
Criteria1:=String_UF, _
Operator:=xlFilterValues
End If
If SolidWaste_UF.Value = True Then
Add_UF String_UF, "SW"
Range("E6:E67").AutoFilter Field:=1, _
Criteria1:=String_UF, _
Operator:=xlFilterValues
End If
If Water_UF.Value = True Then
Add_UF String_UF, "W"
Range("E6:E67").AutoFilter Field:=1, _
Criteria1:=String_UF, _
Operator:=xlFilterValues
End If
End Sub
Sub Add_UF(String_UF() As String, NewValue As String)
Integer_UF = Integer_UF + 1
ReDim Preserve String_UF(Integer_UF)
String_UF(Integer_UF) = NewValue
End Sub
I think the focus should be on Add_UF
I am calling a NewValue. Is there anyway to sort a column after it has been sorted? As you can see in the picture below I'd like to beable to sort one colum. Say on Energy then after that sort it on Work Type.

I do not intend to re-write your code but I can provide the information, and methods, that you will need to achieve what you want.
Currently you are focusing on a single column:
Range("E6:E67").AutoFilter Field:=1, _
You should extend this to the whole table area:
ActiveSheet.Range("$A$5:$M$112").AutoFilter Field:=6, Criteria1:="Leeds"
The number 6 is the sixth column within the filter range. You might also create a Range reference to refer to the filter-range:
Dim rngFilter As Range
Set rngFilter = Worksheets("Staff List").AutoFilter.Range
The filters accumulate, so the following will filter on two columns:
ActiveSheet.Range("$A$5:$M$112").AutoFilter Field:=6, Criteria1:="Leeds"
ActiveSheet.Range("$A$5:$M$112").AutoFilter Field:=7, Criteria1:="Sales"
At some point you will Clear the filters:
ActiveSheet.ShowAllData
Clearing a single filter is just applying a filter with no criteria:
ActiveSheet.Range("$A$5:$M$112").AutoFilter Field:=7
If you record a macro to Sort on more than one column (using Custom Sort) it creates code like the following, to which I've added some comments:
'clear the previous Sort
ActiveWorkbook.Worksheets("Staff List").AutoFilter.Sort.SortFields.Clear
'accumulate the SortFields
ActiveWorkbook.Worksheets("Staff List").AutoFilter.Sort.SortFields.Add Key:= _
Range("C6:C112"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption _
:=xlSortNormal
ActiveWorkbook.Worksheets("Staff List").AutoFilter.Sort.SortFields.Add Key:= _
Range("B6:B112"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption _
:=xlSortNormal
'Apply the Sort
With ActiveWorkbook.Worksheets("Staff List").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.Apply
End With
Recording Macros will also reveal other methods and properties that may be useful to you. The recorded code will not be elegant, and can be reduced (tidied) significantly, but it does provide useful information.

Related

How can I speed up this loop

I have a Vba code that is very slow on 25 sheets, I am wondering if this code can be speeded up in any way
Sub Obracun_place_OLP_NEAKTIVNO()
'
' Obracun_place_NOVI Makronaredba
'
Call Refresh_neto_TM
Application.ScreenUpdating = False
Sheets("PODUZEĆE_PLAĆA").Select
Range("B7:H7").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
Sheets("Neto plaća").Select
ActiveSheet.ListObjects("Tablica_Upit_iz_MS_Access_Database_14").Range. _
AutoFilter Field:=204, Criteria1:=Range("A2")
ActiveSheet.ListObjects("Tablica_Upit_iz_MS_Access_Database_14").Range. _
AutoFilter Field:=207, Criteria1:="<>"
Range("GV11:GZ11").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("PODUZEĆE_PLAĆA").Select
Range("B6:F6").Select
ActiveSheet.Paste
Sheets("Neto plaća").Select
Range("E11:F11").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("PODUZEĆE_PLAĆA").Select
Range("G6:H6").Select
ActiveSheet.Paste
Columns("B:H").Select
Columns("B:H").EntireColumn.AutoFit
Range("A2").Select
Sheets("Neto plaća").Select
ActiveSheet.ListObjects("Tablica_Upit_iz_MS_Access_Database_14").Range. _
AutoFilter Field:=207
ActiveSheet.ListObjects("Tablica_Upit_iz_MS_Access_Database_14").Range. _
AutoFilter Field:=204
Sheets("PODUZEĆE_PLAĆA").Select
Range("B5").Select
ActiveCell.FormulaR1C1 = "=COUNTIF((R[2]C:R[100]C),R[-4]C[-1])"
Range("E5").Select
ActiveCell.FormulaR1C1 = "=SUM(R[2]C:R[100]C)"
Range("E5").Select
Selection.AutoFill Destination:=Range("E5:F5"), Type:=xlFillDefault
Range("E5:F5").Select
Range("B6:H6").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveWorkbook.Worksheets("PODUZEĆE_PLAĆA").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("PODUZEĆE_PLAĆA").Sort.SortFields.Add Key:=Range( _
"C7:C129"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("PODUZEĆE_PLAĆA").Sort
.SetRange Range("B6:H129")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("B7:H7").Select
Range(Selection, Selection.End(xlDown)).Select
With Selection.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Sheets("PLAĆA_SPISAK").Select
ActiveSheet.Range("$C$10:$G$60").AutoFilter Field:=1, Criteria1:="<>"
Sheets("PODUZEĆE_PLAĆA").Select
Range("B5").Select
Sheets("2001").Select
Range("A1").Select
Application.ScreenUpdating = True
End Sub
Getting Rid of Active and Select (Translating Macro-Recorder Code)
Not tested.
There is still much room for improvement but it should illustrate what it could look like.
It compiles but that doesn't mean it's gonna work. Give it a try and share some feedback.
Issues
If there is no match in the table, the code will fail.
If the data isn't 'nice' and has empty rows, the xlDown lines will fail.
Maybe it would be preferable to write the formulas in A1 style.
The Code
Option Explicit
Sub Obracun_place_OLP_NEAKTIVNO()
Application.ScreenUpdating = False
'Refresh_neto_TM '?
' Reference the workbook ('wb').
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' Reference the source worksheet ('sws').
Dim sws As Worksheet: Set sws = wb.Worksheets("Neto plaća")
Dim stbl As ListObject
Set stbl = sws.ListObjects("Tablica_Upit_iz_MS_Access_Database_14")
' Reference the destination worksheet ('dws').
Dim dws As Worksheet: Set dws = wb.Worksheets("PODUZEĆE_PLAĆA")
' Clear the (old) destination data range (headers are in row 6).
With dws.Range("B7:H7")
.Range(.Cells, .End(xlDown)).ClearContents
End With
' Filter the source table.
With stbl
' Clear possible existing filters.
If .ShowAutoFilter Then
If .AutoFilter.FilterMode Then .AutoFilter.ShowAllData
Else
.ShowAutoFilter = True
End If
' Filter.
.Range.AutoFilter Field:=204, Criteria1:=CStr(sws.Range("A2").Value)
.Range.AutoFilter Field:=207, Criteria1:="<>"
End With
' Copy the data from the source to the destination worksheet.
With sws
With .Range("GV11:GZ11")
.Range(.Cells, .End(xlDown)).Copy dws.Range("B6:F6")
End With
With .Range("E11:F11")
.Range(.Cells, .End(xlDown)).Copy dws.Range("G6:H6")
End With
sws.Columns("B:H").EntireColumn.AutoFit
'Application.Goto sws.Range("A2") ' reset to initial selection
End With
' Clear the table filters.
stbl.AutoFilter.ShowAllData
With dws
' Reference the (new) destination range ('drg').
Dim drg As Range
With dws.Range("B6:H6")
Set drg = .Range(.Cells, .End(xlDown))
End With
' Write formulas.
Dim lfRow As Long: lfRow = drg.Rows.Count ' last formula row
.Range("B5").FormulaR1C1 _
= "=COUNTIF((R[2]C:R[" & lfRow & "]C),R[-4]C[-1])"
.Range("E5:F5").FormulaR1C1 = "=SUM(R[2]C:R[" & lfRow & "]C)"
' Sort by the 2nd column ('C').
With .Sort
.SortFields.Clear
.SortFields.Add _
Key:=drg.Columns(2), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortNormal
.SetRange drg
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
' Apply formatting.
With drg.Resize(drg.Rows.Count - 1).Offset(1) ' 'drg' without headers
With .Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End With
'Application.Goto .Range("B5") ' reset to initial selection
End With
' These are irrelevant, the second one probably not necessary!?
wb.Worksheets("PLAĆA_SPISAK").Range("C10:G60").AutoFilter 1, "<>"
'Application.Goto wb.Worksheets("2001").Range("A1")
Application.ScreenUpdating = True
End Sub

Sort Column and Hide Rows without specified text in column using VBA Macro in Excel

I'm looking to use a VBA Macro which will 'sort' a column but 'hide' all the other text.
The column is populated with three letter text, i.e. MFA, KDB, OPA etc...
This is the code I currently have found:
Sub SortByName()
With ActiveSheet
.Sort.SortFields.Clear
.Sort.SortFields.Add Key:=.Range("V:V"), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
CustomOrder:="MFA", _
DataOption:=xlSortNormal
.Sort.SetRange .Range("A:AA")
.Sort.Header = xlYes
.Sort.MatchCase = False
.Sort.Orientation = xlTopToBottom
.Sort.SortMethod = xlPinYin
.Sort.Apply
End With
End Sub
This code works well, but it does not hide the undesired rows with text that is not 'MFA'
Many thanks :)
As mentioned, use AutoFilter to hide rows not containing 'MFA'
Option Explicit
Public Sub SortByName()
Dim ws As Worksheet
Set ws = ActiveSheet
With ws
.Sort.SortFields.Clear
.Sort.SortFields.Add Key:=.Range("V:V"), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
CustomOrder:="MFA", _
DataOption:=xlSortNormal
.Sort.SetRange .Range("A:AA")
.Sort.Header = xlYes
.Sort.MatchCase = False
.Sort.Orientation = xlTopToBottom
.Sort.SortMethod = xlPinYin
.Sort.Apply
.UsedRange.Columns("V").AutoFilter Field:=1, Criteria1:="MFA"
'Or: .Range("A:AA").AutoFilter Field:=22, Criteria1:="MFA"
End With
End Sub

Call subroutines inside Event

I've the Pivot Table in Sheet 1 and in VBA I've the following code to sort another PivotTable in the same sheet based on Update event.
Event Code
Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
If Target = "PivotTable1" Then
ActiveSheet.PivotTables("75Percentile").PivotFields( _
"[DimCustomer].[Customer Desc].[Customer Desc]").ClearAllFilters
ActiveSheet.PivotTables("75Percentile").PivotFields( _
"[DimCustomer].[Customer Desc].[Customer Desc]").PivotFilters.Add2 Type:= _
xlValueIsGreaterThan, DataField:=ActiveSheet.PivotTables("75Percentile"). _
CubeFields("[Measures].[Sales Qty (Van Sales)]"), Value1:=Range("F5").Value
Call Module1.SortGold
End If
End Sub
Inside this code I try to call Module1.SortGold that is:
Module Code
Sub SortGold()
ActiveWorkbook.Worksheets("Gold").AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Gold").AutoFilter.Sort.SortFields.Add Key:=Range( _
"E2:E5001"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("Gold").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
That should sort values in another sheet (Gold). Unfortunately It seems that the module wont trigger. If I run with F5 the module the table is sorted correctly so the problem is launching the module...
Any thoughts?
Try this modification:
Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
Application.EnableEvents = False
If Target = "PivotTable1" Then
ActiveSheet.PivotTables("75Percentile").PivotFields( _
"[DimCustomer].[Customer Desc].[Customer Desc]").ClearAllFilters
ActiveSheet.PivotTables("75Percentile").PivotFields( _
"[DimCustomer].[Customer Desc].[Customer Desc]").PivotFilters.Add2 Type:= _
xlValueIsGreaterThan, DataField:=ActiveSheet.PivotTables("75Percentile"). _
CubeFields("[Measures].[Sales Qty (Van Sales)]"), Value1:=Range("F5").Value
Call Module1.SortGold
End If
Application.EnableEvents = True
End Sub

Very very slow Excel Macro

I am trying to automate process that I have to do every day at work by dumping a pool of data and reformatting it. I have been working on this for quite a while and the last place I thought I'd be would was on a forum asking for help. I've done some research and have included as many of the recommendations that i could find in my macro. When I 1st created the macro I had all of the "Select"ing in there and it was running fast. As i kept running it for trial purposes it got slower and slower. Now it takes 2 minutes or more to complete and within the 1st 5 seconds it stops responding and then 2-3 minutes later it is done.
The purpose of this is to reformat information for a sheet that is look at and to create a sheets based on the date to prioritize the information. All of the date is linked to a sheet call "Hot Sheet" but I create a new sheet and then switch over the formula references so Excel doesn't over work itself. I am a novice and self taught so please go easy on me.
PS: As I am saving the file it now prompts me saying: "Privacy Warning: This document contains macros, ActiveX Controls, XML expansions pack information, or Web components. These may include personal information that cannot be removed by the Document Inspector."
Code:
ActiveSheet.Name = "Sheet1"
Columns("A:A").Select
Range("A4").Activate
Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, _
Semicolon:=False, Comma:=False, Space:=True, Other:=False, FieldInfo _
:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1)), TrailingMinusNumbers:= _
True
Rows("1:3").Insert Shift:=xlDown
Range("A1:T1").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Range("A1:T1").Merge
Range("A1:T1").FormulaR1C1 = "ASCP Planner Overview Report"
Range("A4").FormulaR1C1 = "Input Perameters"
Rows("5:37").ClearContents
Range("B4").ClearContents
Range("B5").FormulaR1C1 = "Instance Name"
Range("B6").FormulaR1C1 = "MRP Plan Name"
Range("B7").FormulaR1C1 = "Organization Code"
Range("B8").FormulaR1C1 = "Bucket Type"
Range("B9").FormulaR1C1 = "Report Type"
Range("B10").FormulaR1C1 = "Planner"
Range("B11").FormulaR1C1 = "Planner user name"
Range("B12").FormulaR1C1 = "Planner Lookup"
Range("B13").FormulaR1C1 = "Supplier"
Range("B14").FormulaR1C1 = "SC Total"
Range("B15").FormulaR1C1 = "Make / Buy"
Range("B16").FormulaR1C1 = "Net Shortage Only"
Range("B17").FormulaR1C1 = "Shortage Cutoff Date"
Range(Selection, Selection.End(xlToRight)).Select
Range("A40:F40").Cut Destination:=Range("E13:J13")
Rows("43:61").Delete Shift:=xlUp
On Error Resume Next
With Application
.ScreenUpdating = False
.EnableEvents = False
PrevCalc = .Calculation
.Calculation = xlCalculationManual
End With
Columns("A:A").ColumnWidth = 11
Range("T41").FormulaR1C1 = "Page 1"
Range("E50").FormulaR1C1 = "=R[-5]C[-2]"
Range("E50").AutoFill Destination:=Range("E50:T50"), Type:=xlFillDefault
Range("B43").CutCopyMode = False
Range("F49").FormulaR1C1 = "=R[-6]C[-2]&R[-6]C[-1]&R[-6]C&R[-6]C[1]"
Range("F49").Copy
Range("F49").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("E50:T50").Copy
Range("E50:T50").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Rows("43:48").ClearContents
Range("A43").FormulaR1C1 = "ORG"
Range("A44").FormulaR1C1 = "Planner"
Range("A45").FormulaR1C1 = "Sourcing Rule"
Range("A46").FormulaR1C1 = "OH Qty-Insp"
Range("A47").FormulaR1C1 = "Negative"
Range("A48").FormulaR1C1 = "OH-Consign"
Range("B43").FormulaR1C1 = "Item Number"
Range("B44").FormulaR1C1 = "Make/Buy"
Range("B46").FormulaR1C1 = "OH Qty-Total"
Range("B47").FormulaR1C1 = "In trans Qty"
Range("B48").FormulaR1C1 = "LT (Post P)"
Range("93:93,95:112,155:155,157:174,217:217,219:236,279:279,281:298,341:341,343:360,403:403 ,405:422").Delete Shift:=xlUp
Rows("351:351").Delete Shift:=xlUp
Rows("352:369").Delete Shift:=xlUp
Rows("394:394").Delete Shift:=xlUp
Rows("395:412").Delete Shift:=xlUp
Rows("437:437").Delete Shift:=xlUp
Rows("440:455").Delete Shift:=xlUp
Rows("439:439").Delete Shift:=xlUp
Rows("481:481").Delete Shift:=xlUp
Range("57:57,63:63,69:69,75:75,81:81,87:87").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("99:101").Insert Shift:=xlDown
Range("F101").FormulaR1C1 = "=R[-52]C"
Range("E102:T102").FormulaR1C1 = "=R[-52]C"
Range("E102:T102").Select
Range("109:109,115:115,121:121,127:127,133:133,139:139").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("151:153").Insert Shift:=xlDown
Range("F153").FormulaR1C1 = "=R[-52]C"
Range("E154:T154").FormulaR1C1 = "=R[-52]C"
Range("E154:T154").Select
Range("161:161,167:167,173:173,179:179,185:185,191:191").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("203:205").Insert Shift:=xlDown
Range("F205").FormulaR1C1 = "=R[-52]C"
Range("E206:T206").FormulaR1C1 = "=R[-52]C"
Range("E206:T206").Select
Range("213:213,219:219,225:225,231:231,237:237,243:243").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("255:257").Insert Shift:=xlDown
Range("F257").FormulaR1C1 = "=R[-52]C"
Range("E258:T258").FormulaR1C1 = "=R[-52]C"
Range("E258:T258").Select
Range("265:265,271:271,277:277,283:283,289:289,295:295").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("307:309").Insert Shift:=xlDown
Range("F309").FormulaR1C1 = "=R[-52]C"
Range("E310:T310").FormulaR1C1 = "=R[-52]C"
Range("E310:T310").Select
Range("317:317,323:323,329:329,335:335,341:341,347:347").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("359:361").Insert Shift:=xlDown
Range("F361").FormulaR1C1 = "=R[-52]C"
Range("E362:T362").FormulaR1C1 = "=R[-52]C"
Range("E362:T362").Select
Range("369:369,375:375,381:381,387:387,393:393,399:399").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("411:413").Insert Shift:=xlDown
Range("F413").FormulaR1C1 = "=R[-52]C"
Range("E414:T414").FormulaR1C1 = "=R[-52]C"
Range("421:421,427:427,433:433,439:439,445:445,451:451").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("463:465").Insert Shift:=xlDown
Range("F465").FormulaR1C1 = "=R[-52]C"
Range("E466:T466").FormulaR1C1 = "=R[-52]C"
Range("473:473,479:479,485:485,491:491,497:497,503:503").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("515:517").Insert Shift:=xlDown
Range("F517").FormulaR1C1 = "=R[-52]C"
Range("E518:T518").FormulaR1C1 = "=R[-52]C"
Rows("519:519").Delete Shift:=xlUp
Range("525:525,531:531,537:537,543:543,549:549,555:555").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = PrevCalc
End With
On Error Resume Next
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Cells.Select
Range("C562").Activate
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, _
Formula1:="=0"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
.Color = -16383844
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 13551615
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Range("A50").Select
Union(Range( _
"B291,B298,B305,B315,B322,B329,B336,B343,B350,B357,B367,B374,B381,B388,B395,B402,B409,B419,B426,B55,B62,B69,B76,B83,B90,B97,B107,B114,B121,B128,B135,B142" _
), Range( _
"B149,B159,B166,B173,B180,B187,B194,B201,B211,B218,B225,B232,B239,B246,B253,B263,B270,B277,B284" _
)).Select
Range("B426").Activate
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _
Formula1:="=0"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
.Color = -16752384
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 13561798
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Range("A401").Select
Range("A51").Select
Application.DisplayAlerts = False
On Error Resume Next
Sheets("Sheet1").Copy Before:=Sheets(1)
ActiveSheet.Select
Sheets("View1").Delete
ActiveSheet.Name = "View1"
Sheets("Hot Sheet").Select
Cells.Select
ActiveSheet.Range("$A$1:$D$524").AutoFilter Field:=4
ActiveSheet.Range("$A$1:$D$524").AutoFilter Field:=1
Selection.Replace What:="View2", Replacement:="View1", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Sheets("View1").Copy Before:=Sheets(1)
Sheets("View1 (2)").Select
Sheets("View2").Delete
Sheets("View1 (2)").Name = "View2"
Sheets("Hot Sheet").Select
Cells.Select
Selection.Replace What:="View1", Replacement:="View2", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
ActiveSheet.Range("$A$1:$D$524").AutoFilter Field:=1, Criteria1:=Array( _
"NA:ASH", "NA:DLM", "NA:FOR", "NA:FRK", "NA:LRS", "NA:MON", "NA:NWK", "NA:YRB", _
"NA:YRK"), Operator:=xlFilterValues
Range("A1").Select
Sheets("Sheet1").Delete
Application.EnableEvents = True
End Sub
Try turning off screen updating to free up system resources. You might have other issues with your macro, but you should notice a marked improvement in performance.
at the beginning of your macro add:
Application.ScreenUpdating = False
At the end (right before 'End Sub") add:
Application.ScreenUpdating = True
I hope this helps.
Where to start? btw don't take it the wrong way, its clear you already know how to get Excel to do what you want with VBA these tips are more about addressing your question in terms of performance.
Application.ScreenUpdating = False (at start) turn back on at end.
you seem to have a preference for using R1C1 notation with formulas, replace that with a pattern that gets all input data from each of your cell blocks into a 2 dimensional array, via .Range2 property.
do all transformations of data using loops to update values in the array as necessary.
write the array back to a cell range of the exact same size passing in the array to the .Range2 property.
The With blocks look pretty harmless you can leave them.
Move the formatting conditions right to the end unless you need it earlier (you shouldn't).
add a table (listobject) and convert your range to that. then use the data block to reference the data you'll be modifying in tip (2.) above.
use the table to insert rows if you have to. however you'd be better off, working with the data in an array, adding rows (elements) as necessary within the array, then calculating the new array size and writing that back as per tips (2. through 4.).

Apply AutoFilter and display results in UserForm ListBox?

Right now I have a UserForm that looks like this:
I have a spreadsheet that looks like this:
I am using the following code in the UserForm_Initialize event to apply an AutoFilter to my data. I need to display the results of the AutoFilter in my listbox which is named "boxPolicyList".
Worksheets("defaults").Select
Me.boxDateBegin.Value = ActiveSheet.Range("E4").Value
Me.boxDateEnd.Value = ActiveSheet.Range("F4").Value
Workbooks.Open Filename:="Z:\Stuff\production\production_database.xlsm"
Worksheets("policies").Select
With ActiveSheet
.AutoFilterMode = False
With .Range("A1:F1")
.AutoFilter
.AutoFilter field:=1, Criteria1:=">=" & Me.boxDateBegin.Value, _
Operator:=xlAnd, Criteria2:="<=" & Me.boxDateEnd.Value
.AutoFilter field:=3, Criteria1:="Bear River Mutual"
End With
End With
Me.txtTotalPolicies.Caption = ActiveSheet.Range("J1").Value
Me.txtTotalPremium.Caption = ActiveSheet.Range("H1").Value
Me.txtTotalPremium.Caption = Format(Me.txtTotalPremium.Caption, "$#,###,###.00")
Workbooks("production_database.xlsm").Activate
ActiveWorkbook.Save
ActiveWorkbook.Close
Does anyone know how this can be done?
Perhaps...
Private Sub UserForm_Initialize()
Dim rngVis As Range
Me.boxDateBegin.Value = Sheets("defaults").Range("E4").Value
Me.boxDateEnd.Value = Sheets("defaults").Range("F4").Value
With Workbooks.Open("Z:\Stuff\production\production_database.xlsm")
With Sheets("policies")
.AutoFilterMode = False
Me.txtTotalPolicies.Caption = .Range("J1").Value
Me.txtTotalPremium.Caption = Format(.Range("H1").Value, "$#,###,###.00")
With Intersect(.UsedRange, .Range("A:F"))
.Sort Intersect(.Cells, .Parent.Columns("C")), xlAscending, Intersect(.Cells, .Parent.Columns("A")), , xlAscending, Header:=xlGuess
.AutoFilter 3, "Bear RIver Mutual"
.AutoFilter 1, ">=" & Me.boxDateBegin.Value, xlAnd, "<=" & Me.boxDateEnd.Value
On Error Resume Next
Set rngVis = .Offset(1).Resize(.Rows.Count).SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If Not rngVis Is Nothing Then Me.boxPolicyList.List = rngVis.Value
End With
End With
.Close False
End With
End Sub