在特定单元格中自动显示 "please enter text here"

automatically display "please enter text here" in specific cell

只是我想在 vba 上使用双击清除内容功能。

我有一个特定的单元格 (B5) 需要显示 "please enter text here" 只要该单元格中没有文本,一旦用户双击该单元格,它就会擦除并允许用户输入他们的内容想要的文字。如果用户离开它并且它像我说的那样是空的,它应该显示 "please enter text here..."

以前从未这样做过,如果这是错误的,我们深表歉意,但这似乎有效。 将以下代码放入工作表代码中。

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
   If Not Intersect(ActiveCell, Cells(5, 2)) Is Nothing Then Target.Clear
End Sub


Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  If Cells(5,2).Value = "" Then Cells(5,2).Value = "Please enter text."
End Sub

您声明了'...并允许用户输入他们想要的文本。'我将采用一般单元格格式对于用户键入的文本。

作品中sheet的代码sheet:

Option Explicit

'you can only double click a single cell so
'no worries about Target being more than one cell here
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    If Not Intersect(Cells(5, "B"), Target) Is Nothing Then
        'Cancel = True    'only if you want to disable 'in-cell' editing
        On Error GoTo bm_Safe_Exit
        With Target
            If .Value2 = "please enter text here..." Then
                Application.EnableEvents = False
                .Clear
            End If
        End With
    End If
bm_Safe_Exit:
    Application.EnableEvents = True
End Sub

'there is a worry about Target being more than one cell here
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Cells(5, "B"), Target) Is Nothing Then
        On Error GoTo bm_Safe_Exit
        Application.EnableEvents = False
        Dim tmp As Variant
        With Cells(5, "B")
            If Not CBool(Len(.Value2)) Then
                .Font.ColorIndex = 10
                .Font.Italic = True
                .Value = "please enter text here..."
                .NumberFormat = "<@>"
            Else
                tmp = .Value
                .Clear
                .Value = tmp
            End If
        End With
    End If
bm_Safe_Exit:
    Application.EnableEvents = True
End Sub

'special cases when B5 is double-clicked but no input provided
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    With Cells(5, "B")
        If Not CBool(Len(.Value2)) Then
            Application.EnableEvents = False
            .Font.ColorIndex = 10
            .Font.Italic = True
            .Value = "please enter text here..."
            .NumberFormat = "<@>"
        End If
    End With
bm_Safe_Exit:
        Application.EnableEvents = True
End Sub

这似乎涵盖了我投入的所有内容¹,同时最大限度地减少了计算时间和工作量。它提供基本的错误控制以维持稳定的用户环境。


¹ 请不要在没有做自己的研究之前要求我解释任何事情。如果您发现某个特定点遇到困难,我会尽力提供帮助;如果你不能掌握一个概念,那就去上一门课程,这超出了这个场地的范围。