vba 激活文本框后如何选择文本框的内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30117252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:35:26  来源:igfitidea点击:

How to select the contents of a textbox once it is activated?

excelvbaeventstextbox

提问by ZygD

I have this simple Userform, where I only have TextBox1and TextBox2. I enter some text in both of them. Assume the focus is on (the cursor is in) the TextBox2. When I click on TextBox1, I want the whole text in this control to be highlighted (selected). Thus I use this code:

我有这个简单的用户表单,其中只有TextBox1TextBox2。我在它们两个中都输入了一些文本。假设焦点在(光标在)上TextBox2。当我单击 时TextBox1,我希望突出显示(选中)此控件中的整个文本。因此我使用这个代码:

Private Sub TextBox1_Enter()
    With TextBox1
        .SetFocus
        .SelStart = 0
        .SelLength = Len(.Text)
    End With
    MsgBox "enter event was fired"
End Sub

There is a MsgBoxat the end which is loaded, that means the event works. However, the text is not highlighted. How to fix this?

最后有一个MsgBox已加载,这意味着该事件有效。但是,文本没有突出显示。如何解决这个问题?

I use the Enterevent and don't want to use the MouseDownevent, because I need the code to also work when the TextBox1is activated programatically, so I feel the Enterevent to be the best choice, as it's fired in both cases! Another drawback of the MouseDownevent is: when I click for the second time on the TextBox1, I would not expect the whole text to be highlighted anymore, because the focus was set on the first click and it was not changed after I clicked on the same control for the second time; so in this case I would like the cursor to act normally (not to keep the text marked).

我使用Enter事件但不想使用MouseDown事件,因为我需要代码在以TextBox1编程方式激活时也能工作,所以我觉得Enter事件是最好的选择,因为它在两种情况下都会被触发!该MouseDown事件的另一个缺点是:当我第二次单击 时TextBox1,我不希望整个文本再突出显示,因为焦点是在第一次单击时设置的,并且在我单击同一个控件后没有改变第二次; 所以在这种情况下,我希望光标正常运行(不要保持文本标记)。

Update
When I click once on the TextBox1, I expect to have this result: enter image description here
If clicked again, the highlight would be removed and the cursor would be placed in the place where it was clicked.

更新
当我在 上单击一次时TextBox1,我希望得到以下结果: 在此处输入图片说明
如果再次单击,突出显示将被删除,光标将放置在单击的位置。

回答by Siddharth Rout

Can't be more simple than this I guess...

我想没有比这更简单的了...

Private Sub TextBox1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, _
ByVal X As Single, ByVal Y As Single)
    With TextBox1
        .SelStart = 0
        .SelLength = Len(.Text)
    End With
End Sub

Whether you click on the textbox or you tab into it, it will do what you want. To deselect the text, use the arrow keys.

无论您是单击文本框还是 Tab 键,它都会执行您想要的操作。要取消选择文本,请使用箭头键。

Explanation

解释

If you debug the code you will see that even though you have said .SetFocus, the focus is not on the Textbox. .SetFocusdoesn't work in TextBox1_Enter()and you need to have focus for the rest of the code to work. And hence my alternative...

如果您调试代码,您将看到即使您说了.SetFocus,焦点也不在文本框上。.SetFocus不起作用TextBox1_Enter(),您需要专注于其余代码才能工作。因此我的选择...

Alternative

选择

You may also like this version :) This overcomes the limitation of using the mouse in the TextBox

您可能也喜欢这个版本 :) 这克服了在 TextBox 中使用鼠标的限制

Dim boolEnter As Boolean

Private Sub TextBox1_Enter()
    boolEnter = True
End Sub

Private Sub TextBox1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, _
ByVal X As Single, ByVal Y As Single)
    If boolEnter = True Then
        With TextBox1
            .SelStart = 0
            .SelLength = Len(.Text)
        End With
        boolEnter = False
    End If
End Sub

回答by vacip

Pff, took me a while. Actually, your code works, but it highlights the text BEFORE the click event happens. So you clicking in the box instantly overrides the selection created by the code. I have used a delayed selection, and it works, though it is a bit disgusting...

噗,花了我一段时间。实际上,您的代码有效,但它在单击事件发生之前突出显示了文本。因此,您在框中单击会立即覆盖由代码创建的选择。我使用了延迟选择,它有效,虽然它有点恶心......

The code for the textboxes:

文本框的代码:

Private Sub TextBox1_Enter()
  Application.OnTime Now + TimeValue("00:00:01"), "module1.SelectText1"
End Sub

Private Sub TextBox2_Enter()
  Application.OnTime Now, "module1.SelectText2"
End Sub

Note that it works even withouth the {+ TimeValue("00:00:01")} part, but it might theoretically stop it from working at times. Hmm, on a second thought, just leave it out. I doubt it would ever cause a problem.

请注意,即使没有 {+ TimeValue("00:00:01")} 部分它也能工作,但理论上有时可能会阻止它工作。嗯,三思而后行,把它放在一边。我怀疑它会不会引起问题。

Now the code in module1:

现在模块1中的代码:

Sub SelectText1()
  UserForm1.TextBox1.SelStart = 0
  UserForm1.TextBox1.SelLength = Len(UserForm1.TextBox1.Text)
End Sub

Sub SelectText2()
  UserForm1.TextBox2.SelStart = 0
  UserForm1.TextBox2.SelLength = Len(UserForm1.TextBox2.Text)
End Sub

Hope this works for you too. Ineresting problem. :) Cheers!

希望这对你也有用。无趣的问题。:) 干杯!

回答by Thomas G

I couldn't manage to select/highlight text in the Enter event as the the mousedown and mouseup events coming after are somewhat resetting the selection.

