繁体   English   中英

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

[英]Clear contents of active cell if it contains specific text

我正在尝试开发一个基于excel的工具,其中我已将对我问题的默认答案作为“输入评论”。 我想设置一个代码,当用户单击答案单元格时,“输入评论”文本消失,并且变成空白单元格。 但是,一旦用户输入了答案,就不应清除该单元格-答案文本应保留。

我已经尝试了许多VBA代码来解决此问题。 尽管没有一个抛出任何错误,但是它们都不起作用。 以下是我尝试过的代码示例:

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

将此代码插入工作表中,而不是模块中:

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

您可以将RngComments更改为任何范围或范围的并集。 else部分中的循环重新填充了空的注释单元格,但是我不确定是否需要它,并且您可能想考虑另一个事件来执行此操作,因为这可能会经常运行。

您可以使用:

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