在特定单元格中自动显示“请在此输入文字”

时间:2016-09-14 04:08:57

标签: excel vba excel-vba excel-formula double-click

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

我有一个特定的单元格(B5)需要显示“请在此处输入文本”,只要该单元格中没有文本,并且一旦用户双击单元格,它将擦除并允许用户输入他们想要的文本。如果用户离开它并且它是空的,就像我说它应该显示“请在这里输入文字......”

2 个答案:

答案 0 :(得分:0)

如果这是错误的话,从来没有这样做过道歉,但这似乎有效。 将以下内容放在工作表代码中。

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

答案 1 :(得分:0)

您声明'...并允许用户输入所需的文字。'我将假设用户输入文字的常规单元格格式。< / p>

在工作表的代码表中:

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

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

¹如果没有先做自己的研究,请不要让我解释一下。如果您发现自己遇到问题的具体问题,我会尽力协助;如果你不能掌握一个概念然后选修一门课程,那么解释一下就超出了这个场所的范围。