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.).
Related
I have the following code and it appears to always produce an error 619 "Control not found" at line session.findById("wnd[1]/tbar[0]/btn[0]").press, even though I have entered Application.DisplayAlerts = False and I've taken extra precaution to bypass the error. I have attempted using On Error GoTo, On Error Resume Next, and even If IsError(), but none of that seems to be working.
'Insert Sum of Amts and list as Balance on Summary tab
Sheets(2).Select
LastRow = ActiveSheet.UsedRange.Rows.Count
Range("D" & LastRow + 1).Select
ActiveCell.FormulaR1C1 = "=SUM(R2C4:R" & LastRow & "C4)"
Columns("D:D").Select
Selection.NumberFormat = "_(* #,##0.00_);_(* (#,##0.00);_(* ""-""??_);_(#_)"
Sheets(1).Select
Range("C7").Select
ActiveCell.FormulaR1C1 = "=Statement!R" & LastRow + 1 & "C4"
'Insert V-lookup for open items
Sheets(2).Select
Range("G2").Select
ActiveCell.FormulaR1C1 = _
"=IF(OR(RC[-1]=""R"",RC[-1]=""A""),""-"",IF(IFERROR(VLOOKUP(RC[-5],'FBL1N Scheduled'!C1:C2,2,0), ""-"")>TODAY(),IFERROR(VLOOKUP(RC[-5],'FBL1N Scheduled'!C1:C2,2,0), ""-""),IF(IFERROR(VLOOKUP(RC[-5],'FBL1N Scheduled'!C1:C2,2,0), ""-"")<=DATE(YEAR(TODAY()),MONTH(TODAY()),15),IF(TODAY()<=DATE(YEAR(TODAY()),MONTH(TODAY()),15),DATE(YEAR(TODAY()),MONTH(TODAY()),15),EOMONTH(TODAY(),0)))))"
Range("G2").Select
Selection.AutoFill Destination:=Range("G2:G" & LastRow), Type:=xlFillDefault
Range("G2:G" & LastRow).Select
Selection.NumberFormat = "mm/dd/yyyy;#"
'Insert V-lookup for cleared items
Range("H2").Select
ActiveCell.FormulaR1C1 = _
"=IF(RC[-1]<>""-"",""-"",IFERROR(VLOOKUP(RC[-6],'FBL1N Paid'!C1:C2,2,0),""-""))"
Range("H2").Select
Selection.AutoFill Destination:=Range("H2:H" & LastRow), Type:=xlFillDefault
Range("H2:H" & LastRow).Select
Selection.NumberFormat = "mm/dd/yyyy;#"
'Autofit and filter
Cells.Select
Cells.EntireColumn.AutoFit
Application.CutCopyMode = False
Selection.AutoFilter
'Copy values for Vim
LastRow = ActiveSheet.UsedRange.Rows.Count
ActiveSheet.Range("$A$1:$K$" & LastRow).AutoFilter Field:=7, Criteria1:="-"
ActiveSheet.Range("$A$1:$K$" & LastRow).AutoFilter Field:=8, Criteria1:="-"
'Insert DPN for processing/obsolete invoices
With Worksheets("Statement").AutoFilter.Range
Range("E" & .Offset(1, 0).SpecialCells(xlCellTypeVisible)(1).Row).Select
End With
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(RC[-3],'VIM Export'!C1:C5,3,0),"""")"
'Copy down in only visible
With ActiveSheet.UsedRange
.Resize(.Rows.Count - 1).Offset(1).Columns("E"). _
SpecialCells(xlCellTypeVisible).FillDown
End With
'Select Reference #
With Worksheets("Statement").AutoFilter.Range
Range("B" & .Offset(1, 0).SpecialCells(xlCellTypeVisible)(1).Row).Select
End With
'If none are left processing, skip VIM
If ActiveCell.Value = "" Then GoTo Valuations:
'Copy all invoice numbers not posted
Range(ActiveCell, ActiveCell.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
'Switch to Summary page to pull vendor data in VIM search
Sheets(1).Select
'Execute in SAP
If Not IsObject(SAPApp) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set SAPApp = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
Set Connection = SAPApp.Children(0)
End If
If Not IsObject(session) Then
Set session = Connection.Children(0)
End If
If IsObject(WScript) Then
WScript.ConnectObject session, "on"
WScript.ConnectObject SAPApp, "on"
End If
'Open Vim and apply parameters (inserting Doc Numbers)
session.findById("wnd[0]/tbar[0]/btn[12]").press
session.findById("wnd[0]/tbar[0]/btn[12]").press
't-code entered in bar
session.findById("wnd[0]/tbar[0]/okcd").Text = "/n/opt/vim_analytics"
session.findById("wnd[0]").sendVKey 0
session.findById("wnd[0]/usr/btn%_S_XBLNR_%_APP_%-VALU_PUSH").press
session.findById("wnd[1]/tbar[0]/btn[24]").press
session.findById("wnd[1]").sendVKey 8
session.findById("wnd[0]/usr/btn%_S_LIFNR_%_APP_%-VALU_PUSH").press
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,0]").Text = Cells(3, 1).Value
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,1]").Text = Cells(4, 1).Value
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,2]").Text = Cells(5, 1).Value
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,3]").Text = Cells(3, 3).Value
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,4]").Text = Cells(4, 3).Value
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,5]").Text = Cells(5, 3).Value
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,1]").SetFocus
session.findById("wnd[1]/usr/tabsTAB_STRIP/tabpSIVA/ssubSCREEN_HEADER:SAPLALDB:3010/tblSAPLALDBSINGLE/ctxtRSCSEL_255-SLOW_I[1,1]").caretPosition = 7
session.findById("wnd[1]").sendVKey 8
session.findById("wnd[0]").sendVKey 8
On Error Resume Next
session.findById("wnd[1]/tbar[0]/btn[0]").press
If Err.Number = 0 Then
'Export to Excel (Existing XXL Format)
session.findById("wnd[0]/usr/cntlCL_GRID/shellcont/shell").contextMenu
session.findById("wnd[0]/usr/cntlCL_GRID/shellcont/shell").selectContextMenuItem "&XXL"
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Select Export and Paste into Workbook
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Cut
Windows("Updated Auto Recon.xlsm").Activate
Sheets(5).Select
Range("A1").Select
ActiveSheet.Paste
'Clear Formatting
ThisWorkbook.ActiveSheet.Cells.ClearFormats
'Close temporary export sheet
Windows("Worksheet in Basis (1)").Activate
ActiveWindow.Close
If Not IsObject(SAPApp) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set SAPApp = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
Set Connection = SAPApp.Children(0)
End If
If Not IsObject(session) Then
Set session = Connection.Children(0)
End If
If IsObject(WScript) Then
WScript.ConnectObject session, "on"
WScript.ConnectObject SAPApp, "on"
End If
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Formatting VIM Export
''Moves columns to the appropriate postions in the worksheet
''Move Reference to Column A; Move CoCode to Column B; Move Doc. ID to Column C; Move Document Status to Column D
Range("A1").End(xlToRight).Select
LastColumn = ActiveCell.Column
For i = 1 To LastColumn
Cells(1, i).Select
If ActiveCell.Value = "CoCd" Then
ActiveCell.Value = "CoCode"
ElseIf ActiveCell.Value = "Company Code" Then
ActiveCell.Value = "CoCode"
ElseIf ActiveCell.Value = "DocumentStatus" Then
ActiveCell.Value = "Document Status"
ElseIf ActiveCell.Value = "DOC Status" Then
ActiveCell.Value = "Document Status"
ElseIf ActiveCell.Value = "DOC status" Then
ActiveCell.Value = "Document Status"
ElseIf ActiveCell.Value = "Document Id" Then
ActiveCell.Value = "Doc. Id"
ElseIf ActiveCell.Value = "Vendor Nam" Then
ActiveCell.Value = "Vendor Name"
Else
End If
Next i
For i = 1 To LastColumn
Cells(1, i).Select
If ActiveCell.Value = "Reference" Then
If ActiveCell.Column <> 1 Then
Columns(i).Select
Selection.Cut
Columns("A").Insert Shift:=xlToRight
Else
End If
Else
End If
Next i
For i = 1 To LastColumn
Cells(1, i).Select
If ActiveCell.Value = "CoCode" Then
If ActiveCell.Column <> 2 Then
Columns(i).Select
Selection.Cut
Columns("B").Insert Shift:=xlToRight
Else
End If
Else
End If
Next i
For i = 1 To LastColumn
Cells(1, i).Select
If ActiveCell.Value = "Doc. Id" Then
If ActiveCell.Column <> 3 Then
Columns(i).Select
Selection.Cut
Columns("C").Insert Shift:=xlToRight
Else
End If
Else
End If
Next i
For i = 1 To LastColumn
Cells(1, i).Select
If ActiveCell.Value = "Document Status" Then
If ActiveCell.Column <> 4 Then
Columns(i).Select
Selection.Cut
Columns("D").Insert Shift:=xlToRight
Else
End If
Else
End If
Next i
For i = 1 To LastColumn
Cells(1, i).Select
If ActiveCell.Value = "Vendor" Then
If ActiveCell.Column <> 5 Then
Columns(i).Select
Selection.Cut
Columns("E").Insert Shift:=xlToRight
Else
End If
Else
End If
Next i
For i = 1 To LastColumn
Cells(1, i).Select
If ActiveCell.Value = "Vendor Name" Then
If ActiveCell.Column <> 6 Then
Columns(i).Select
Selection.Cut
Columns("F").Insert Shift:=xlToRight
Else
End If
Else
End If
Next i
'Remove Confirmed Duplicate Status
i = Application.WorksheetFunction.CountIf(Columns("D:D"), "Confirmed Duplicate")
If i > 0 Then
LastRow = ActiveSheet.UsedRange.Rows.Count
Range(Cells(1, 1), Cells(LastRow, LastColumn)).Select
Selection.AutoFilter
ActiveSheet.Range(Cells(1, 1), Cells(LastRow, LastColumn)).AutoFilter Field:=4, Criteria1:="Confirmed Duplicate", _
Operator:=xlAnd
Rows("2:" & LastRow).SpecialCells(xlCellTypeVisible).Select
Selection.Delete Shift:=xlToLeft
ActiveSheet.ShowAllData
Else
End If
'Remove Cancelled Status
i = Application.WorksheetFunction.CountIf(Columns("D:D"), "Cancelled")
If i > 0 Then
LastRow = ActiveSheet.UsedRange.Rows.Count
Range(Cells(1, 1), Cells(LastRow, LastColumn)).Select
Selection.AutoFilter
ActiveSheet.Range(Cells(1, 1), Cells(LastRow, LastColumn)).AutoFilter Field:=4, Criteria1:="Cancelled", _
Operator:=xlAnd
Rows("2:" & LastRow).SpecialCells(xlCellTypeVisible).Select
Selection.Delete Shift:=xlToLeft
ActiveSheet.ShowAllData
Else
End If
Application.ScreenUpdating = True
Application.ScreenUpdating = False
'Force Doc Id to convert to number
Range("C:C").Select
With Selection
Selection.NumberFormat = "General"
.Value = .Value
End With
Application.ScreenUpdating = True
Application.ScreenUpdating = False
'Force Vendor # to convert to number
Range("E:E").Select
With Selection
Selection.NumberFormat = "General"
.Value = .Value
End With
'Sorts Reference number by most recent document status
LastRow = ActiveSheet.UsedRange.Rows.Count
Range(Cells(1, 1), Cells(LastRow, LastColumn)).Select
Range("A2").Activate
ActiveWorkbook.Worksheets("VIM Export").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("VIM Export").Sort.SortFields.Add Key:=Range( _
"C2:C" & LastRow), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
xlSortNormal
ActiveWorkbook.Worksheets("VIM Export").Sort.SortFields.Add Key:=Range( _
"A2:A" & LastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("VIM Export").Sort
.SetRange Range(Cells(1, 1), Cells(LastRow, LastColumn))
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("A2").Select
Else
Err.Clear
End If
On Error GoTo 0
'Resume
Valuations:
'Select Statement sheet
Sheets(2).Select
'Clear Filter
ActiveSheet.ShowAllData
Application.ScreenUpdating = True
Application.ScreenUpdating = False
'Change Font and Size, autofit
Cells.Select
With Selection.Font
.Name = "CotySans"
.FontStyle = "Regular"
.Size = 9
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
.TintAndShade = 0
.ThemeFont = xlThemeFontNone
End With
'Format Top Row
Rows("1:1").SpecialCells(xlCellTypeConstants).Select
Selection.Font.Bold = True
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
.TintAndShade = -0.149998474074526
.PatternTintAndShade = 0
End With
'Insert Company Code from all tabs
LastRow = ActiveSheet.UsedRange.Rows.Count
Range("A2").Select
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(RC[1],'FBL1N Scheduled'!C1:C4,3,0), IFERROR(VLOOKUP(RC[1],'FBL1N Paid'!C1:C4,3,0),IFERROR(VLOOKUP(RC[1],'VIM Export'!C1:C5,2,0),"""")))"
Selection.AutoFill Destination:=Range("A2:A" & LastRow - 1)
'Insert Vendor Number from all tabs
Columns("B:B").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("B1").Select
ActiveCell.FormulaR1C1 = "Vendor #"
Range("B2").Select
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(RC[1],'FBL1N Scheduled'!C1:C4,4,0), IFERROR(VLOOKUP(RC[1],'FBL1N Paid'!C1:C4,4,0),IFERROR(VLOOKUP(RC[1],'VIM Export'!C1:C5,5,0),"""")))"
Selection.AutoFill Destination:=Range("B2:B" & LastRow - 1)
'Pull Block Marker
Range("F2").Select
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(RC[-3],'VIM Export'!C1:C5,3,0),"""")"
Range("F2").Select
Selection.AutoFill Destination:=Range("F2:F" & LastRow)
Range("F:F").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'Insert VIM Status for processing/obsolete invoices
Range("L2").Select
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(RC[-9],'VIM Export'!C1:C5,4,0),"""")"
'Copy down in only visible
Selection.Copy
Range("L" & LastRow - 1).Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
'Insert Status based on VIM Status
LastRow = ActiveSheet.UsedRange.Rows.Count - 1
Range("J2").Select
ActiveCell.FormulaR1C1 = _
"=IF(OR(RC[-3]=""R"",RC[-3]=""A""),""Blocked"",IF(RC[-8]="""",""Need Copy"",IF(RC[2]="""","""",IF(RC[2]=""Return To Vendor"",""Return To Vendor"",IF(RC[2]=""Obsolete"",""Obsolete"",""Processing"")))))"
Selection.AutoFill Destination:=Range("J2:J" & LastRow)
'Paste special over formulas
Range("A:A").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("B:B").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("F:F").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("H:J").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Application.ScreenUpdating = True
Application.ScreenUpdating = False
'AutoFit Columns
Cells.Select
Cells.EntireColumn.AutoFit
Application.CutCopyMode = False
Range("L:L").Value = ""
LastRow = ActiveSheet.UsedRange.Rows.Count - 1
Range("B2:C" & LastRow).Select
With Selection
.HorizontalAlignment = xlRight
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Range("A2").Select
'Refresh Pivot Info for dates
Worksheets("Pivots").PivotTables("PivotTable1").PivotCache.Refresh
Worksheets("Pivots").PivotTables("PivotTable2").PivotCache.Refresh
'Hide Data Tabs
ThisWorkbook.Sheets(Array(3, 4, 5)).Visible = False
Sheets(1).Select
'Saves the file
Dim VN As String
VN = Range("A3").Value
Dim VName As String
VName = Range("B3").Value
Set objWS = CreateObject("WScript.Shell")
strDesktopPath = objWS.SpecialFolders("Desktop")
ActiveWorkbook.SaveAs strDesktopPath & "\" & VN & "." & VName & " as of " & Format(Now, "mm.dd.yyyy") & ".xlsm"
'Update final once macro completes
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
It may be that the script does not wait long enough for the button to be present.
At this one can either wait for a defined time or wait until it actually exists.
for example:
...
session.findById("wnd[0]").sendVKey 8
on error resume next
application.wait (Now + TimeValue("00:00:01")) '1 second
session.findById("wnd[1]/tbar[0]/btn[0]").press
If Err.Number = 0 Then
on error goto 0
...
or
...
session.findById("wnd[0]").sendVKey 8
on error resume next
do
application.wait (Now + TimeValue("00:00:01")) '1 second
session.findById("wnd[1]/tbar[0]/btn[0]").press
if err.number = 0 then exit do
loop
If Err.Number = 0 Then
on error goto 0
...
Regards, ScriptMan
I have 6 identical macros in one workbook. 4 out of 6 work good, but I have the same issue for the rest.
If I run the macro from debug window with F8, I have perfect , expected results. If I run a macro normally, I have not any errors, but the result is obviously wrong.
I can guess that at that case , that the macto ignores this part (all mistakes start here), but not sure
ActiveSheet.Range("H2").Select
ActiveCell.FormulaR1C1 = "=COUNTIF(C[-3],RC[-3])"
ActiveSheet.Range("H2").Select
Selection.AutoFill Destination:=Range("H2:H" & lastrow)
ActiveSheet.Range("H2:H" & lastrow).Select
The goal of the macro is to filter one tab, put a few columns in another tab; compare values from one of the columns to another tab, remove duplicates , filter and paste the results in the "Results" tab.
When I do this manually I have got 6 rows in a "Result" tab. When I run it normally, I have one row, or nothing..
Can you please kindly advise - what is wrong with this macro?
I have tried to put this line in my code (no luck) :
Application.PrintCommunication = True
I have tried to put DoEvents
ThisWorkbook before each Row, Column and Range - no luck
Many thanks in advance!!
And here is my full code:
Public lastrow As Long
Public FileName As String
Public TabName As String
Sub APP_filtering_new()
'
' APP_filtering Macro
lastrow = ActiveSheet.Range("A1048576").End(xlUp).Row
Sheets("APP-input").Select
ActiveSheet.Rows("1:1").Select
Selection.AutoFilter
ActiveSheet.Range("$A$1:$AG$14878").AutoFilter Field:=2, Criteria1:=Array( _
"BRAMPTON", "VANCOUVER, CD", "VANCOUVER", _
"VANCOUVER TERMINAL"), Operator:=xlFilterValues
ActiveSheet.Columns("E:E").Select
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.Copy
Sheets("APP_output").Select
ActiveSheet.Columns("A:A").Select
ActiveSheet.Paste
Sheets("APP-input").Select
ActiveSheet.Columns("N:N").Select
Selection.SpecialCells(xlCellTypeVisible).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("APP_output").Select
ActiveSheet.Columns("D:D").Select
ActiveSheet.Paste
Sheets("APP-input").Select
ActiveSheet.Columns("G:G").Select
Selection.SpecialCells(xlCellTypeVisible).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("APP_output").Select
ActiveSheet.Columns("E:E").Select
ActiveSheet.Paste
ActiveSheet.Range("F2").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = " "
ActiveSheet.Range("F2").Select
Selection.AutoFill Destination:=Range("F2:F" & lastrow)
ActiveSheet.Range("F2:F" & lastrow).Select
ActiveSheet.Range("G2").Select
ActiveCell.FormulaR1C1 = " "
ActiveSheet.Range("G2").Select
Selection.AutoFill Destination:=Range("G2:G" & lastrow)
ActiveSheet.Range("G2:G" & lastrow).Select
ActiveSheet.Range("H2").Select
ActiveCell.FormulaR1C1 = "=COUNTIF(C[-3],RC[-3])"
ActiveSheet.Range("H2").Select
Selection.AutoFill Destination:=Range("H2:H" & lastrow)
ActiveSheet.Range("H2:H" & lastrow).Select
ActiveSheet.Columns("H:H").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'remove duplicates
ActiveSheet.Columns("A:H").Select
Application.CutCopyMode = False
ActiveSheet.Range("A1:E" & lastrow).RemoveDuplicates Columns:=5, Header:= _
xlNo
'vlookup, IF condition
ActiveSheet.Range("I2").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-4],container,4,FALSE)"
ActiveSheet.Range("I2").Select
Selection.AutoFill Destination:=Range("I2:I" & lastrow)
ActiveSheet.Range("I2:I" & lastrow).Select
ActiveSheet.Range("J2").Select
ActiveCell.FormulaR1C1 = _
"=IF(RC[-1]<RC[-2],""C. has bigger number of Containers"",IF(RC[-1]=RC[-2],""The same amount of containers"",IF(RC[-2]<RC[-1],""The C. has less amount of Containers"")))"
ActiveSheet.Range("J2").Select
Selection.AutoFill Destination:=Range("J2:J" & lastrow)
ActiveSheet.Range("J2:J" & lastrow).Select
ActiveSheet.Range("H1").Select
ActiveCell.FormulaR1C1 = "Amt of Containers - External report"
ActiveSheet.Range("I1").Select
ActiveCell.FormulaR1C1 = "Amt of Containers - Internal report"
ActiveSheet.Range("J1").Select
ActiveCell.FormulaR1C1 = "Result (N/A means New Shipment)"
ActiveSheet.Range("H1:J1").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlTop
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
ActiveSheet.Range("H1:I1").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ActiveSheet.Range("J1").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ActiveSheet.Range("J1").Select
Application.CutCopyMode = False
Selection.AutoFilter
ActiveSheet.Range("D1:J" & lastrow).AutoFilter Field:=7, Criteria1:=Array( _
"#N/A", "C. has bigger number of Containers", _
"The C. has less amount of Containers"), Operator:=xlFilterValues
' paste in next empty row
ActiveSheet.Rows("2:2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.Copy
Sheets("Results").Select
lastrow = ActiveSheet.Range("A1048576").End(xlUp).Row
ActiveSheet.Range("A" & lastrow + 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
This isn't a full answer, but e.g this block of code
ActiveSheet.Range("H2").Select
ActiveCell.FormulaR1C1 = "=COUNTIF(C[-3],RC[-3])"
ActiveSheet.Range("H2").Select
Selection.AutoFill Destination:=Range("H2:H" & lastrow)
ActiveSheet.Range("H2:H" & lastrow).Select
can be replaced by a single line
ActiveSheet.Range("H2:H" & lastrow).FormulaR1C1 = "=COUNTIF(C[-3],RC[-3])"
Get rid of ActiveSheet and replace with the actual sheet name.
I have a code that I want to run several times but for now I can run it only once unless I made some changes at data sheet name.
My code:
Public Sub MyFilter()
Dim lngStart As Date, lngEnd As Date
lngStart = Range("b2").Value 'assume this is the start date
lngEnd = Range("b3").Value 'assume this is the end date
Range("q:q").AutoFilter field:=1, _
Criteria1:=">=" & lngStart, _
Operator:=xlAnd, _
Criteria2:="<=" & lngEnd
Range("A1:s3000").Select
Range("A:A").Activate
Selection.Copy
Sheets.Add After:=ActiveSheet
Sheets("Sheet2").Select
Sheets("Sheet2").Name = "FilterData"
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Columns("A:A").EntireColumn.AutoFit
Cells.Select
Cells.EntireColumn.AutoFit
Rows("1:1").Select
Application.CutCopyMode = False
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 15773696
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Selection.AutoFilter
Columns("A:A").EntireColumn.AutoFit
Range("A2").Select
End Sub
Before I execute it I create sheet2 manually but if I want to run it again I cant because I already have "FilterData" sheet data name.
How can I modify the code to:
1. Run it without the need to enter "sheet2" manually.
2. To run it more than once.
Thanks!
When you create a new sheet in Excel it becomes the active sheet, so instead of specifically selecting sheet 2 you can use activesheet
Sheets.Add After:=ActiveSheet
With ActiveSheet
.Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
.Columns("A:A").EntireColumn.AutoFit
.Cells.Select
.Cells.EntireColumn.AutoFit
.Rows("1:1").Select
.Application.CutCopyMode = False
With Selection
With .Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 15773696
.TintAndShade = 0
.PatternTintAndShade = 0
End With
.AutoFilter
End With
.Columns("A:A").EntireColumn.AutoFit
.Range("A2").Select
End With
Then you can manually rename all your new sheets.
Alternatively if you want to loop a set number of times you could wrap the whole thing in a loop and increment sheet names:
For i = 1 to 4
Sheets.Add After:=ActiveSheet
With ActiveSheet
.Name = "FilterData " & i
*rest of the code here*
End With
Next i
This will create 4 sheets called FilterData 1, 2, 3 etc, but again this will throw an error if you already have sheets called those things.
I recently joined, and am looking forward to working with the community!
This is my first VBA project ever. I have a project building a macro, and it requires using several vlookup formulas. The formula looks on subsequent tabs for a translation. So, for values on tab 1 column 1, it looks on tab 2; for tab 1 column 2, it looks on tab 3 and so on.
The problem is that the lookup seems to be functioning more as a "find/replace" instead of a true lookup for exact matches only. Below, is what my research has gotten me to so far. I know there is much to learn - please help!
Thanks!
'Insert Crosswalk columns
Columns("H:H").Insert
Set Rng = Range("H2:H" & Range("A:A").End(xlDown).Row)
Rng.FormulaR1C1 = "=VLOOKUP(RC[-1],Crosswalk_1!C[-7]:C[-6],2,0)"
Range("H1").Select
ActiveCell.FormulaR1C1 = "Crosswalk_1"
Columns("J:J").Insert
Set Rng = Range("J2:J" & Range("A:A").End(xlDown).Row)
Rng.FormulaR1C1 = "=VLOOKUP(RC[-1],Crosswalk_2!C[-9]:C[-8],2,0)"
Range("J1").Select
ActiveCell.FormulaR1C1 = "Crosswalk_2"
Columns("K:K").Insert
Set Rng = Range("K2:K" & Range("A:A").End(xlDown).Row)
'Rng.FormulaR1C1 = "=VLOOKUP(RC[1],Crosswalk_3!C[-10]:C[-9],2,0)"
Range("K1").Select
ActiveCell.FormulaR1C1 = "Crosswalk_3"
Here is the FULL macro - I assume the issue is with the lookups, but I may well be wrong!
Sub MainMacro()
If MsgBox("Before starting, ensure Entity ID is ascending", vbYesNo, "Input Required") = vbYes Then
MsgBox "Please do not use Excel while this macro is running."
Dim Rng As Range
'Insert "Formula" columns
Columns("C:C").Insert
Set Rng = Range("C2:C" & Range("A:A").End(xlDown).Row)
Rng.FormulaR1C1 = "=IF(RC[-1]=R[1]C[-1],1,0)"
Range("C1").Select
ActiveCell.FormulaR1C1 = "Formula1"
Columns("D:D").Insert
Set Rng = Range("D2:D" & Range("A:A").End(xlDown).Row)
Rng.FormulaR1C1 = "=IF(RC[-2]=R[-1]C[-2],1,0)"
Range("D1").Select
ActiveCell.FormulaR1C1 = "Formula2"
Columns("E:E").Insert
Set Rng = Range("E2:E" & Range("A:A").End(xlDown).Row)
Rng.FormulaR1C1 = "=CONCATENATE(RC[-2],RC[-1])"
Range("E1").Select
ActiveCell.FormulaR1C1 = "Concatenate1"
'Insert Crosswalk columns
Columns("H:H").Insert
Set Rng = Range("H2:H" & Range("A:A").End(xlDown).Row)
Rng.FormulaR1C1 = "=VLOOKUP(RC[-1],Crosswalk_1!C[-7]:C[-6],2,0)"
Range("H1").Select
ActiveCell.FormulaR1C1 = "Crosswalk_1"
Columns("J:J").Insert
Set Rng = Range("J2:J" & Range("A:A").End(xlDown).Row)
Rng.FormulaR1C1 = "=VLOOKUP(RC[-1],Crosswalk_2!C[-9]:C[-8],2,0)"
Range("J1").Select
ActiveCell.FormulaR1C1 = "Crosswalk_2"
Columns("K:K").Insert
Set Rng = Range("K2:K" & Range("A:A").End(xlDown).Row)
Rng.FormulaR1C1 = "=VLOOKUP(RC[1],Crosswalk_3!C[-10]:C[-9],2,0)"
Range("K1").Select
ActiveCell.FormulaR1C1 = "Crosswalk_3"
'Copy&Paste Values
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
'Clean-up & Final Formatting
Range("G1").Select
Range("G1").Cut Destination:=Range("H1")
Range("I1").Select
Range("I1").Cut Destination:=Range("J1")
Range("L1").Select
Range("L1").Cut Destination:=Range("K1")
Columns("G:G").Select
Selection.Delete Shift:=xlToLeft
Columns("H:H").Select
Selection.Delete Shift:=xlToLeft
Columns("J:J").Select
Selection.Delete Shift:=xlToLeft
Columns("G:I").Select
Selection.Replace What:="#N/A", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Application.CutCopyMode = False
'Apply Filter to isolate duplicates
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
Application.CutCopyMode = False
Range(Selection, Selection.End(xlToRight)).Select
Selection.AutoFilter
ActiveSheet.Range("$A:$I").AutoFilter Field:=5, Criteria1:=Array( _
"01", "10", "11"), Operator:=xlFilterValues
'Delete dupes
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
ActiveSheet.Range("$A:$L").RemoveDuplicates Columns:=Array(1, 2, 6, 7, 8, 9), Header:=xlYes
'Final De-Dupe Process
Columns("C:E").Select
Selection.Delete Shift:=xlToLeft
Range("A1").Select
Columns("C:C").Insert
Set Rng = Range("C2:C" & Range("A:A").End(xlDown).Row)
Rng.FormulaR1C1 = "=IF(RC[-1]=R[1]C[-1],1,0)"
Range("C1").Select
ActiveCell.FormulaR1C1 = "Formula1"
Columns("D:D").Insert
Set Rng = Range("D2:D" & Range("A:A").End(xlDown).Row)
Rng.FormulaR1C1 = "=IF(RC[-2]=R[-1]C[-2],1,0)"
Range("D1").Select
ActiveCell.FormulaR1C1 = "Formula2"
Columns("E:E").Insert
Set Rng = Range("E2:E" & Range("A:A").End(xlDown).Row)
Rng.FormulaR1C1 = "=CONCATENATE(RC[-2],RC[-1])"
Range("E1").Select
ActiveCell.FormulaR1C1 = "Duplicate Status"
'Copy&Paste Values
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Columns("C:D").Select
Selection.Delete Shift:=xlToLeft
Range("C1").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColor = 12632256
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
'Replace "01", "10", "11" with "Duplicate"
Columns("C:C").Select
Selection.Replace What:="10", Replacement:="Duplicate", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="01", Replacement:="Duplicate", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="11", Replacement:="Duplicate", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
'Clear filter
Range("C1").Select
ActiveWorkbook.Worksheets("Inputdata (3)").AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Inputdata (3)").AutoFilter.Sort.SortFields.Add Key _
:=Range("C1"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("Inputdata (3)").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'Final message for user (manually check for remaining duplicates)
Range("A1").Select
MsgBox "Macro Complete! Remaining duplicates require manual editing."
End If
End Sub
How can i make my code go faster?
It's go real slow when the Vlookup is active and i don't know how to make it go fast.
It takes more than 2 minute and it's the same as doing manually.
Sub
Columns("I:I").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("J1").Select
ActiveCell.FormulaR1C1 = "KEY"
Range("I1").Select
ActiveCell.FormulaR1C1 = "CHECK"
Range("J2").Select
ActiveCell.FormulaR1C1 = "=RC[7]&RC[12]&RC[16]"
Range("J2").Select
Selection.AutoFill Destination:=Range("j2:j" & cells(Rows.Count, "a").End(xlUp).Row)
Sheets("CSI Plans Report").Select
Columns("A:A").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Application.Calculation = xlManual
Sheets("CSI Plan ww").Select
Range("J1:N1").Select
Selection.Copy
Sheets("CSI Plans Report").Select
Range("A1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
Selection.AutoFilter
Selection.AutoFilter
Range("A2").Select
ActiveCell.FormulaR1C1 = "=RC[7]&RC[12]&RC[16]"
Range("B2").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-1],'CSI Plan ww'!C[8]:C[12],2,0)"
Range("C2").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-2],'CSI Plan ww'!C[7]:C[11],3,0)"
Range("D2").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-3],'CSI Plan ww'!C[6]:C[10],4,0)"
Range("E2").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-4],'CSI Plan ww'!C[5]:C[9],5,0)"
Range("A2").Select
Selection.AutoFill Destination:=Range("A2:A" & cells(Rows.Count, "f").End(xlUp).Row)
Range("B2").Select
Selection.AutoFill Destination:=Range("b2:b" & cells(Rows.Count, "f").End(xlUp).Row)
Range("C2").Select
Selection.AutoFill Destination:=Range("c2:c" & cells(Rows.Count, "f").End(xlUp).Row)
Range("D2").Select
Selection.AutoFill Destination:=Range("d2:d" & cells(Rows.Count, "f").End(xlUp).Row)
Range("E2").Select
Selection.AutoFill Destination:=Range("e2:e" & cells(Rows.Count, "f").End(xlUp).Row)
Application.Calculation = xlAutomatic
Range("A:E").Select
Range("A:E").Copy
Range("A:E").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Sheets("CSI Plan ww").Select
Range("I2").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[1],'CSI Plans Report'!C[-8]:C[-3],6,0)"
Range("I2").Select
Selection.AutoFill Destination:=Range("i2:i" & cells(Rows.Count, "a").End(xlUp).Row)
Columns("I:J").Copy
Columns("I:J").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
End Sub
This:
Range("A:E").Select
Range("A:E").Copy
Range("A:E").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
can be written as just:
Range("A:E").Value = Range("A:E").Value
to achieve best performance in excel VBA try to not use Select.
instead of
Range("A2").Select
Selection.AutoFill Destination:=Range("A2:A" & cells(Rows.Count, "f").End(xlUp).Row)
better use this
Range("A2").AutoFill Destination:=Range("A2:A" & cells(Rows.Count, "f").End(xlUp).Row)
And best what you can do is to specify sheet too (but it has nothing to do with performance, its just good practice)
Sheets("someSheetName").Range("A2").AutoFill Destination:=Range("A2:A" & cells(Rows.Count, "f").End(xlUp).Row)
And i strongly recomend to use on begining of your sub
application.screenUpdating = false
and this on end of your sub
application.screenUpdating = true
So your excel wont show any change imediately, but at once at the end of the code. (you can read more about screenUpdating almost everywhere on web)
I think this can make you some performance boost.
If you turn off calculation you will save significant periods of time that would otherwise be devoted to calculating formulas that are only oin to be recalculated later.
If you put your formulas into all the rows at once, you do not have to have the calculation on; if you put them into a single cell and fill down you need to run a calculation cycle.
Anytime you can do multiple things at once is better than doing things repeatedly.
Everyone will tell you to read this. It is good advice.
Here's is my contribution to the rewrite process.
Option Explicit
Sub sonic()
Dim lr As Long
'uncomment the next line when you have completed debugging
'appTGGL bTGGL:=False 'see appTGGL helper sub below for details on suspending the enviroment
With Worksheets("CSI Plan ww") '<~~you should know what worksheet you are on!!
'don't insert a sinle column twice - insert 2 columns
.Columns("I:J").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
'never do something twice when you do two things at once
.Range("I1:J1") = Array("CHECK", "KEY")
'write all of the formulas at once
.Range(.Cells(2, "J"), .Cells(Rows.Count, "A").End(xlUp).Offset(0, 9)). _
FormulaR1C1 = "=RC17&RC22&RC26"
End With
With Worksheets("CSI Plans Report")
'again - all at once
.Columns("A:E").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
'no need to select to make a copy
Worksheets("CSI Plan ww").Range("J1:N1").Copy _
Destination:=.Range("A1")
'collect the last row so it doesn't have to be repeatedly looked up
lr = .Cells(Rows.Count, "F").End(xlUp).Row
'each column's formulas all at once
.Range("A2:A" & lr).FormulaR1C1 = "=RC8&RC13&RC17"
.Range("B2:B" & lr).FormulaR1C1 = "=VLOOKUP(RC1,'CSI Plan ww'!C10:C14, 2, 0)"
.Range("C2:C" & lr).FormulaR1C1 = "=VLOOKUP(RC1,'CSI Plan ww'!C10:C14, 3, 0)"
.Range("D2:D" & lr).FormulaR1C1 = "=VLOOKUP(RC1,'CSI Plan ww'!C10:C14, 4, 0)"
.Range("E2:E" & lr).FormulaR1C1 = "=VLOOKUP(RC1,'CSI Plan ww'!C10:C14, 5, 0)"
.Range("A2:E" & lr) = .Range("A2:E" & lr).Value2 'use .Value if any of these are dates
End With
With Worksheets("CSI Plan ww")
.Range(.Cells(2, "I"), .Cells(Rows.Count, "A").End(xlUp).Offset(0, 8)). _
FormulaR1C1 = "=VLOOKUP(RC10,'CSI Plans Report'!C1:C6, 6, 0)"
'collect the last row so it doesn't have to be repeatedly looked up
lr = .Cells(Rows.Count, "J").End(xlUp).Row
'revert formulas to values
.Range("I2:J" & lr) = .Range("I2:J" & lr).Value2 'use .Value if any of these are dates
End With
appTGGL 'turn everything back on
End Sub
Public Sub appTGGL(Optional bTGGL As Boolean = True)
With Application
.ScreenUpdating = bTGGL
.EnableEvents = bTGGL
.DisplayAlerts = bTGGL
.Calculation = IIf(bTGGL, xlCalculationAutomatic, xlCalculationManual)
.CutCopyMode = False
.StatusBar = vbNullString
End With
Debug.Print Timer
End Sub
What I usually do, when writing macros is the following:
Public Sub MyMainMacro
Call OnStart
'Here comes the code
Call OnEnd
End Sub
Public Sub OnStart()
Application.ScreenUpdating = False
Application.Calculation = xlAutomatic
Application.EnableEvents = False
End Sub
Public Sub OnEnd()
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.StatusBar = False
End Sub