正如您所发现的,问题是当您离开备忘录时光标位置会丢失。
这可能是因为 Access 表单控件不是“真正的”控件:它们只有在获得焦点时才是真正的窗口控件。其余时间,它们是粘贴到表单上的控件图像。
因此,您需要做的是在各种交互过程中跟踪光标位置(以及当前选择的文本长度):
- 当用户使用键盘移动光标时(
KeyUp
事件)
- 当用户在备忘录内单击时(
Click
事件,定位光标或使用鼠标选择文本)
- 当备忘录最初获得焦点时(
GetFocus
第一次,整个文本被选中并且光标位于位置 0)
为了测试这一点,我做了一个小表格:
将以下代码添加到表单中:
'----------------------------------------------------------
' Track the position of the cursor in the memo
'----------------------------------------------------------
Private currentPosition As Long
Private currentSelLen As Long
Private Sub txtMemo_Click()
RecordCursorPosition
End Sub
Private Sub txtMemo_GotFocus()
RecordCursorPosition
End Sub
Private Sub txtMemo_KeyUp(KeyCode As Integer, Shift As Integer)
RecordCursorPosition
End Sub
Private Sub RecordCursorPosition()
currentPosition = txtMemo.SelStart
currentSelLen = txtMemo.SelLength
End Sub
'----------------------------------------------------------
' Insert when the user double-click the listbox or press the button
'----------------------------------------------------------
Private Sub listSnippets_DblClick(Cancel As Integer)
InsertText
End Sub
Private Sub btInsert_Click()
InsertText
End Sub
'----------------------------------------------------------
' Do the actual insertion of text
'----------------------------------------------------------
Private Sub InsertText()
If Len(Nz(listSnippets.Value, vbNullString)) = 0 Then Exit Sub
Echo False 'Avoid flickering during update
' Update the Memo content
Dim oldstr As String
oldstr = Nz(txtMemo.Value, vbNullString)
If Len(oldstr) = 0 Then
txtMemo.Value = listSnippets.Value
Else
txtMemo.Value = Left$(oldstr, currentPosition) & _
listSnippets.Value & _
Mid$(oldstr, currentPosition + currentSelLen + 1)
End If
'We will place the cursor after the inserted text
Dim newposition As Long
newposition = currentPosition + Len(listSnippets.Value)
txtMemo.SetFocus
txtMemo.SelStart = newposition
txtMemo.SelLength = 0
currentPosition = newposition
currentSelLen = 0
Echo True
End Sub
我制作了一个测试 accdb 数据库,您可以下载它,以便您查看详细信息并尝试使用它。