Excel VBA – 在用户表单多行文本框中双击单词

任务 :我的目标是双击后从UserForm的多行TextBox提取突出显示的单词。

使用属性 :虽然通过TextBox属性.SelStart.SelLength突出显示给定的string位置是绝对没有问题的,但.SelLength却不那么容易:用户DblClick突出显示整个string,但Excel不会重置可以假定突出显示的文本的起始位置处的.SelStart值保持在用户双击的位置。

我的问题 :是否有可能直接捕捉应用程序设置的突出显示的文本起始位置?

我的工作 :我将演示一个非常简单的解决方法,通过检查以下和之前的例如20个左右字母来实际点击位置来重build高亮度的单词(当然,也可以使用正则expression式,并细化示例代码):

 Private Sub TextBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean) Dim sTxt, sSel As String Dim selPos, i, i2 As Long TextBox1.SetFocus ' this is the User's DblClick Position, ' but not the starting Position of the highlighted Word ' after DblClick selPos = TextBox1.SelStart sTxt = Replace(Replace(TextBox1.Text, vbCrLf, vbLf), "\", ".") If TextBox1.SelLength > 0 Then sSel = TextBox1.SelText Else sSel = Mid(sTxt, selPos + 1, 5) ' check the preceding 20 letters i = selPos For i = selPos To (selPos - 20) Step -1 If i < 0 Then Exit For Select Case Left(Mid(sTxt, i + 1), 1) Case " ", vbLf, ":", ".", "?", """", "'", "(", ")" sSel = Mid(sTxt, i + 2, selPos - i) Exit For End Select Next i ' check the following 20 letters i2 = selPos For i2 = selPos To (selPos + 20) If i2 > Len(sTxt) Then Exit For Select Case Left(Mid(sTxt, i2 + 1), 1) Case " ", vbLf, ":", ".", "?", """", "'", ")", "(" sSel = Replace(Mid(sTxt, i + 2, i2 - i - IIf(i = i2, 0, 1)), vbLf, "") Exit For End Select Next i2 End If ' Show the highlighted word Me.Label1.Text = sSel End Sub 

我认为这是一个时间问题。 它似乎工作,如果您使用标志variables和MouseUp事件与DblClick事件相结合:

 Private bCheck As Boolean Private Sub TextBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean) bCheck = True End Sub Private Sub TextBox1_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single) If bCheck Then bCheck = False MsgBox Me.TextBox1.SelStart & "; " & Me.TextBox1.SelLength End If End Sub