简体   繁体   中英

Clear contents of active cell if it contains specific text

I am trying to develop an excel based tool, wherein I have put the default answer to my questions as 'enter comments'. I would like to set up a code where, when the user clicks on the answer cell, the text 'enter comments' disappears, and it becomes a blank cell. However, once the user has entered his answer, the cell should not be cleared - the answer text should remain.

I have tried a host of VBA codes for this problem. While none throw up any error, none of them work either. Below is an example of the code I have tried:

Sub Macro1()
Dim text as String
text = "Enter comments"
If ActiveCell = text then
ActiveCell.ClearContents 
End if
End sub

Insert this code inside the worksheet, not in a module:

Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If Target = "Enter comments" Then Target.ClearContents

End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Set RngComments = Range("A1:B5")

If Not Intersect(Target, RngComments) Is Nothing Then
    If Target.Cells.Count = 1 Then
        If Target.Value = "Enter comments" Then
            Target.Value = ""
        End If
    End If
Else
    'this part refills all comment cells with "Enter comments" if found empty
    For Each cell In RngComments.Cells
        If cell.Value = "" Then cell.Value = "Enter comments"
    Next
End If

End Sub

You can change the RngComments to any range or union of ranges. The loop in the else part refills empty comment cells but I'm unsure whether you need it and you might want to consider another event to do this as this might run too often.

You could use:

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    'Limit the range where the code should triggered to avoid delays, check if only one cell affected to avoid errors and check cell value.
    If Not Intersect(Target, Range("A1:A10")) Is Nothing And Target.Value = "Enter comments" And Target.Count = 1 Then
        'Stop code to re run when cell clear to avoid delays
        Application.EnableEvents = False
            Target.Value = ""
        Application.EnableEvents = True
    End If

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM