简体   繁体   English

如果活动单元格包含特定文本,则清除其内容

[英]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'. 我正在尝试开发一个基于excel的工具,其中我已将对我问题的默认答案作为“输入评论”。 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. 我已经尝试了许多VBA代码来解决此问题。 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. 您可以将RngComments更改为任何范围或范围的并集。 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. else部分中的循环重新填充了空的注释单元格,但是我不确定是否需要它,并且您可能想考虑另一个事件来执行此操作,因为这可能会经常运行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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