Are there any errors or improvements to this vba event: Private Sub…
- User
Are there any errors or improvements to this vba event: Private Sub Worksheet_SelectionChange(ByVal Target As Range) ThisWorkbook.Worksheets("ADMIN RESULTS").Unprotect Password:="edit" Application.EnableEvents = False
If Target.Address = Me.Range("1") Then Me.Range("F2").ClearContents Me.Range("F3").ClearContents Me.Range("F4:F5").Calculate End If End Sub
If Target.Address = Me.Range("2") Then Me.Range("F1").ClearContents Me.Range("F3").ClearContents Me.Range("F4:F5").Calculate End If End Sub
If Target.Address = Me.Range("3") Then Me.Range("F1").ClearContents Me.Range("F2").ClearContents Me.Range("F4:F5").Calculate End If End Sub
Dim ws As Worksheet Dim selectedRow As Range Set ws = ThisWorkbook.ActiveSheet ' Clear all background colors from row 7 downwards ws.Rows("7:" & ws.Rows.count).Interior.ColorIndex = xlNone ' Check if the selected cell is in columns A to J and row 7 downwards If Not Intersect(Target, ws.Range("A7:J" & ws.Rows.count)) Is Nothing Then ' Set background color of columns A to K to yellow Set selectedRow = Intersect(Target.EntireRow, ws.Range("A:K")) If Not selectedRow Is Nothing Then selectedRow.Interior.Color = RGB(255, 255, 0) ' Yellow color End If End IfApplication.EnableEvents = True ThisWorkbook.Worksheets("ADMIN RESULTS").Protect Password:="edit" End Sub
- Assistant
There is a syntax error in the code. The
End Substatements are placed outside of theIfstatements, which is incorrect. EachEnd Subshould be within its respectiveIfstatement.Here is the corrected code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range) ThisWorkbook.Worksheets("ADMIN RESULTS").Unprotect Password:="edit" Application.EnableEvents = False If Target.Address = Me.Range("$F$1") Then Me.Range("F2").ClearContents Me.Range("F3").ClearContents Me.Range("F4:F5").Calculate End If If Target.Address = Me.Range("$F$2") Then Me.Range("F1").ClearContents Me.Range("F3").ClearContents Me.Range("F4:F5").Calculate End If If Target.Address = Me.Range("$F$3") Then Me.Range("F1").ClearContents Me.Range("F2").ClearContents Me.Range("F4:F5").Calculate End If Dim ws As Worksheet Dim selectedRow As Range Set ws = ThisWorkbook.ActiveSheet ' Clear all background colors from row 7 downwards ws.Rows("7:" & ws.Rows.count).Interior.ColorIndex = xlNone ' Check if the selected cell is in columns A to J and row 7 downwards If Not Intersect(Target, ws.Range("A7:J" & ws.Rows.count)) Is Nothing Then ' Set background color of columns A to K to yellow Set selectedRow = Intersect(Target.EntireRow, ws.Range("A:K")) If Not selectedRow Is Nothing Then selectedRow.Interior.Color = RGB(255, 255, 0) ' Yellow color End If End If Application.EnableEvents = True ThisWorkbook.Worksheets("ADMIN RESULTS").Protect Password:="edit" End Sub