我正在尝试开发一个基于excel的工具,在该工具中,我已将问题的默认答案作为“输入评论”。我想设置一个代码,当用户单击答案单元格时,“输入评论”文本消失,并且变成空白单元格。但是,一旦用户输入了答案,就不应清除该单元格-答案文本应保留。
我已经尝试了许多VBA代码来解决此问题。尽管没有一个抛出任何错误,但是它们都不起作用。下面是我尝试过的代码示例:
Sub Macro1()
Dim text as String
text = "Enter comments"
If ActiveCell = text then
ActiveCell.ClearContents
End if
End sub
答案 0 :(得分:2)
将此代码插入工作表中而不是模块中:
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target = "Enter comments" Then Target.ClearContents
End Sub
答案 1 :(得分:1)
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部分中的循环重新填充了空的注释单元格,但是我不确定是否需要它,并且您可能想考虑另一个事件来执行此操作,因为这可能会经常运行。
答案 2 :(得分:0)
您可以使用:
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