Intermittent Run-time Error 1004 or 13 in Excel 365 - excel

I am at a loss, I have been working to create this macro to help automate an obnoxious process we have at work and the best way to sum up where it is right now is, 60% of the time it works every time!
The macro takes a workbook with the raw data, reorders the columns, filters out data based on certain criteria, creates separate files for each unique value in one of the columns and then attaches that newly created workbook to an email. The email has text and a logo that is placed into the body of the email. Altogether, when the macro finishes running, it will create anywhere from 7 to 11 separate files and emails.
The problem I am having is when I run the macro, 1 of the following 3 things happens:
No issue, it runs perfectly as expected
I get Run-time error '1004':
Method 'SaveAs' of object '_Workbook' failed
This error happens on this line in the code:
ActiveWorkbook.SaveAs FName
I get Run-time error '13':
Type mismatch
This error happens on this line in the code:
OutMailDocument.Range(0, 1).InsertBefore EmailText
I have tried searching several sites and although I can find information about the errors, I can't seem to find anything that has provided any help in fixing the problem.
I do not know where in my macro I went wrong, but I don't understand why sometimes it works just fine and other times I get one of the 2 errors?
Anyway, I am hoping someone may be able to help provide some guidance as to where I am going wrong. I have posted the full code below for reference:
Sub FeeManagement()
Dim CurrentColumn As Integer
Dim Columnheading As String
Dim lastrow As Long
Dim columnorder As Variant, ndx As Integer
Dim found As Range, counter As Integer
Dim wb As Workbook, ws As Worksheet
Dim lr As Long
Dim i As Integer
Dim ar As Variant
Dim j As Long
Dim rng As Range
Dim OutApp As Object
Dim Outmail As Object
Dim OutMailDocumet As Object
Dim OutShape As Excel.Shape
Dim OutWorksheet As Excel.Worksheet
Dim FName As String
Dim FPath As String
Application.ScreenUpdating = False
ActiveSheet.Cells.Interior.Color = xlNone
Range("A1").End(xlDown).Offset(1).Resize(ActiveSheet.UsedRange.Rows.Count).EntireRow.Delete
ActiveSheet.Cells.Font.Name = "Arial"
ActiveSheet.Cells.Font.Size = "10"
Sheets("Sheet1").Copy before:=Sheets(Sheets.Count)
ActiveSheet.Name = "Original"
Worksheets("Sheet1").Activate
'Remove Unwanted Columns
For CurrentColumn = ActiveSheet.UsedRange.Columns.Count To 1 Step -1
Columnheading = ActiveSheet.UsedRange.Cells(1, CurrentColumn).Value
Select Case Columnheading
Case "Auditor", "Auditor ID", "SAI. Nbr", "Pol. Form", "Pol. Nbr", "Aud. Type", "Days todue date", "Pol. Eff Date", "End Date", "Due Date", "Ins. Name", _
"State", "Market Group", "Scheduled Dt.", "Assigned Date", "CI Date", "Aud. System Key"
Case Else
ActiveSheet.Columns(CurrentColumn).Delete
End Select
Next
'Rearrange Columns
columnorder = Array("Auditor", "Assigned Date", "SAI. Nbr", "Ins Name", "State", "Pol. Eff Date", "End Date", "Due Date", "Pol. Form", "Pol. Nbr", "Days to ue date", _
"MarketGroup", "Aud. Type", "Aud. System Key", "Scheduled DT.", "CI Date", "Auditor ID")
counter = 1
For ndx = LBound(columnorder) To UBound(columnorder)
Set found = Rows("1:1").Find(columnorder(ndx), LookIn:=xlValues, Lookat:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
If Not found Is Nothing Then
If found.Column <> counter Then
found.EntireColumn.Cut
Columns(counter).Insert Shift:=xlToRight
Application.CutCopyMode = False
End If
counter = counter + 1
End If
Next ndx
'Add Due Date Columns and Amend Auditor Column
Range("K1").Value = "Days To Due Date"
Columns("L:L").Insert Shift:=xlToRight, _
CopyOrigin:=xlFormatFromLeftOrAbove
Range("L1").Value = "Days Assigned"
Range("S1").Value = "Sched DT Helper"
Range("T1").Value = "CI Helper"
With Sheets("Sheet1")
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
With .Range("K2:K" & lastrow)
.NumberFormat = "0"
End With
With .Range("L2:L" & lastrow)
.Formula = "=-(B2-Today())"
.NumberFormat = "0"
End With
With .Range("S2:S" & lastrow)
.Formula = "=(Q2-Today())"
.NumberFormat = "0"
End With
With .Range("T2:T" & lastrow)
.Formula = "=ABS(Q2-Today())"
.NumberFormat = "0"
End With
End With
Columns("A:B").Insert Shift:=xlToRight, _
CopyOrigin:=xlFormatFromLeftOrAbove
Range("B1").Value = "Auditor"
With Sheets("Sheet1")
lastrow = .Cells(.Rows.Count, "C").End(xlUp).Row
With .Range("B2:B" & lastrow)
.Formula = "=left(C,25)"
End With
End With
Sheets("Sheet1").Columns("B").Copy
Sheets("Sheet1").Columns("A").PasteSpecial Paste:=xlPasteValues
Columns("B:C").EntireColumn.Delete
Worksheets("Sheet1").Columns("A:Z").AutoFit
Worksheets("Sheet1").Range("A1").AutoFilter
'Filter and Delete records based on assigned/due dates & scheduled DT/CI Dates
Set ws = ActiveSheet
On Error Resume Next
ws.ShowAllData
On Error GoTo 0
ws.Range("A1:A20000").AutoFilter Field:=12, Criteria:="<=6"
Application.DisplayAlerts = False
ws.Range("A2:Z20000").SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
ws.ShowAllData
ws.Range("A1:A20000").AutoFilter Field:=11, Criteria:=">=30"
Application.DisplayAlerts = False
ws.Range("A2:Z20000").SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
ws.ShowAllData
ws.Range("A1:A20000").AutoFilter Field:=19, Criteria:=">=-3"
Application.DisplayAlerts = False
ws.Range("A2:Z20000").SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
ws.ShowAllData
ws.Range("A1:A20000").AutoFilter Field:=20, Criteria:="<=6"
Application.DisplayAlerts = False
ws.Range("A2:Z20000").SpecialCells(xlCellTypeVisible).Delete
Application.DisplayAlerts = True
ws.ShowAllData
On Error Resume Next
ws.ShowAllData
On Error GoTo 0
Columns("S:T").EntireColumn.Delete
Columns("P:Q").EntireColumn.Delete
ws.AutoFilter.Sort.SortFields.Clear
ws.AutoFilter.Sort.SortFields.Add2 Key:=Range( _
"K1:K10000"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ws.AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Columns("P:T").Insert Shift:=xlToRight, _
CopyOrigin:=xlFormatFromLeftOrAbove
Range("P1").Value = "New Status"
Range("Q1").Value = "New Status Text"
Range("R1").Value = "Date"
Range("S1").Value = "New Status Date"
Range("T1").Value = "Host Status"
'Create separate worksheets
Set wb = ActiveWorkbook
Set ws = ActiveSheet
lr = ws.Range("A" & Rows.Count).End(xlUp).Row
Set rng = ws.Range("A1:A" & lr)
j = ws.[A1].CurrentRegion.Columns.Count + 1
rng.AdvancedFilter 2, , ws.Cells(1, j), True
ar = ws.Range(ws.Cells(2, j), ws.Cells(Rows.Count, j).End(xlUp))
ws.Columns(j).Clear
For i = 1 To unbound(ar)
rng.AutoFilter 1, ar(i, 1)
If Not Evaluate("=ISREF('" & ar(i, 1) & "'!A10") Then
Sheets.Add(after:=Sheets(Sheets.Count)).Name = ar(i, 1)
Else
Sheets(ar(i, 1)).Move after:=Sheets(Sheets.Count)
End If
ws.Range("A1:A" & lr).Resize(, j - 1).Copy [A1]
Next
ws.AutoFilterMode = False
Sheet("Sheet1").Name = "Modified"
'Create separate files and email
For Each ws In ActiveWorkbook.Worksheets
If ws.Name <> "original" And ws.Name <> "Modified" Then
ws.Copy
Workbooks("Fee Management Macro.xlsm").Sheets("List").Copy before:=Sheets(Sheets.Count)
Range("A2:A13").Select
ActiveWorkbook.Names.Add Name:="StatusList", RefersToR1C1:="=List!R2C1:R12C1"
ActiveWorkbook.Names("StatusList").Comment = ""
Worksheets("Lis").Visible = False
Rows("2:2").Select
ActiveWindow.FreezePanes = True
With ActiveSheet
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
With .Range("S2:S" & lastrow)
.Formula = "=Now()"
End With
With .Range("T2:T") & lastrow
.Formula = "=IFERROR(VLOOKUP(RC[-4],List!C[-19]:[C-18],2,FALSE,"""")"
End With
With .Range("P2:P" & lastrow).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=Statuslist"
.IgnoreBlank = False
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = "Select Status"
.ErrorMessage = "Please select status from the list"
.ShowInput = True
.ShowError = True
End With
With .Range("Q2:Q" & lastrow).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=0", Formula2:="460"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = "Max 460 Characters"
.InputMessage = "If black, do not complete"
.ErrorMessage = "Max 460 Characters"
.ShowInput = True
.ShowError = True
End With
With .Range("R2:R" & lastrow).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlGreater, Formula1:="11/1/2012"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = "Invalid Date"
.InputMessage = "If black, do not complete"
.ErrorMessage = "Please enter a valid date."
.ShowInput = True
.ShowError = True
End With
With .Range("P2:P" & lastrow).Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent4
.TintAndShade = 0.599993896298105
.Patterntintshade = 0
End With
With .Range("Q2:Q" & lastrow).Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.Patterntintshade = 0
End With
With .Range("R2:R" & lastrow).Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.Patterntintshade = 0
End With
With .Range("R2:R" & lastrow).FormatConditions
.Add Type:=xlExpression, Formula1:= _
"=$P2=""Contacted Insured"""
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent4
.TinAndShade = 0.599963377788629
End With
Selection.FormatConditions(1).StopIfTrue = False
End With
With .Range("R2:R" & lastrow).FormatConditions
.Add Type:=xlExpression, Formula1:= _
"=$P2=""Appointment Date Set"""
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent4
.TinAndShade = 0.599963377788629
End With
Selection.FormatConditions(1).StopIfTrue = False
End With
With .Range("R2:R" & lastrow).FormatConditions
.Add Type:=xlExpression, Formula1:= _
"=$P2=""Close Out Submitted"""
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent4
.TinAndShade = 0.599963377788629
End With
Selection.FormatConditions(1).StopIfTrue = False
End With
With .Range("R2:R" & lastrow).FormatConditions
.Add Type:=xlExpression, Formula1:= _
"=$P2=""Contacted Agent"""
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent4
.TinAndShade = 0.599963377788629
End With
Selection.FormatConditions(1).StopIfTrue = False
End With
With .Range("R2:R" & lastrow).FormatConditions
.Add Type:=xlExpression, Formula1:= _
"=$P2=""Other"""
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent4
.TinAndShade = 0.599963377788629
End With
Selection.FormatConditions(1).StopIfTrue = False
End With
End With
Rows("1:1").Select
With Selection
.Font.Bold = True
.Font.Underline = xlUnderlineStyleSingle
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
ActiveSheet.Columns("A:Z").AutoFit
ActiveSheet.Columns("A:Z").HorizontalAlignment = xlCenter
ActiveSheet.Columns("A:Z").VerticalAlignment = xlCenter
ActiveSheet.Range("A1").AutoFilter
With ActiveSheet.Sort
.SortFields.Add Key:=Range("K1"), Order:=xlAscending
.Header = xlYes
.Apply
End With
lcol = Cells(1, Columns.Count).End(xlToLeft).Column
lrow = Cells(Rows.Count, "A").End(xlUp).Row
Range(Cells(1, lcol + 1), Cells(Rows.Count, Columns.Count)).EntireColumn.Hidden = True
Range(Cells(lrow + 1, 1), Cells(Rows.Count, Columns.Count)).EntireRow.Hidden = True
Columns("C").Hidden = True
Columns("O").Hidden = True
Columns("S").Hidden = True
Columns("T").Hidden = True
Columns("U").Hidden = True
Range("A1").Select
Selection.AutoFilter
Range("R:R").Select
Selection.NumberFormat = "yyy-mm-dd;#"
Range("H;H,G:G,F;F,B:B").Select
Selection.NumberFormat = "m/d/yyy"
Range("D:D,A:A").Select
Range("A1").Activate
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Rows("1:1").Select
With Selection
.HorizontalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Columns("A:A").ColumnWidth = 25
Columns("D:D").ColumnWidth = 30
Columns("P:P").ColumnWidth = 30
Columns("Q:Q").ColumnWidth = 35
Columns("R:R").ColumnWidth = 10
Range("P:P,Q:Q,R:R").Locked = False
ActiveSheet.Protect Password:="ChrisBrianGreg2020", Userinterfaceonly:=True
FName = ws.Name & ".xlsx"
ActiveWorkbook.SaveAs FName
Set EmailText = Workbooks("Fee Management Macro.xlsm").Sheets("List").Range("M14")
Set OutWorksheet = Workbooks("Fee Management Macro.xlsm").Sheets("List")
Set OutApp = CreateObject("Outlook.Application")
Set Outmail = OutApp.CreateItem(OutAppOutMailItem)
Set OutMailDocument = Outmail.GetInspector.WordEditor
On Error Resume Next
With Outmail
.To = ""
.CC = ""
.BCC = ""
.Subject = "Weekly Inventory Status Update -" & " " & Date & " " & "-" & " " & ws.Name
.Body = ""
.Attachments.Add ActiveWorkbook.FullName
.Display
End With
On Error GoTo 0
'Copy Images to the email
For Each OutShape In OutWorksheet.Shapes
OutShape.Copy
OutMailDocument.Range(0, 1).Paste
Next
OutMailDocument.Range(0, 1).InsertBefore EmailText
Application.CutCopyMode = False
FName = Application.ActiveWorkbook.FullName
ActiveWorkbook.Saved = True
Application.ActiveWorkbook.ChangeFileAccess xlReadOnly
Kill FName
Application.ActiveWorkbook.Close False
End If
Next ws
Set Outmail = Nothing
Set OutApp = Nothing
Application.ScreenUpdating = True
End Subenter code here

Related

Slow running macro

I've created a macro (using lots of online help) to take data from one sheet, create another sheet, format the data and set up the printer.
Everything works as it should but the macro seems to take a long time to run.
Would someone be able to look at my code and see if I've done something that I shouldn't?
Thanks
Sub Preactor_Sort()
Application.ScreenUpdating = False
'**Copy "Full List" Data into New Sheet**
Sheets("FULL LIST").Select
Range("A8:R8").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets.Add(Before:=Sheets("MASTER")).Name = "Sorted Full"
Range("A1").Select
ActiveSheet.Paste
ActiveWindow.Zoom = 60
'**************************************************
'**Formatting and removing previous conditional formatting**
Cells.FormatConditions.Delete
Cells.Select
With Selection.Font
.Name = "Calibri"
.Size = 9
.Bold = False
.Color = vbBlack
End With
With Selection
.VerticalAlignment = xlCenter
.HorizontalAlignment = xlCenter
.WrapText = True
.Interior.ColorIndex = 0
.RowHeight = 23
End With
Cells.EntireColumn.AutoFit
'***************************************************
'**Deleting Unwanted Columns**
Columns("E:E").Select
Selection.Cut
Columns("C:C").Select
Selection.Insert Shift:=xlToRight
Columns("A:C").Select
Range("A1").Activate
Selection.Delete Shift:=xlToLeft
'***************************************************
'**Rearranging Columns**
Columns("G:H").Select
Selection.Cut
Columns("B:B").Select
Selection.Insert Shift:=xlToRight
Columns("K:L").Select
Selection.Cut
Columns("E:E").Select
Selection.Insert Shift:=xlToRight
'****************************************************
'**Sorting Day/Date**
Columns("C:C").Select
Selection.NumberFormat = "dd/mm/yy hh:mm"
Columns("C:C").EntireColumn.AutoFit
Columns("C:C").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Columns("C:C").Select
Selection.NumberFormat = "General"
'**Find Last Row**
LR = Cells.Find("*", Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row
'**Insert Formula**
Range("C2").Formula = "=TEXT(D2,""ddd"")"
'**Drag Formula down to last row**
Range("C2").AutoFill Range("C2:C" & LR)
Columns("C:C").EntireColumn.AutoFit
'*****************************************************
'**Sorting**
With ActiveSheet.Sort
.SortFields.Add2 Key:=Range("C1"), Order:=xlAscending, CustomOrder:="Mon,Tue,Wed,Thu,Fri,Sat,Sun", DataOption:=xlSortNormal
.SortFields.Add2 Key:=Range("B1"), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:="Make,Discharge,Packing,Wrapping", DataOption:=xlSortNormal
.SetRange Range("A:P")
.Header = xlYes
.Apply
End With
'******************************************************
'**Formatting**
Range("C:C,E:E").Select
With Selection
.Font.Bold = True
End With
Columns("B:B").Select
Selection.ColumnWidth = 10
Columns("F:G").Select
Selection.ColumnWidth = 25
Columns("A:A").Select
Selection.ColumnWidth = 8
Columns("I:J").Select
Selection.ColumnWidth = 5
Columns("L:N").Select
Selection.ColumnWidth = 15
Columns("O:O").Select
Selection.ColumnWidth = 80
Columns("H:H").Select
Selection.ColumnWidth = 40
Columns("K:K").Select
Selection.ColumnWidth = 6
'**Conditional Formatting**
'** Alternating Rows
Dim lastRow As Long
lastRow = Range("A1:P1").End(xlDown).Row
For Each cell In Range("A1:P" & lastRow)
If cell.Row Mod 2 = 1 Then
cell.Interior.ColorIndex = 34 'Light Blue
End If
Next cell
'**Highlighting Operations
Dim cell1 As Range
For Each cell1 In Range("B:B")
If cell1.Value = "Make" Then
cell1.Interior.ColorIndex = 35 'Light Green
ElseIf cell1.Value = "Discharge" Then
cell1.Interior.ColorIndex = 36 'Light Yellow
ElseIf cell1.Value = "Packing" Then
cell1.Interior.ColorIndex = 19 'Light Cream
ElseIf cell1.Value = "Wrapping" Then
cell1.Interior.ColorIndex = 6 'Yellow
ElseIf cell1.Value = "Boxing" Then
cell1.Interior.ColorIndex = 44 'Light Orange
ElseIf cell1.Value = "Oil Phase" Then
cell1.Interior.ColorIndex = 38 'Pink
End If
Next
'**Highlighting Day
Dim cell2 As Range
For Each cell2 In Range("C:C")
If cell2.Value = "Mon" Then
cell2.Interior.ColorIndex = 7 'Pink
ElseIf cell2.Value = "Tue" Then
cell2.Interior.ColorIndex = 4 'Green
ElseIf cell2.Value = "Wed" Then
cell2.Interior.ColorIndex = 6 'Yellow
ElseIf cell2.Value = "Thu" Then
cell2.Interior.ColorIndex = 45 'Orange
ElseIf cell2.Value = "Fri" Then
cell2.Interior.ColorIndex = 33 'Blue
End If
Next
'** Top Bar Colour
Range("A1:P1").Select
With Selection
.Interior.ColorIndex = 15
.Font.Bold = True
End With
'*********************************************************
'** Printer Setup
Application.PrintCommunication = True
With ActiveSheet.PageSetup
.PrintTitleRows = ""
.PrintTitleColumns = ""
End With
ActiveSheet.PageSetup.PrintArea = ""
With ActiveSheet.PageSetup
.LeftMargin = Application.InchesToPoints(0.12)
.RightMargin = Application.InchesToPoints(0.12)
.TopMargin = Application.InchesToPoints(0.16)
.BottomMargin = Application.InchesToPoints(0.16)
.HeaderMargin = Application.InchesToPoints(0.12)
.FooterMargin = Application.InchesToPoints(0.12)
.PrintHeadings = False
.PrintGridlines = False
.PrintComments = xlPrintNoComments
.PrintQuality = 600
.CenterHorizontally = True
.CenterVertically = False
.Orientation = xlLandscape
.Draft = False
.PaperSize = xlPaperA3
.FirstPageNumber = xlAutomatic
.Order = xlDownThenOver
.BlackAndWhite = False
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = False
.PrintErrors = xlPrintErrorsDisplayed
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
.ScaleWithDocHeaderFooter = True
.AlignMarginsHeaderFooter = True
End With
' Application.PrintCommunication = False
End Sub
Trying adding in this, it speeds up by turning off screen updating, events, animations etc, this should speed it up a bit!
At the start of your code add in this sub
Call TurnOffCode
At the end of your code add in this sub
Call TurnOnCode
This is what they should both look like
Sub TurnOffCode() 'Used to turn off settings to make workbook run faster
Application.Calculation = xlCalculationManual 'Set calculations to manual
Application.ScreenUpdating = False 'Turns off screen updating
Application.EnableEvents = False 'Turns off events
Application.EnableAnimations = False 'Turns off animations
Application.DisplayStatusBar = False 'Turns off display status bar
Application.PrintCommunication = False 'Turns off print communications
End Sub
Sub TurnOnCode() 'Used to turn settings back on to normal
Application.Calculation = xlCalculationAutomatic 'Set calculations to automatic
Application.ScreenUpdating = True 'Turns on screen updating
Application.EnableEvents = True 'Turns on events
Application.EnableAnimations = True 'Turns on animations
Application.DisplayStatusBar = True 'Turns on display status bar
Application.PrintCommunication = True 'Turns on print communications
End Sub
However, you should also avoid using selects as well, look at the comment section for a page displaying that information
Thanks for looking at this for me.
I tried the solution that EuanM28 offered and this did marginally increase the speed - from 38sec to around 34sec.
I made a couple of tweaks to my code from
Dim cell1 As Range
For Each cell1 In Range("B:B")
to
Dim cell1 As Range
For Each cell1 In Range("B2:B" & LR) '*LR = last row variable defined earlier in the code
and
Dim cell2 As Range
For Each cell2 In Range("C:C")
to
Dim cell2 As Range
For Each cell2 In Range("C2:C" & LR)
This made a huge difference (34sec to 6sec) I'm guessing because it's no longer cycling through all the rows on the sheet and just the populated ones.
I will have to look into removing .Selects as suggested (didn't realise it causes so many issues!)
Thanks
You have a lot of select statements in your code only to subsequently do something with the selection you can avoid that.
A section like the below
Application.ScreenUpdating = False
'**Copy "Full List" Data into New Sheet**
Sheets("FULL LIST").Select
Range("A8:R8").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets.Add(Before:=Sheets("MASTER")).Name = "Sorted Full"
Range("A1").Select
ActiveSheet.Paste
ActiveWindow.Zoom = 60
'**************************************************
'**Formatting and removing previous conditional formatting**
Cells.FormatConditions.Delete
Cells.Select
With Selection.Font
.Name = "Calibri"
.Size = 9
.Bold = False
.Color = vbBlack
End With
With Selection
.VerticalAlignment = xlCenter
.HorizontalAlignment = xlCenter
.WrapText = True
.Interior.ColorIndex = 0
.RowHeight = 23
End With
Cells.EntireColumn.AutoFit
can be rewritten as:
Dim slc As Range
Dim rng As Range
'Application.ScreenUpdating = False <= be careful with setting update to false as it will not restore if your program encounters an error!
'**Copy "Full List" Data into New Sheet**
Set rng = Sheets(1).Range("A8:R8")
Set slc = Range(rng, rng.End(xlDown))
slc.Copy
Sheets.Add(Before:=Sheets(1)).Name = "Sorted Full"
Sheets("Sorted Full").Paste
ActiveWindow.Zoom = 60
'**************************************************
'**Formatting and removing previous conditional formatting**
Cells.FormatConditions.Delete
With Cells.Font
.Name = "Calibri"
.Size = 9
.Bold = False
.Color = vbBlack
End With
With Cells
.VerticalAlignment = xlCenter
.HorizontalAlignment = xlCenter
.WrapText = True
.Interior.ColorIndex = 0
.RowHeight = 23
End With
Cells.EntireColumn.AutoFit
This will prevent Excel from making the select statement which is causing the slow execution and flickering of the screen.
If you apply that throughout your code you will have a much cleaner execution, without the need to turn off screen updating.
So, if you clean up your code a bit it can look like below:
Mind you, even this has plenty of room for improvement but at least it get's rid of most of the select statements.
This can still be combined with the solution proposed by #EuanM28
However, there are some drawbacks with switching of calculation and screenupdates that may require appropriate ErrorHandling in case your macro encounters an error.
So, combining them would look like the below:
Sub Preactor_Sort()
On Error GoTo ErrorHandler '<= called in case of an Error
Call ToggleCode(False)
Dim slc As Range
Dim rng As Range
'Application.ScreenUpdating = True
'**Copy "Full List" Data into New Sheet**
Set rng = Sheets(1).Range("A8:R8")
Set slc = Range(rng, rng.End(xlDown))
slc.Copy
Sheets.Add(Before:=Sheets(1)).Name = "Sorted Full"
Sheets("Sorted Full").Paste
ActiveWindow.Zoom = 60
'**************************************************
'**Formatting and removing previous conditional formatting**
With Cells
.FormatConditions.Delete
.VerticalAlignment = xlCenter
.HorizontalAlignment = xlCenter
.WrapText = True
.Interior.ColorIndex = 0
.RowHeight = 23
With .Font
.Name = "Calibri"
.Size = 9
.Bold = False
.Color = vbBlack
End With
.EntireColumn.AutoFit
End With
'***************************************************
'**Deleting Unwanted Columns**
columns("E:E").Cut
columns("C:C").Insert Shift:=xlToRight
columns("A:C").Delete Shift:=xlToLeft
'***************************************************
'**Rearranging Columns**
columns("G:H").Cut
columns("B:B").Insert Shift:=xlToRight
columns("K:L").Cut
columns("E:E").Insert Shift:=xlToRight
'****************************************************
'**Sorting Day/Date**
columns("C:C").NumberFormat = "dd/mm/yy hh:mm"
columns("C:C").EntireColumn.AutoFit
columns("C:C").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
columns("C:C").NumberFormat = "General"
'**Find Last Row**
LR = Cells.Find("*", Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).row
'**Insert Formula**
Range("C2").Formula = "=TEXT(D2,""ddd"")"
'**Drag Formula down to last row**
Range("C2").AutoFill Range("C2:C" & LR)
columns("C:C").EntireColumn.AutoFit
'*****************************************************
'**Sorting**
With ActiveSheet.Sort
.SortFields.Add2 Key:=Range("C1"), Order:=xlAscending, CustomOrder:="Mon,Tue,Wed,Thu,Fri,Sat,Sun", DataOption:=xlSortNormal
.SortFields.Add2 Key:=Range("B1"), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:="Make,Discharge,Packing,Wrapping", DataOption:=xlSortNormal
.SetRange Range("A:P")
.Header = xlYes
.Apply
End With
'******************************************************
'**Formatting**
Range("C:C,E:E").Font.Bold = True
columns("B:B").ColumnWidth = 10
columns("F:G").ColumnWidth = 25
columns("A:A").ColumnWidth = 8
columns("I:J").ColumnWidth = 5
columns("L:N").ColumnWidth = 15
columns("O:O").ColumnWidth = 80
columns("H:H").ColumnWidth = 40
columns("K:K").ColumnWidth = 6
'**Conditional Formatting**
'** Alternating Rows
Dim lastRow As Long
lastRow = Range("A1:P1").End(xlDown).row
For Each cell In Range("A1:P" & lastRow)
If cell.row Mod 2 = 1 Then
cell.Interior.ColorIndex = 34 'Light Blue
End If
Next cell
'**Highlighting Operations
Dim cell1 As Range
For Each cell1 In Range("B:B")
If cell1.value = "Make" Then
cell1.Interior.ColorIndex = 35 'Light Green
ElseIf cell1.value = "Discharge" Then
cell1.Interior.ColorIndex = 36 'Light Yellow
ElseIf cell1.value = "Packing" Then
cell1.Interior.ColorIndex = 19 'Light Cream
ElseIf cell1.value = "Wrapping" Then
cell1.Interior.ColorIndex = 6 'Yellow
ElseIf cell1.value = "Boxing" Then
cell1.Interior.ColorIndex = 44 'Light Orange
ElseIf cell1.value = "Oil Phase" Then
cell1.Interior.ColorIndex = 38 'Pink
End If
Next
'**Highlighting Day
Dim cell2 As Range
For Each cell2 In Range("C:C")
If cell2.value = "Mon" Then
cell2.Interior.ColorIndex = 7 'Pink
ElseIf cell2.value = "Tue" Then
cell2.Interior.ColorIndex = 4 'Green
ElseIf cell2.value = "Wed" Then
cell2.Interior.ColorIndex = 6 'Yellow
ElseIf cell2.value = "Thu" Then
cell2.Interior.ColorIndex = 45 'Orange
ElseIf cell2.value = "Fri" Then
cell2.Interior.ColorIndex = 33 'Blue
End If
Next
'** Top Bar Colour
'Range("A1:P1").Select
With Range("A1:P1")
.Interior.ColorIndex = 15
.Font.Bold = True
End With
'*********************************************************
'** Printer Setup
'Application.PrintCommunication = True
With ActiveSheet.PageSetup
.PrintTitleRows = ""
.PrintTitleColumns = ""
End With
ActiveSheet.PageSetup.PrintArea = ""
With ActiveSheet.PageSetup
.LeftMargin = Application.InchesToPoints(0.12)
.RightMargin = Application.InchesToPoints(0.12)
.TopMargin = Application.InchesToPoints(0.16)
.BottomMargin = Application.InchesToPoints(0.16)
.HeaderMargin = Application.InchesToPoints(0.12)
.FooterMargin = Application.InchesToPoints(0.12)
.PrintHeadings = False
.PrintGridlines = False
.PrintComments = xlPrintNoComments
.PrintQuality = 600
.CenterHorizontally = True
.CenterVertically = False
.Orientation = xlLandscape
.Draft = False
.PaperSize = xlPaperA3
.FirstPageNumber = xlAutomatic
.Order = xlDownThenOver
.BlackAndWhite = False
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = False
.PrintErrors = xlPrintErrorsDisplayed
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
.ScaleWithDocHeaderFooter = True
.AlignMarginsHeaderFooter = True
End With
' Application.PrintCommunication = False
Call ToggleCode(True)
Exit Sub
ErrorHandler:
Call ToggleCode(True) '<= this ensures your application get's reset in case of an Error
End Sub
Sub ToggleCode(Optional switch As Boolean = True) 'Used to turn on/off settings to make workbook run faster
If (switch) Then
Application.Calculation = xlCalculationAutomatic 'Set calculations to automatic
Else
Application.Calculation = xlCalculationManual 'Set calculations to manual
End If
Application.ScreenUpdating = switch 'Turns on/off screen updating
Application.EnableEvents = switch 'Turns on/off events
Application.EnableAnimations = switch 'Turns on/off animations
Application.DisplayStatusBar = switch 'Turns on/off display status bar
Application.PrintCommunication = switch 'Turns on/off print communications
End Sub

VBA insert a Row with formula - Unable to Track

Al,
There is a sheet which Macro is written to add a new team along with formula. I would like to change the formula, but i am unable to find it.
The formula is =IFNA(INDEX($F$24:$F$9223,MATCH($A4,$A$24:$A$9223,0)),0)
VBA Code is:
frmAllTeams.Show
'Adding a team to the dtl overview page
Sheets("HLE").Activate
Call unprotect_sheet
Worksheets("HLE").Range("A1").Activate
'Identifying String name
strname = frmAllTeams.cbox1.Value
typenote = frmAllTeams.cbox2.Value
Dim i As Integer, intValueToFind As String
intValueToFind = frmAllTeams.cbox1.Value
For i = 1 To 30 ' Revise the 500 to include all of your values
If Cells(i, 1).Value = intValueToFind Then
MsgBox ("You cannot add a team twice " & i)
Exit Sub
End If
Next i
'Un-Hiding the third row on dtl overview
ActiveSheet.Rows("3:3").Hidden = False
'loop until you find the row "Project Management" and insert line above
Do
ActiveCell.Offset(1, 0).Select
Loop Until ActiveCell = "Project Management"
Rows(Selection.Row - 1).Copy
Rows(Selection.Row).Insert Shift:=xlDown
'name the cell in col A the name of the page
Cells(ActiveCell.Row, 1).Select
ActiveCell.Value = strname
'formatting
Range(ActiveCell, Cells(ActiveCell.Row, ActiveCell.Column + 8)).Select
With Selection.Borders
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
ActiveCell.Offset(0, 8).Select
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlThick
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = xlAutomatic
End With
'go to the team sheet and select col 3-5 on last row and copy
Sheets("HLETeams").Activate
Range("F1:P16").Select
Selection.Copy
'select the col 2 on team line and paste
Sheets("HLE").Select
Range("A1").Select
Dim lastRow As Long
lastRow = ActiveSheet.UsedRange.Rows.Count
'lastRow = lastRow
'MsgBox ("Last Row" & lastRow)
ActiveCell.Offset(lastRow, 0).Select
ActiveCell.PasteSpecial xlPasteAll
Cells.Replace What:="TMxxxx", Replacement:=strname, LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Cells.Replace What:="TEAM: TMxxxx", Replacement:="TEAM: " + strname, LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Dim c As Range
For Each c In Range("A23:I1000").Cells
If c.Value = strname Then
c.EntireRow.Hidden = True
End If
Next c
Worksheets("HLE").Range("A1").Activate
Do
ActiveCell.Offset(1, 0).Select
Loop Until ActiveCell = "TEAM: " & strname
ActiveCell.AddComment typenote
ActiveCell.Offset(2, 2).Select
If typenote = "Mainframe" Then
With Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=mfmod"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
ElseIf typenote = "Distributed" Then
With Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=distmod"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
ElseIf typenote = "Other" Then
ActiveCell.Value = "Other Item"
End If
'Hiding the third row on dtl overview
ActiveSheet.Rows("3:3").Hidden = True
Call protect_sheet
teamcount = teamcount + 1
End Sub
I verified the formula and checked the dependents, but no clue, i just clicked on the dotted line, i didn't see the above said formula.
Where that formula is constructed in VBA code?
EDIT: Please refer below the default row added in the sheet.
As I mentioned in the comments, the formula already exists in row 3, but the row is hidden by default. The code unhides this row and then hides it again. You can accomplish the same thing manually by highlighting rows 2 through 4, right clicking, and clicking Unhide. You should then be able to manually update this formula and hide the row again.
Alternatively, as Siddharth Rout mentioned in the comments, you can press CTRL + F, type =IFNA(INDEX in the Find Box, set the "Within" to "Workbook" and "Look In" to "Formulas", and simply find it. It will directly take you to the cell which has that formula. Then you can edit the formula without unhiding the row.
If you are able to edit the code, I would suggest making some changes to avoid using Select, as discussed here.

VBA code in excel runs slow on Activate event in worksheet. Need to improve performance please

I am trying to protect rows, set dropdown list dynamically on Worksheet_Activate event but my code for 1000 rows takes 15 mins to open the worksheet as it keeps spinning. When I switch between tabs I want to be able to set the dropdowns, disable rows and set color on the rows.Can you tell how I can improve the performance of the worksheet while being able to achieve the mentioned objective.?
Sub DisableOsIs()
On Error Resume Next
Dim NoOfDataRows As Integer
Dim RngOP, RngIL, RngL, RngM, RngN, RngO, RngP, RngQ, RngR, RngLockAll As Range
Dim cell As Range
'ActiveSheet.Unprotect Password:="1234"
'Set NoOfDataRows = ActiveSheet.UsedRange.Rows.Count
Set RngOP = Range("P5:P" & ActiveSheet.UsedRange.Rows.Count)
Set RngIL = Range("I5:I" & ActiveSheet.UsedRange.Rows.Count)
Set RngL = Range("L5:L" & ActiveSheet.UsedRange.Rows.Count)
Set RngM = Range("M5:M" & ActiveSheet.UsedRange.Rows.Count)
Set RngN = Range("N5:N" & ActiveSheet.UsedRange.Rows.Count)
Set RngO = Range("O5:O" & ActiveSheet.UsedRange.Rows.Count)
Set RngP = Range("P5:P" & ActiveSheet.UsedRange.Rows.Count)
Set RngQ = Range("Q5:Q" & ActiveSheet.UsedRange.Rows.Count)
Set RngR = Range("R5:R" & ActiveSheet.UsedRange.Rows.Count)
Set RngLockAll = Range("A" & ActiveSheet.UsedRange.Rows.Count + 1 & ":R" & ActiveSheet.UsedRange.Rows.Count + 1000)
Call SetLEDWattageList(RngL)
Call SetColorTemperatureList(RngM)
Call SetLShield(RngN)
Call SetRemoveSLModifyAList(RngO)
Call SetRemoveSLModifyAList(RngP)
Call SetALengthList(RngQ)
Call SetArmDModList(RngR)
Call DisableLED(RngIL)
Call LockAll(RngLockAll)
End Sub
Sub LockAll(ByVal Target As Range)
On Error Resume Next
ActiveSheet.Unprotect Password:="1234"
With Cells(Target.Row, Target.Column)
.Locked = True
End With
ActiveSheet.Protect Password:="1234"
End Sub
Sub SetLEDWattageList(ByVal Target As Range)
With Cells(Target.Row, Target.Column)
.Locked = False
With .Validation
.Delete
'replace "=A1:A6" with the range the data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=listone!D2:D5"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End With
End Sub
Sub SetColorTemperatureList(ByVal Target As Range)
With Cells(Target.Row, Target.Column)
.Locked = False
With .Validation
.Delete
'replace "=A1:A6" with the range the data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=listone!E2:E3"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End With
End Sub
Sub SetLShield(ByVal Target As Range)
With Cells(Target.Row, Target.Column)
.Locked = False
With .Validation
.Delete
'replace "=A1:A6" with the range the data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=listone!A2:A4"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End With
End Sub
Sub SetRemoveSLModifyAList(ByVal Target As Range)
With Cells(Target.Row, Target.Column)
.Locked = False
With .Validation
.Delete
'replace "=A1:A6" with the range the data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=listone!I2:I3"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End With
End Sub
Sub SetALengthList(ByVal Target As Range)
With Cells(Target.Row, Target.Column)
.Locked = False
With .Validation
.Delete
'replace "=A1:A6" with the range the data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=listone!F2:F4"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End With
End Sub
Sub SetArmDModList(ByVal Target As Range)
With Cells(Target.Row, Target.Column)
.Locked = False
With .Validation
.Delete
'replace "=A1:A6" with the range the data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=listone!G2:G9"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End With
End Sub
'I am passing in a range and checking if the value is LED and color the 'successive columns and protect them.
Sub DisableLED(ByVal Target As Range)
On Error Resume Next
'Check if Target cell in the "Make a selection" range is changed
If Not Intersect(Target, Range("I5:O" & ActiveSheet.UsedRange.Rows.Count)) Is Nothing Then
' ActiveSheet.Cells.Locked = False
If Target.Value = "LED" Then
ActiveSheet.Unprotect Password:="1234"
'Dropdown and error message on cells 2 and 3 columns left of "Make a selection" will be enabled
With Cells(Target.Row, Target.Column + 1)
.Interior.Color = RGB(255, 255, 204)
'.Value = vbNullString
End With
With Cells(Target.Row, Target.Column + 2)
.Interior.Color = RGB(255, 255, 204)
'.Value = vbNullString
End With
With Cells(Target.Row, Target.Column + 3)
.Interior.Color = RGB(217, 217, 217)
.Value = vbNullString
With .Validation
.InCellDropdown = False
.ShowError = False
End With
End With
With Cells(Target.Row, Target.Column + 4)
.Interior.Color = RGB(217, 217, 217)
.Value = vbNullString
With .Validation
.InCellDropdown = False
.ShowError = False
End With
End With
With Cells(Target.Row, Target.Column + 5)
.Interior.Color = RGB(217, 217, 217)
.Value = vbNullString
With .Validation
.InCellDropdown = False
.ShowError = False
End With
End With
With Cells(Target.Row, Target.Column + 6)
.Interior.Color = RGB(217, 217, 217)
.Value = vbNullString
With .Validation
.InCellDropdown = False
.ShowError = False
End With
End With
With Cells(Target.Row, Target.Column + 7)
.Interior.Color = RGB(217, 217, 217)
.Value = vbNullString
With .Validation
.InCellDropdown = False
.ShowError = False
End With
End With
With Cells(Target.Row, Target.Column + 8)
.Interior.Color = RGB(221, 217, 196)
.Value = vbNullString
With .Validation
.InCellDropdown = False
.ShowError = False
End With
End With
With Cells(Target.Row, Target.Column + 9)
.Interior.Color = RGB(221, 217, 196)
.Value = vbNullString
With .Validation
.InCellDropdown = False
.ShowError = False
End With
End With
Target.Locked = False
'Range(Target.Row & ":" & Target.Column).Cells.Locked = False
Cells(Target.Row, Target.Column + 1).Locked = True
Cells(Target.Row, Target.Column + 2).Locked = True
Cells(Target.Row, Target.Column + 3).Locked = True
Cells(Target.Row, Target.Column + 4).Locked = True
Cells(Target.Row, Target.Column + 5).Locked = True
Cells(Target.Row, Target.Column + 6).Locked = True
Cells(Target.Row, Target.Column + 7).Locked = True
Cells(Target.Row, Target.Column + 8).Locked = True
Cells(Target.Row, Target.Column + 9).Locked = True
ActiveSheet.Protect Password:="1234" 'Contents:=True, DrawingObjects:=False
End If
End If
End Sub
At the first glance, your code does not need the functions you call loosing time calling them cell by cell. For instance, the first three calls can be replaced, making the code more efficient, by simple doing that:
Dim RngIL As Range, RngM As Range, RngN As Range, lastRow As Long
Dim sh As Worksheet
Set sh = ActiveSheet 'You have to define sh according to your sheet name
sh.Unprotect "1234"
lastRow = sh.Cells(sh.Rows.count, "M").End(xlUp).Row
Set RngIL = sh.Range("I5:I" & lastRow): RngIL.Locked = False
With RngIL.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=listone!D$2:D$5"
.IgnoreBlank = True
.InCellDropdown = True
.ShowInput = True
.ShowError = True
End With
Set RngM = sh.Range("M5:M" & lastRow): RngM.Locked = False
With RngM.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=listone!E$2:E$3"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ShowInput = True
.ShowError = True
End With
Set RngN = sh.Range("N5:N" & lastRow): RngN.Locked = False
With RngM.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=listone!A$2:A$4"
.IgnoreBlank = True
.InCellDropdown = True
.ShowInput = True
.ShowError = True
End With
'do here the locking procedure if you consider it makes sense...
sh.Protect "1234"
'and so on for all ranges where you must change their cells in the same way...
And a simpler/shorter piece of code doing the same, but un-protecting the sheet:
Sub testSimplified()
Dim RngIL As Range, RngM As Range, RngN As Range, lastRow As Long, cel As Range
Dim sh As Worksheet
Set sh = ActiveSheet 'You have to define sh according to your sheet name
sh.Unprotect "1234"
lastRow = sh.Cells(sh.Rows.count, "M").End(xlUp).Row
Set RngIL = sh.Range("I5:I" & lastRow): RngIL.Locked = False
ChangeValidation RngIL, "=listone!D$2:D$5"
Set RngM = sh.Range("M5:M" & lastRow): RngM.Locked = False
ChangeValidation RngM, "=listone!E$2:E$3"
Set RngN = sh.Range("N5:N" & lastRow): RngN.Locked = False
ChangeValidation RngN, "=listone!A$2:A$4"
'do here the locking procedure...
For Each cel In RngIL
If cel.value = "LED" Then
DisableLED cel, sh
End If
Next
sh.Protect "1234"
End Sub
Sub ChangeValidation(rng As Range, strCondition As String)
With rng.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:=strCondition
.IgnoreBlank = True
.InCellDropdown = True
.ShowInput = True
.ShowError = True
End With
End Sub
Sub DisableLED(ByVal Target As Range, sh As Worksheet)
With sh.Range(Target.Offset(0, 1).Address & ":" & Target.Offset(0, 2).Address)
.Interior.Color = RGB(255, 255, 204)
End With
With sh.Range(Target.Offset(0, 3).Address & ":" & Target.Offset(0, 7).Address)
.Interior.Color = RGB(217, 217, 217)
.Validation.Delete
End With
With sh.Range(Target.Offset(0, 8).Address & ":" & Target.Offset(0, 9).Address)
.Interior.Color = RGB(221, 217, 196)
.Validation.Delete
End With
sh.Range(Target.Offset(0, 1).Address & ":" & Target.Offset(0, 9).Address).Locked = True
End Sub
You must take care of making the validation range absolute (using '$' in front of the validation range row)...
A even better way would be to use named ranges.
No need of un-protect in the called sub due to the fact that the sheet has been un-protected at the beginning of the code.

Macro breaks when ran for the first time of the day

When I run my macro for the first time for the day it fails when it adds another sheet to the file.
Run-time error 1004: That name is already taken. Try a different
one.
My goal:
look for the file within \Downloads
convert the saved file it found from .xls -> .xlsx
delete the original downloaded file
run a bunch of formatting for printing.
When it fails, I close the current file, re-download the file, manually save the file with the needed format & name, delete the download, re-download the file.
After that I can run the macro.
The line that breaks: Sheets.Add(After:=Sheets("Dock Activity Report")).Name = "Cases"
Sub Schedule_macro()
Dim Filename, Pathname, SaveFileName As String
Dim wb As Workbook
Dim UserName As String
UserName = Environ("username")
Pathname = "C:\Users\" & Environ$("username") & "\Downloads\"
Filename = Dir(Pathname & "Dock_Activity_*.xls")
SaveFileName = Dir(Pathname & "dockactivity.xlsx")
Application.DisplayAlerts = False
If Len(Dir(Pathname & "Dock_Activity_*.xls")) > 0 Then
Debug.Print "Filename found, running macro"
Else
MsgBox "You need to download the" & vbNewLine & "Dock Activity Report from the" & vbNewLine & "'Report Run Log' in Lean." & vbNewLine & vbNewLine & "Once downloaded, please rerun the macro", vbCritical, "HiRise Schedule Macro"
Debug.Print "could not find Filename within given Pathname"
Debug.Print "exiting macro"
Exit Sub
End If
Do While Filename <> ""
Set wb = Workbooks.Open(Pathname & Filename)
wb.CheckCompatibility = True
Application.DisplayAlerts = False
wb.SaveAs Filename:="dockactivity", FileFormat:=xlOpenXMLWorkbook
wb.Close SaveChanges:=False
Filename = Dir(Pathname & "Dock_Activity_*.xls")
Filename = Dir()
Loop
Application.DisplayAlerts = True
If Dir(Pathname & "Dock_Activity_*.xls") <> "" Then
kill (Pathname & "Dock_Activity_*.xls")
End If
Debug.Print "looking for SaveFileName within given Pathname"
Set wb = Workbooks.Open(Pathname & "dockactivity.xlsx")
Debug.Print "SaveFileName found, opening file"
Windows("dockactivity.xlsx").Activate
Rows("1:21").Delete Shift:=xlUp
Range("A:B,D:F,H:N,S:S,U:V,X:Y,AB:AK,AM:BA").Delete Shift:=xlToLeft
Columns("H:H").Cut
Columns("A:A").Insert Shift:=xlToRight
Columns("K:K").Cut
Columns("G:G").Insert Shift:=xlToRight
Columns("J:K").Copy
Range("L1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
Columns("J:K").ClearContents
Range("J1").FormulaR1C1 = "Trailer Number"
Range("K1").FormulaR1C1 = "Arrival Time"
Columns("G:M").Copy
Range("N1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
Selection.ClearContents
Range("N1").FormulaR1C1 = "Door"
Range("O1").FormulaR1C1 = "Ship Rail"
Range("P1").FormulaR1C1 = "Staged"
Range("Q1").FormulaR1C1 = "Check If Loaded"
Range("R1").FormulaR1C1 = "Case Picks"
Range("S1").FormulaR1C1 = "Layer Picks"
Range("T1").FormulaR1C1 = "Check if Released by Pool"
Debug.Print "1:1 table headers complete"
Columns("A:B").ColumnWidth = 17.71
Columns("C:C").ColumnWidth = 19.14
Columns("D:D").ColumnWidth = 25.71
Columns("E:E").ColumnWidth = 14.41
Columns("F:F").ColumnWidth = 10.71
Columns("G:G").ColumnWidth = 30.29
Columns("H:H").ColumnWidth = 9.43
Columns("I:I").ColumnWidth = 13.71
Columns("J:J").ColumnWidth = 26.14
Columns("K:L").ColumnWidth = 23.57
Columns("M:M").ColumnWidth = 46
Columns("N:S").ColumnWidth = 15
Columns("T:T").ColumnWidth = 12.86
Debug.Print "column resizing complete"
Cells.Select
With Selection.Font
.Name = "Arial"
.Size = 14
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.TintAndShade = 0
.ThemeFont = xlThemeFontNone
End With
Rows("1:1").RowHeight = 75
Rows("2:150").RowHeight = 55
' #############################################################################
Sheets.Add(After:=Sheets("Dock Activity Report")).Name = "Cases"
Sheets.Add(After:=Sheets("Cases")).Name = "Layers"
' #############################################################################
Sheets("Dock Activity Report").Range("R2:R150").FormulaR1C1 = "=VLOOKUP(RC[-17],Cases!C[-13]:C[-12],2,FALSE)"
Sheets("Dock Activity Report").Range("S2:S150").FormulaR1C1 = "=VLOOKUP(RC[-18],Layers!C[-15]:C[-14],2,FALSE)"
Worksheets("Dock Activity Report").Select
Range("A2:T150").Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$C2=""Live Trailer"""
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
End With
Range("B2:B150").Select
ActiveWorkbook.Worksheets("Dock Activity Report").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Dock Activity Report").Sort.SortFields.Add Key:= _
Range("B2"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("Dock Activity Report").Sort
.SetRange Range("A1:T150")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
ActiveWorkbook.Worksheets("Dock Activity Report").Select
Columns("A:A").Copy
Columns("B:B").Insert Shift:=xlToRight
Range("B2").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=IFERROR(RC[-1]*1,TRIM(RC[-1]))"
Range("B3").Select
Range("B2").Select
Selection.AutoFill Destination:=Range("B2:B150"), Type:=xlFillDefault
Range("B2:B150").Select
Columns("B:B").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Columns("B:B").Select
Application.CutCopyMode = False
Selection.Delete Shift:=xlToLeft
Debug.Print "A:A value reformat complete"
Sheets("Dock Activity Report").Select
Columns("A:T").Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=COUNTA($A1:$F1)>0"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Borders
.LineStyle = xlContinuous
.TintAndShade = 0
.Weight = xlThin
End With
Selection.FormatConditions(1).StopIfTrue = False
Debug.Print "cell borders added"
Dim r As Long
Dim LastRow As Long
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
For r = LastRow To 1 Step -1
If Cells(r, 1) = 0 Then
Rows(r).Delete
End If
Next r
Range("A1").Select
Sheets("Cases").Range("E2:E300").FormulaR1C1 = "=VALUE(TRIM(CLEAN(RC[-4])))"
Sheets("Cases").Range("F2:F300").FormulaR1C1 = "=RC[-2]"
Sheets("Cases").Columns("E:F").EntireColumn.Hidden = True
Sheets("Layers").Range("D2:D300").FormulaR1C1 = "=VALUE(TRIM(CLEAN(RC[-3])))"
Sheets("Layers").Range("E2:E300").FormulaR1C1 = "=RC[-2]"
Sheets("Layers").Columns("D:E").EntireColumn.Hidden = True
Sheets("Dock Activity Report").Range("A1").Select
Application.DisplayAlerts = False
ActiveWorkbook.Save
Application.DisplayAlerts = True
MsgBox "All Finished!", vbInformation, "HiRise Schedule"
ActiveWorkbook.Save
End Sub
That is because there is already a sheet with that name.
Add this code and it will be ok.
On Error Resume Next
Application.DisplayAlerts = False
Sheets("Cases").Delete
Application.DisplayAlerts = True
On Error GoTo 0
Sheets.Add(After:=Sheets("Dock Activity Report")).Name = "Cases"
TIP: Avoid the use of .Select/Activate. Work with Objects. You may want to see How to avoid using Select in Excel VBA. It will be easy to manage the code as well.

How to speed up macros/hide screen while code is running

I have a series of macros that format a single sheet and import values from hardcoded arrays if a match is found. The code is well commented. Macros are called in the order that they are listed. I would like your opinion on how to speed up the code or hide the sheet from view, so that the user doesn’t see any manipulation on the screen while Macro is running. Thank you very much.
Sub MacroA()
'
' addcolumn Macro
'
Dim sht As Worksheet
Dim LastRow As Long
Set sht = ThisWorkbook.Worksheets("QC")
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
Application.EnableEvents = False
Application.ScreenUpdating = False
'~~~~~> error checking
If Sheet2.Range("A2").Value = "" Then
'MsgBox " There are no QC samples on this run"
Exit Sub
End If
Worksheets("QC").Select
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~copy down value from A2
sht.Range("A2").Value2 = "HD200_QC"
'copy QC name down
Range("A2").Select
Selection.Copy
Range("A2:A" & LastRow).Select
ActiveSheet.Paste
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Columns(3).EntireColumn.Delete 'removes extra column for interpretation
Columns("H:H").Select '\\add one column
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Columns("G:G").Select 'convert formulas to values
Selection.Copy
Columns("G:G").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
With sht
.Range("A1").Value2 = "QC"
.Range("G1").Value2 = "AAchange"
.Range("H1").Value2 = "Standard"
End With
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Sub deleteIrrelevantColumns() 'delete all columns except for the ones with a certain name.
Dim currentColumn As Integer
Dim columnHeading As String
Application.EnableEvents = False
Application.ScreenUpdating = False
'ActiveSheet.Columns("L").Delete
For currentColumn = ActiveSheet.UsedRange.Columns.Count To 1 Step -1
columnHeading = ActiveSheet.UsedRange.Cells(1, currentColumn).Value
'CHECK WHETHER TO KEEP THE COLUMN
Select Case columnHeading
Case "QC", "gene", "exon", "cDNA", "AAchange", "%Alt", "Standard"
'Do nothing
Case Else
'Delete if the cell doesn't contain these
If InStr(1, _
ActiveSheet.UsedRange.Cells(1, currentColumn).Value, _
"Matreshkaper", vbBinaryCompare) = 0 Then
ActiveSheet.Columns(currentColumn).Delete
End If
End Select
Next
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
Sub PopulateStandard()
'PURPOSE: Filter on specific values
Dim rng As Range
Dim LastRow, i As Long
Dim GeneCheck As String
Dim vArr As Variant
Dim x
Dim y
'wsQC.Select
Worksheets("QC").Select
LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
Application.EnableEvents = False
Application.ScreenUpdating = False
vArr = Array(Array("HD300_QCL861Q", "5"), _
Array("HD300_QCE746_E749del", "5"), _
Array("HD300_QCL858R", "5"), _
Array("HD300_QCT790M", "5"), _
Array("HD300_QCG719S", "5"), _
Array("HD200_QCV600E", "10.5"), _
Array("HD200_QCD816V", "10"), _
Array("HD200_QCE746_E749del", "2"), _
Array("HD200_QCL858R", "3"), _
Array("HD200_QCT790M", "1"), _
Array("HD200_QCG719S", "24.5"), _
Array("HD200_QCG13D", "15"), _
Array("HD200_QCG12D", "6"), _
Array("HD200_QCQ61K", "12.5"), _
Array("HD200_QCH1047R", "17.5"), _
Array("HD200_QCE545K", "9"))
For i = 2 To LastRow
GeneCheck = Right(Cells(i, 1).Value, 8) & Cells(i, 5).Value
'//Tell VBA to ignore an error and continue (ie if it can't find the value)
On Error Resume Next
'//Assign the result of your calculation to a variable that VBA can query
x = WorksheetFunction.VLookup(GeneCheck, vArr, 2, False)
'//if Vlookup finds the value, then paste it into the required column
If Err = 0 Then
Cells(i, 6).Value = x
Else
End If
'//resets to normal error handling
On Error GoTo 0
Next
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Sub MissingValues()
Dim zArr As Variant
Dim yArr As Variant
Dim LastRow As Long
Dim LastRow2 As Long
Dim sht As Worksheet
Set sht = ThisWorkbook.Worksheets("QC")
Application.EnableEvents = False
Application.ScreenUpdating = False
yArr = Array(Array("EGFR", "", "", "L861Q", "5"), _
Array("EGFR", "", "", "KELRE745delinsK", "5"), _
Array("EGFR", "", "", "L858R", "5"), _
Array("EGFR", "", "", "T790M", "5"), _
Array("EGFR", "", "", "G719S", "5"))
zArr = Array(Array("BRAF", "", "", "V600E", "10.5"), _
Array("KIT", "", "", "D816V", "10"), _
Array("EGFR", "", "", "KELRE745delinsK", "2"), _
Array("EGFR", "", "", "L858R", "3"), _
Array("EGFR", "", "", "T790M", "1"), _
Array("EGFR", "", "", "G719S", "24.5"), _
Array("KRAS", "", "", "G13D", "15"), _
Array("KRAS", "", "", "G12D", "6"), _
Array("NRAS", "", "", "Q61K", "12.5"), _
Array("PIK3CA", "", "", "H1047R", "17.5"), _
Array("PIK3CA", "", "", "E545K", "9"))
'Ctrl + Shift + End
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
If InStr(1, ActiveSheet.Range("A2").Value, "HD200") > 0 Then
Sheets("QC").Select
Worksheets("QC").Range("B" & LastRow + 2 & ":F" & LastRow + 12).Value = Application.Index(zArr, 0)
ElseIf InStr(1, ActiveSheet.Range("A2").Value, "HD300") > 0 Then
Sheets("QC").Select
Worksheets("QC").Range("B" & LastRow + 2 & ":F" & LastRow + 6).Value = Application.Index(yArr, 0)
End If
LastRow2 = sht.Cells(sht.Rows.Count, "B").End(xlUp).Row
'MsgBox (LastRow2)
Columns("B:G").Select
ActiveSheet.Range("$A$1:$G$" & LastRow2).RemoveDuplicates Columns:=Array(2, 5, 6), _
Header:=xlYes
Range("A1").Select
With Worksheets("QC")
'lRow = .Range("A" & Rows.Count).End(xlUp).Row
.Cells(LastRow + 1, 1).Value = "Removed Low Alts."
End With
Columns("A:A").Select
Range(Selection, Selection.End(xlToRight)).Select
Columns("A:G").EntireColumn.AutoFit
Range("A1").Select
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
ActiveWorkbook.Worksheets("QC").Sort.SortFields.clear
ActiveWorkbook.Worksheets("QC").Sort.SortFields.Add Key:=Range("F2:F" & LastRow), _
SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("QC").Sort
.SetRange Range("A1:G" & LastRow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
' Adds a grid around the data
LastRow2 = sht.Cells(sht.Rows.Count, "B").End(xlUp).Row
Range("A2:G" & LastRow2).Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.colorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.colorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.colorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.colorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.colorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.colorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
'~~~~> add yellow color
Range("F2:G" & LastRow2).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 12514808
.TintAndShade = 0
.PatternTintAndShade = 0
End With
'~~~~> make font red
Range("F2:F" & LastRow2).Select
With Selection.Font
.Color = -16777024
.TintAndShade = 0
End With
Range("A1").Select
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Sub Filter()
'PURPOSE: Filter on specific values
Dim rng As Range
Dim LastRow, i As Long
Dim GeneCheck As String
Dim vArr As Variant
Dim x
Dim y
Dim FilterField As Variant
'wsQC.Select
Worksheets("QC").Select
LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
Application.EnableEvents = False
Application.ScreenUpdating = False
Set rng = ActiveSheet.Range("A1:AC" & LastRow)
FilterField = WorksheetFunction.Match("AAchange", rng.Rows(1), 0)
'Turn on filter if not already turned on
'If ActiveSheet.AutoFilterMode = False Then rng.AutoFilter
If InStr(1, ActiveSheet.Range("A2").Value, "HD200") > 0 Then
rng.AutoFilter
'Filter Specific Countries
rng.AutoFilter Field:=FilterField, Criteria1:=Array( _
"V600E", "KELRE745delinsK", "T790M", "G719S", "D816V", "G13D", "G12D", "Q61K", "H1047R", "L858R", "E545K"), Operator:=xlFilterValues
Else 'If InStr(1, ActiveSheet.Range("A2").Value, "HD300") > 0 Then
rng.AutoFilter
rng.AutoFilter Field:=FilterField, Criteria1:=Array( _
"L861Q", "KELRE745delinsK", "L858R", "T790M", "G719S"), Operator:=xlFilterValues
End If
'End If
'~~~> format top row.
Range("A1").Select 'format top row
Range(Selection, Selection.End(xlToRight)).Select
With Selection.Interior
.Pattern = xlPatternLinearGradient
.Gradient.Degree = 90
.Gradient.ColorStops.clear
End With
With Selection.Interior.Gradient.ColorStops.Add(0)
.Color = 11298378
.TintAndShade = 0
End With
With Selection.Interior.Gradient.ColorStops.Add(1)
.Color = 5384228
.TintAndShade = 0
End With
With Selection.Font
.ThemeColor = xlThemeColorDark1
.TintAndShade = 0
End With
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Just this bit of code to add borders could speed things up.
LastRow2 = sht.Cells(sht.Rows.Count, "B").End(xlUp).Row
Range("A2:G" & LastRow2).Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.colorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.colorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.colorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.colorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.colorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.colorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
Can be replaced with this. Edit your code to remove the selects.
Dim sht As Worksheet
Dim LastRow As Long
Set sht = ThisWorkbook.Worksheets("QC")
Dim rng As Range
LastRow2 = sht.Cells(sht.Rows.Count, "B").End(xlUp).Row
Set rng = sht.Range("A2:G" & LastRow2)
With rng.Borders
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With

Resources