Sudden Runtime error '9' on a two year old macro - vba

I'm having issues with a macro that I've been using for months with little issue. The macro is designed to reformat an excel report and insert it into a different workbook within excel. Today, I keep encountering this message:
runtime error '9': subscript out of range
When I select Debug, it highlights this line of code:
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
I am not a coder. I've used the macro button to copy what I do to shorten tasks, but outside copy and pasting the errors and highlighted code into a search engine to see what someone else may have tried, I'm not savvy enough to troubleshoot the logic. The code has always worked, I've done nothing different, but today it's throwing that '9' error. What I have tried is renaming the worksheet to match the code, so basically "Sheet1". I have copied the previous month's worksheet, deleted the old data, and tried running the macro. I even tweaked the code as was suggested by a google find with an individual suffering a similar problem, but I just created a '1004' error because I don't totally understand the logic with xlTop vs. xlDown other than the implied direction. That didn't work so I'm back to square one.
Here is my macro code in total. It's simple enough.
Sub UserStats()
'
' UserStats Macro
'
Application.ScreenUpdating = False 'Doesn't show the macro
run on the screen, speeds up program
'
Cells.Select
With Selection
.VerticalAlignment = xlTop
.WrapText = True
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Columns("A:A").Select
Selection.Delete Shift:=xlToLeft
Columns("B:C").Select
Selection.Delete Shift:=xlToLeft
Columns("C:D").Select
Selection.Delete Shift:=xlToLeft
Columns("D:I").Select
Selection.Delete Shift:=xlToLeft
Rows("1:7").Select
Selection.Delete Shift:=xlUp
Columns("A:D").Select
' SortUserStats Macro
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("A1"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortTextAsNumbers
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A:D")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
' CopyUserStats Macro
Cells.Select
Selection.RowHeight = 12
Range("A2:D2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Workbooks("User Stats Prep.xlsx").Worksheets(1).Activate
Cells(Range("A1").End(xlDown).Row + 1, 1).Select
Selection.Insert Shift:=xlDown
Cells.Select
Selection.RowHeight = 12
Cells(Range("A1").End(xlDown).Row + 1, 1).Select
Application.CutCopyMode = False
ActiveWorkbook.Close SaveChanges:=True
ActiveWorkbook.Close SaveChanges:=False
End Sub
I appreciate any suggestions, otherwise I'll be adding the new data row by row copy and paste style.

I've tried to re-write it so that it doesn't have the excess that the macro recorder generally creates. If this does not work or if it works differently than before, please describe exactly what is wrong/the error
Sub UserStats()
'
' UserStats Macro
'
Application.ScreenUpdating = False 'hides screen, speeds up program
With ActiveWorkbook.Sheets(1)
'format all sheet1 cells
With .Cells
.VerticalAlignment = xlTop
.WrapText = True
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.RowHeight = 12
End With
'delete A:D, D:I, and 1:7
.Columns("A:D").Delete Shift:=xlToLeft
.Columns("D:I").Delete Shift:=xlToLeft
.Rows("1:7").Delete Shift:=xlUp
'Sort UserStats
With .Columns("A:D").Sort
.SortFields.Clear
.SortFields.Add _
key:=Range("A1"), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortTextAsNumbers
.SetRange Range("A:D")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'Copy UserStats
ActiveWorkbook.Sheets(1).Range(Range("A2:D2"), Range("A2:D2").End(xlDown)).copy
End With
With Workbooks("User Stats Prep.xlsx").Worksheets(1)
.Cells.RowHeight = 12
.Cells(Range("A1").End(xlDown).row + 1, 1).Insert Shift:=xlDown
End With
Workbooks("User Stats Prep.xlsx").Close SaveChanges:=True
With Application
.CutCopyMode = False
.ScreenUpdating = True
End With
End Sub

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

Optimizing VBA command to delete rows with blanks

I have a macro where I use the following command to delete all rows where A = blank:
Range("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
The files that I am running through this macro range from 1kb to 300mb.
Doing some pressure testing, it appears that when the file is below 15mb, the command will execute almost instantaneously, resulting in a 20 second to 6 minute run time for the macro.
The second I plug in a file that is larger than 15mb, the macro will get caught on this command for 30-40 minutes.
Does anyone have a nifty trick to optimize this command for large files? If it takes a fraction of a second for a 13mb file, there must be a way to make it take a fraction of a second for a 15mb file and hopefully make it take a fraction of a second for a 300mb file...
Use an AutoFilter Method and temporarily turn off all possible environment parameters.
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
With Worksheets("Sheet1")
If .AutoFilterMode Then .AutoFilterMode = False
With .Cells(1, 1).CurrentRegion
.Cells.Sort Key1:=.Columns(1), Order1:=xlAscending, _
Orientation:=xlTopToBottom, Header:=xlYes
.AutoFilter Field:=1, Criteria1:="="
.Resize(.Rows.Count - 1, 1).Offset(1, 0).EntireRow.Delete
.AutoFilter
End With
End With
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Application.DisplayAlerts = True
Application.ScreenUpdating = True
It has been my experience that even looping through the rows from bottom to top can sometimes beat a call to delete Range.SpecialCells with the xlCellTypeBlanks.
Alright, so, basically riding on Jeeped's suggestions that sorting is the best method to do it, I just decided to index the data and sort:
'Insert column for index
Columns("A:A").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
'Apply index
Range("A1").Select
ActiveCell.FormulaR1C1 = "1"
Range("A2").Select
ActiveCell.FormulaR1C1 = _
"=IF(RC[1]="""","""",R[-1]C+1)"
Range("A3:A" & Range("B" & Rows.Count).End(xlUp).Row).Formula = "=IF(RC[1]="""","""",IF(R[-1]C="""",R[-2]C+1,R[-1]C+1))"
'Sort blanks to bottom
Columns("A:Z").Select
ActiveWorkbook.Worksheets("MasterList").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("MasterList").Sort.SortFields.Add Key:=Columns( _
"A:A"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("Masterlist").Sort
.SetRange Columns("A:Z")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Columns("A").Select
Selection.Delete Shift:=xlToLeft
Which runs like butter. Leaves the non-true-blank rows at the bottom, which is going to drive up the file size a bit, which is not ideal, but id rather run the macro run fast and take a half Meg penalty in file size than sit here waiting 40 minutes when I want to run a large file.

Delete rows that DON'T meet VBA criteria

I have many worksheets with sequential linear xy data that vary in length. The objective is to delete all rows where x data is not divisible by 50. Below is the generated macro that uses a helper column to search for integers to be deleted.
Sub Divis50()
Sheets("VERT SCALES").Select
Range("C2").Select
ActiveCell.FormulaR1C1 = _
"=IF((OR((RIGHT(RC[-2],2)=""50""),(RIGHT(RC[-2],2)=""00""))),""YES"",""NO"")"
Range("C2").Select
Selection.AutoFill Destination:=Range("C2:C6062")
'sort filtered results
Range("C2").Select
ActiveWorkbook.Worksheets("VERT SCALES").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("VERT SCALES").Sort.SortFields.Add Key:=Range("C2") _
, SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("VERT SCALES").Sort
.SetRange Range("A2:C6062")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
' scroll to first no and delete rows
Rows("123:123").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
'sort "A" back to consecutive numbers
Range("A2").Select
ActiveWorkbook.Worksheets("VERT SCALES").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("VERT SCALES").Sort.SortFields.Add Key:=Range("A2") _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("VERT SCALES").Sort
.SetRange Range("A2:C122")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'delete filtered column
Columns("C:C").Select
Selection.Delete Shift:=xlToLeft
End Sub
This will delete rows that don't equal a whole number when divided by 50
Sub Button1_Click()
Dim FrstRng As Range, Lrw As Long
Dim UnionRng As Range
Dim c As Range
Lrw = Cells(Rows.Count, "A").End(xlUp).Row
Set FrstRng = Range("A2:A" & Lrw)
For Each c In FrstRng.Cells
If Int(c / 50) / (c / 50) <> 1 Then
If Not UnionRng Is Nothing Then
Set UnionRng = Union(UnionRng, c) 'adds to the range
Else
Set UnionRng = c
End If
End If
Next c
UnionRng.EntireRow.Delete
End Sub
I would recommend a helper column that flags your data appropriately. Either through formula or VB.
Then use an Autofilter to select the the flags and then delete.
try here for sample code that will delete filtered data.
http://www.mrexcel.com/forum/excel-questions/460513-visual-basic-applications-code-delete-only-rows-filtered.html

Paste Run Time Error 1004

I am trying to copy a set of filtered data from one sheet to the bottom of another sheet. And my code works great except for the first time upon opening the file I get a:
Run Time error 1004
If I quit the debugger and re-run the macro it works great.
Here is my code: noted where the problem occurs.
Sub MoveData_Click()
'Select the filtered alarm data and paste on the master spreadsheet
Sheets("DailyGen").Select
ActiveSheet.UsedRange.Offset(5, 0).SpecialCells _
(xlCellTypeVisible).Copy
Sheets("2015 Master").Select
If ActiveWorkbook.ActiveSheet.FilterMode _
Or ActiveWorkbook.ActiveSheet.AutoFilterMode Then
ActiveWorkbook.ActiveSheet.ShowAllData
End If
Range("C4").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, -2).Range("A1").Select
ActiveSheet.Paste '~~> THIS IS WHERE IT ERRORS
'Sort newest to oldest in the date column
ActiveWorkbook.Worksheets("2015 Master").ListObjects("Table44").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("2015 Master").ListObjects("Table44").Sort.SortFields.Add _
Key:=Range("Table44[[#All],[Active Time]]"), _
SortOn:=xlSortOnValues,
Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("2015 Master").ListObjects("Table44").Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
When you ShowAllData (same as Data->Clear in the Filter section) you are emptying the clipboard and telling Excel to forget about the copied Range. Do it outside of VBA to confirm if you want. Excel loves to empty the clipboard when you edit a cell or do much of anything other than selecting.
To fix, do the Copy after the ShowAllData. In your case, you will have to Select the Worksheet back and forth.
You should generally work to avoid using Select and Activate for your VBA. See this post for details.
Here is the final code with the changes made:
Sub MoveData_Click()
'Select the filtered alarm data and paste on the master spreadsheet
Sheets("2015 Master").Select
If ActiveWorkbook.ActiveSheet.FilterMode Or ActiveWorkbook.ActiveSheet.AutoFilterMode Then
ActiveWorkbook.ActiveSheet.ShowAllData
End If
Sheets("DailyGen").Select
ActiveSheet.UsedRange.Offset(5, 0).SpecialCells _
(xlCellTypeVisible).Copy
Sheets("2015 Master").Select
Range("C4").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, -2).Range("A1").Select
ActiveSheet.Paste
'Sort newest to oldest in the date column
ActiveWorkbook.Worksheets("2015 Master").ListObjects("Table44").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("2015 Master").ListObjects("Table44").Sort.SortFields.Add _
Key:=Range("Table44[[#All],[Active Time]]"), SortOn:=xlSortOnValues, Order _
:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("2015 Master").ListObjects("Table44").Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
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.).