我有备注字段和列表。我想要完成的是,如果我在备忘录字段中输入一些内容,然后只需单击列表中的文本记录,该文本就会显示在备忘录中,并且位于光标所在的开头。
经过研究和谷歌搜索,我成功地做到了。我用 .selstart 属性做到了。
但对我来说, selstart 似乎有错误。它仅在我单击备忘录中的某个位置时才有效(然后一切正常。)但是如果正在输入某些内容,然后单击列表中的文本(之前没有在备忘录字段中单击),selstart 将返回位置 0。
这给我带来了很大的问题。
任何人都可以帮忙吗?谢谢你。
我有备注字段和列表。我想要完成的是,如果我在备忘录字段中输入一些内容,然后只需单击列表中的文本记录,该文本就会显示在备忘录中,并且位于光标所在的开头。
经过研究和谷歌搜索,我成功地做到了。我用 .selstart 属性做到了。
但对我来说, selstart 似乎有错误。它仅在我单击备忘录中的某个位置时才有效(然后一切正常。)但是如果正在输入某些内容,然后单击列表中的文本(之前没有在备忘录字段中单击),selstart 将返回位置 0。
这给我带来了很大的问题。
任何人都可以帮忙吗?谢谢你。
正如您所发现的,问题是当您离开备忘录时光标位置会丢失。
这可能是因为 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 数据库,您可以下载它,以便您查看详细信息并尝试使用它。