I'm having trouble trying to use with instead of .select when writing code to insert a new row. I have been told multiple times that .select is not to be used as it is much slower.
My macro creates a new row but deletes the contents in the row below and copies the formatting of the row above which never happened when I was using .select. This also means that the increasing number in cell B11 is not correct as it starts again from 1 due to the cleared contents below.
Sub New_Entry()
Application.ScreenUpdating = False
Application.EnableEvents = False
Dim rng As Range
Set rng = Range("B11:AB11")
With rng
.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End With
Application.CutCopyMode = False
With rng
.ClearContents
.Interior.ColorIndex = xlNone
.Borders.LineStyle = xlContinuous
End With
With Range("B11")
.Value = Range("B12") + 1
End With
With rng
.Font.Bold = False
.Font.ColorIndex = xlAutomatic
.Font.TintAndShade = 0
End With
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Any help would be appreciated, thanks!
As far as I can see you have two questions:
1. Why does this delete the content?
That is because your With rng takes Set rng = Range("B11:AB11") and does .ClearContents to it at the same time as it inserts a row.
You can check this by switching around the order of your code.
All With statements with the same condition always run at the same time.
2. Why is the formatting copied?
The format isn't actually copied, you are formatting every line you create with .Borders.LineStyle = xlContinuous.
This should work:
Sub New_Entry()
Application.ScreenUpdating = False
Application.EnableEvents = False
Dim rng As Range
Set rng = Range("B11:AB11")
With rng
'.ClearContents
.Interior.ColorIndex = xlNone
'.Borders.LineStyle = xlContinuous
'End With
'With rng
.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End With
Application.CutCopyMode = False
With Range("B11")
.Value = Range("B12") + 1
End With
With rng
.Font.Bold = False
.Font.ColorIndex = xlAutomatic
.Font.TintAndShade = 0
End With
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
.Select is slower because it runs code line by line.
The range "rng" seems to shift down after the insert. Here is the route I would take:
Sub New_Entry()
Application.ScreenUpdating = False
Application.EnableEvents = False
Range("B11:AB11").Insert Shift:=xlDown
Range("B11").Value = Range("B12") + 1
With Range("B11:AB11")
.Interior.ColorIndex = xlNone
.Borders.LineStyle = xlContinuous
.Font.Bold = False
.Font.ColorIndex = xlAutomatic
.Font.TintAndShade = 0
End With
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Related
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
I have a table from Column A to Column M where I will input new row of data everyday. I have a Macro which enables me to highlight selected cells in Column I and sum to column J including merge. However, I would like to add "Thick Bottom Border" from Column A to Column M after triggering the Macro. In addition, it would be a better if the Selection Cells will go to Column C 1 row below for faster data input.
Image below for your reference:
Expected Result:
Sub Macro6()
'
' Macro6 Macro
'
' Keyboard Shortcut: Ctrl+l
Dim mergeCells As Range
Set mergeCells = selection.Offset(, 1)
With mergeCells
.Merge
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.Formula = "=SUM(" & selection.Address & ")"
End With
End Sub
If you run the macro recorder, and add your border, you should get something along the lines of:
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
And now that you know how to add a border, you just need to specify the range.
One way would be to get the last row of your selection. Which can be done by looking at the starting row, the amount of selected rows, and then subtracting one, since we are essentially counting the first row twice.
lrow = Selection.Row + Selection.Rows.Count - 1
Since the range in where you want this will always be the same, it's easy enough to hard-code it, by concatenating the Column and the row, using &.
Sub Macro6()
'
' Macro6 Macro
'
' Keyboard Shortcut: Ctrl+l
Dim lRow as Long
Dim mergeCells As Range
Set mergeCells = selection.Offset(, 1)
With mergeCells
.Merge
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.Formula = "=SUM(" & selection.Address & ")"
End With
lRow = Selection.Row + Selection.Rows.Count - 1
With Range("A" & lRow, "M" & lRow).Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
End Sub
I have wrote a code which paste the borders on Sheet1 used range whenever i make an entry and same for Sheet2. The data is cover by borders automatically.
I have been facing an error (select method of range class failed) if i apply the both codes in sheet1 and Sheet2.
If i use the code for single sheet it works.
Is there an way to merge these both codes OR any way to make it work OR to do this thing in an efficient way.
Any help will be appreciated.
Sheet1
Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False
Dim lngLstCol As Long, lngLstRow As Long
lngLstRow = Sheet1.UsedRange.Rows.Count
lngLstCol = Sheet1.UsedRange.Columns.Count
For Each rngCell In Range("A2:A" & lngLstRow)
If rngCell.Value > "" Then
r = rngCell.Row
c = rngCell.Column
Range(Cells(r, c), Cells(r, lngLstCol)).Select
With Selection.Borders
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Font
.Name = "Calibri"
.Size = 10
End With
End If
Next
Application.ScreenUpdating = True
End Sub
Sheet2
Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False
lngLstRow = Worksheets("Current Stock").UsedRange.Rows.Count
lngLstCol = Worksheets("Current Stock").UsedRange.Columns.Count
For Each rngCell In Range("A2:A" & lngLstRow)
If rngCell.Value > "" Then
r = rngCell.Row
c = rngCell.Column
Range(Cells(r, c), Cells(r, lngLstCol)).Select
With Selection.Borders
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Font
.Name = "Calibri"
.Size = 10
End With
End If
Next
Application.ScreenUpdating = True
End Sub
If i use the code for single sheet it works.
This might be because you are not fully qualifying ranges: If you don not qualify Cells and Range it works on the activesheet so you need to pre-qualify wuith the sheet that contains the ranges so target.parent.Cells and target.parent.range might solve your problem
Is there an way to merge these both code
Define a sub which takes a worksheet as a parameter
sub do_the_work(byref ws as worksheet)
Application.ScreenUpdating = False
lngLstRow = Worksheets("Current Stock").UsedRange.Rows.Count
lngLstCol = Worksheets("Current Stock").UsedRange.Columns.Count
For Each rngCell In ws.Range("A2:A" & lngLstRow)
If rngCell.Value > "" Then
r = rngCell.Row
c = rngCell.Column
ws.Range(ws.Cells(r, c), ws.Cells(r, lngLstCol)).Select
With Selection.Borders
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Font
.Name = "Calibri"
.Size = 10
End With
End If
Next
Application.ScreenUpdating = True
end sub
then inside the worksheet.change call
Private Sub Worksheet_Change(ByVal Target As Range)
do_the_work target.parent
End Sub
Improvement removing select
With ws.Range(ws.Cells(r, c), ws.Cells(r, lngLstCol))
With .Borders
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With .Font
.Name = "Calibri"
.Size = 10
End With
End With
How could I change this code so I don't have to first select all the cells? I would like this to work without selecting the cells first, instead, it should work with the worksheet("Phase").
Option Explicit
Sub RemoveFormats()
'Remove all formatting except changes in font and font size
'Turn off screen updates to improve performance
Application.ScreenUpdating = False
With Selection
'Remove cell colors
.Interior.ColorIndex = xlNone
'Remove all cell borders
.Borders(xlDiagonalDown).LineStyle = xlNone
.Borders(xlDiagonalUp).LineStyle = xlNone
.Borders(xlEdgeLeft).LineStyle = xlNone
.Borders(xlEdgeTop).LineStyle = xlNone
.Borders(xlEdgeBottom).LineStyle = xlNone
.Borders(xlEdgeRight).LineStyle = xlNone
.Borders(xlInsideVertical).LineStyle = xlNone
.Borders(xlInsideHorizontal).LineStyle = xlNone
'Remove all special font properties and formatting
With .Font
.FontStyle = "Regular"
.Strikethrough = False
.Superscript = False
.Subscript = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
End With
End With
'Restore screen updates to display changes
Application.ScreenUpdating = True
End Sub
If you are talking about applying your macro to the entire sheet called "Phase", you would simply reference the Worksheet.Cells instead of the Selection object property to get all cells of a worksheet.
Sub YourMethod()
'// code...
With ThisWorkbook.Worksheets("Phase").Cells
'Remove cell colors
.Interior.ColorIndex = xlNone
'// more code....
End With
end Sub
I have a set of data in columns A to Z, if any cells in Column F is bolded, shall call to bold the entire row.
For example, F3 and F80 is bolded. A3:Z3 and A80:Z80 shall be bolded. My code only works until bolding cells in column F, can't proceed to bold the entire row.
Sub Bold()
Dim CheckRange As Range
Dim cell As Range
With ActiveSheet
Set CheckRange = .Range("F2:F" & .Cells(.Rows.Count, "F").End(xlUp).Row)
End With
With CheckRange
.FormatConditions.Delete
.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreaterEqual, formula1:="1000000"
With .FormatConditions(1)
.Font.Bold = True
.StopIfTrue = False
End With
For Each cell In CheckRange
If cell(cell.Row, 6).Font.Bold = True Then
cell.EntireRow.Font.Bold = True
End If
Next
End Sub
Any help is much appreciated.
May be using a formula for the conditional formatting is better
Sub Bold()
With ActiveSheet.UsedRange
.FormatConditions.Delete
.Range("A1:Z" & .Cells(Rows.Count, 6).End(xlUp).Row).FormatConditions.Add Type:=xlExpression, Formula1:="=$F1>=1000000"
With .FormatConditions(1)
.Font.Bold = True
.StopIfTrue = False
End With
End With
End Sub
Or to adhere to your code you can use offset and resize in the loop
Sub Bold()
Dim checkRange As Range, cell As Range
With ActiveSheet
Set checkRange = .Range("F2:F" & .Cells(.Rows.Count, "F").End(xlUp).Row)
End With
With checkRange
.FormatConditions.Delete
.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreaterEqual, Formula1:="1000000"
With .FormatConditions(1)
.Font.Bold = True
.StopIfTrue = False
End With
End With
For Each cell In checkRange
If cell.DisplayFormat.Font.Bold = True Then
cell.Offset(, -5).Resize(1, 26).Font.Bold = True
End If
Next cell
End Sub
The code sample is missing an end with after the first one to run.
Other than that, the issue is here: If cell(cell.Row, 6).Font.Bold
cell is already a Range type reference to the cell you need, so you don't need to look up anything, in fact doing that causes it to point elsewhere with the cell function: for example this is from the watch window, note the value difference:
Watch : : cell.Address : "$F$2" : String : Module1.Bold
Watch : : cell(cell.Row, 6).Address : "$K$3" : Variant/String : Module1.Bold
This is the full code:
Sub Bold()
Dim CheckRange As Range
Dim cell As Range
With ActiveSheet
Set CheckRange = .Range("F2:F" & .Cells(.Rows.Count, "F").End(xlUp).Row)
End With
With CheckRange
.FormatConditions.Delete
.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreaterEqual, Formula1:="1000000"
With .FormatConditions(1)
.Font.Bold = True
.StopIfTrue = False
End With
End With
For Each cell In CheckRange
If cell.Font.Bold = True Then
cell.EntireRow.Font.Bold = True
End If
Next
End Sub