The best way to avoid such of errors is to write code in context!
Never use
Select
or
Activate
method, unless you're sure what you doing! Usage of these methods might be the reason of several troubles, such of application hangs, long time of macro execution, etc, and even application crash, because
Select/Activate
method call fires up several events, for example: screen refreshing, cell calculating and many others.
Based on MSDN documentation (
Selecting and Activating Cells | Microsoft Docs[
^]):
Quote:
The macro recorder will often create a macro that uses the Select method and the Selection property. The following Sub procedure was created using the macro recorder, and it shows how Select and Selection work together.
Sub Macro1()
Sheets("Sheet1").Select
Range("A1").Select
ActiveCell.FormulaR1C1 = "Name"
Range("B1").Select
ActiveCell.FormulaR1C1 = "Address"
Range("A1:B1").Select
Selection.Font.Bold = True
End Sub
The following example performs the same task without activating or selecting the worksheet or cells.
Sub Labels()
With Worksheets("Sheet1")
.Range("A1") = "Name"
.Range("B1") = "Address"
.Range("A1:B1").Font.Bold = True
End With
End Sub
But it does not avoid you from errors! Why? Imagine, you have 2 workbooks opened already. In each of them, there's a "
Sheet1
". Where the changes will be made? It depends on what workbook is currently active! So, how to improve above code to be sure that macro will be ecxecuted in correct (desired) workbook? Simple, use variable!
Sub Labels()
Dim wbk As Workbook, wsh As Worksheet
Set wbk = ThisWorkbook
Set wsh = wbk.Worksheets("Sheet1")
With wsh
.Range("A1") = "Name"
.Range("B1") = "Address"
.Range("A1:B1").Font.Bold = True
End With
Set wsh = Nothing
Set wbk = Nothing
End Sub
For further information, please see:
Language reference for Visual Basic for Applications (VBA) | Microsoft Docs[
^]
Excel VBA Performance Coding Best Practices - Microsoft 365 Blog[
^]