[英]Excel VBA: How to clear contents for specified cells when another cell contains specific text or string
[英]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.