我无法在 Enter 事件中选择/突出显示文本,因为之后的 mousedown 和 mouseup 事件在某种程度上重置了选择。

I think the most proper way of achieving what you want is this :

我认为实现你想要的最正确的方法是:

' if you want to allow highlight more then once, reset the  variable LastEntered prior to call SelectTboxText:
'       LastEntered = ""
'       SelectTboxText TextBox2


Dim LastEntered As String


' Button to select Textbox1
Private Sub CommandButton1_Click()
    SelectTboxText TextBox1
End Sub

' Button to select Textbox2
Private Sub CommandButton2_Click()
    SelectTboxText TextBox2
End Sub

Private Sub TextBox1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    SelectTboxText TextBox1
End Sub


Private Sub TextBox2_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
     SelectTboxText TextBox2
End Sub


Public Sub SelectTboxText(ByRef tBox As MSForms.TextBox)

    If LastEntered <> tBox.Name Then

        LastEntered = tBox.Name

        With tBox
            .SetFocus
            .SelStart = 0
            .SelLength = Len(.Text)
        End With

    End If

End Sub

So each time you want to activate one of the textbox programmatically, you should call the sub SelectTboxText, which is not really annoying IMO. I made 2 buttons for this as an example.

所以每次你想以编程方式激活一个文本框时,你应该调用子 SelectTboxText,这并不是真的很烦 IMO。我为此制作了 2 个按钮作为示例。

回答by Pradeep Kumar

This is somewhat an enhancement of what @vacip posted. The benefit you get is that you don't need to add a separate method in the Module for each new textbox.

这在某种程度上是对@vacip 发布的内容的增强。您获得的好处是您不需要在模块中为每个新文本框添加单独的方法。

The following code in your User Form:

您的用户表单中的以下代码:

'===== User Form Code ========

Option Explicit

Private Sub TextBox1_Enter()
    OnTextBoxEnter
End Sub

Private Sub TextBox2_Enter()
   OnTextBoxEnter
End Sub

Private Sub TextBox3_Enter()
   OnTextBoxEnter
End Sub

The following code goes in a Module:

以下代码进入模块:

'===== Module Code ========

Sub SelectAllText()
    SendKeys "{HOME}+{END}", True
End Sub

Sub OnTextBoxEnter()
   Application.OnTime Now + 0.00001, "SelectAllText", Now + 0.00002
End Sub

回答by Gordon

Private Sub UserForm_Initialize()                                                                
    TextBox1.SetFocus
    TextBox1.SelStart = 0
    TextBox1.SelLength = Len(TextBox1.Text)
End Sub   

Add this to the form's code

将此添加到表单的代码中

回答by Luke

I know this is well out of date but I'm leaving this here in case it helps someone in my position.

我知道这已经过时了,但我将其留在这里以防万一它对我的职位有所帮助。

What I want is:

我想要的是:

  • If I click on the box for the first time: select all the text
  • If I click on it a subsequent time: put the cursor where the mouse is and allow me to use the mouse to select a substring
  • 如果我第一次单击该框:选择所有文本
  • 如果我随后单击它:将光标放在鼠标所在的位置并允许我使用鼠标选择一个子字符串

Firstly it is important to know that "Select all the text" is the default behaviour when tabbing into a TextBox and that "Put the cursor here" is the default behaviour when clicking on a TextBox so we only need to worry about what the mouse is doing.

首先,重要的是要知道“选择所有文本”是选项卡进入文本框时的默认行为,而“将光标放在此处”是单击文本框时的默认行为,因此我们只需要担心鼠标是什么正在做。

To do this, we can keep track of the Active Control, but only while the mouse is moving over our TextBox (ie. before the Click)

为此,我们可以跟踪活动控件,但只有在鼠标移动到我们的 TextBox 上时(即单击之前)

Code:

代码

Private m_ActiveControlName As String

Private Sub Text1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    m_ActiveControlName = Me.ActiveControl.Name
End Sub

Private Sub Text1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    If m_ActiveControlName <> Me.Text1.Name Then
        Call Text1_Enter   'we don't have to use Text1_Enter for this, any method will do
        Exit Sub           'quit here so that VBA doesn't finish doing its default Click behaviour
    End If
End Sub

Private Sub Text1_Enter()
    With Text1
        .SelStart = 0
        .SelLength = Len(.Text)
    End With
End Sub

回答by Ajit S Fernando

Try the same code with TextBox1_MouseDown. It should work.

尝试使用相同的代码TextBox1_MouseDown。它应该工作。

Private Sub TextBox1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    With TextBox1
        .SetFocus
        .SelStart = 0
        .SelLength = Len(.Text)
    End With
    MsgBox "Text in TextBox1 is selected"
End Sub

回答by Kris

The behavior you're trying to implement is already built in to the TextBox. When you move the mouse over the left side of the text box, the mouse pointer will point to the right. If you click, it will select all the text in the field. Clicking anywhere else will deselect the text.

您尝试实现的行为已经内置于TextBox. 当您将鼠标移到文本框左侧时,鼠标指针将指向右侧。如果单击,它将选择字段中的所有文本。单击其他任何地方将取消选择文本。

I will try a few other strategies to see if I can get this to work in one Sub.

我将尝试其他一些策略,看看我是否可以在一个 Sub 中使用它。

回答by Vasily

use this

用这个

Private Sub TextBox1_Enter()
    With TextBox2
        .ForeColor = vbBlack
        .Font.Bold = False
    End With
    With TextBox1
        .ForeColor = vbRed
        .Font.Bold = True
    End With
End Sub

Private Sub TextBox2_Enter()
    With TextBox1
        .ForeColor = vbBlack
        .Font.Bold = False
    End With
    With TextBox2
        .ForeColor = vbRed
        .Font.Bold = True
    End With
End Sub