0

I have a table ranging from ("C22:Q26"), where cell ("R22"), ("R23"), ("R24") up to ("R26") are the cells to be selected in a row, to clear contents.

I want to clear contents of a range("C22:Q22"), when cell ("R22") is selected.

Similarly clear contents of a range("C23:Q23"), when cell ("R23") is selected, and so on up to range("C26:Q26") when cell ("R26") is selected.

I wrote this, placed in sheet code.

Sub clearcontents()
If Range("r22").Selected Then
   Range("R22").Offset(, -15).Resize(, 15).Select
   Range("R22").Offset(, -15).Resize(, 15).clearcontents
ElseIf Range("r23").Selected Then
   Range("R23").Offset(, -15).Resize(, 15).Select
   Range("R23").Offset(, -15).Resize(, 15).clearcontents
ElseIf Range("r24").Selected Then
   Range("R24").Offset(, -15).Resize(, 15).Select
   Range("R24").Offset(, -15).Resize(, 15).clearcontents
ElseIf Range("r25").Selected Then
   Range("R25").Offset(, -15).Resize(, 15).Select
   Range("R25").Offset(, -15).Resize(, 15).clearcontents
ElseIf Range("r26").Selected Then
   Range("R26").Offset(, -15).Resize(, 15).Select
   Range("R26").Offset(, -15).Resize(, 15).clearcontents
End If
End Sub
2
  • Do you want the cells to be cleared automatically? If so, look at the Worksheet.SelectionChange event.
    – BigBen
    Commented Nov 10, 2019 at 2:31
  • yes Iplaced this code in worksheet.selectionchange event but still dosent work
    – jonty
    Commented Nov 10, 2019 at 2:35

2 Answers 2

2

Try using the Worksheet.SelectionChange event. Add the following code to the sheet code module.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If Target.CountLarge <> 1 Then Exit Sub

    If Not Intersect(Target, Me.Range("R22:R26")) Is Nothing Then
        Me.Range("C" & Target.Row & ":Q" & Target.Row).ClearContents
    End If

End Sub
0
1

If your code is in the 'Worksheet_SelectionChange' macro and it doesn't fire, i would double-check that you have events enabled.

enter image description here

otherwise this piece of code should do what you want to do, some checks also that the selection needs to be of one cell:

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Dim rColumn As Range
  Dim tTable As Range

  Set rColumn = Me.Range("R22:R26")
  Set tTable = Me.Range("C22:Q26")

  If Not Intersect(Target, rColumn) Is Nothing Then
    If Target.Count = 1 Then
      Intersect(Target.EntireRow, tTable).ClearContents
    End If
  End If

End Sub
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.