VBA - 在用户表单上的列表框中键入,处理退格

VBA - Typing into ListBox on User Form, handling backspaces

我在用户表单上有一个 ListBox,我希望用户能够在其中的第 3 列中键入数值。前两列将包含一些预定义的值,我希望用户 select 他们想要修改的行,然后在第三列中输入数字。

我做了以下代码:

Private Sub cardList_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)

Dim curSel As Single
curSel = cardList.ListIndex
Dim curString As String
Dim newString As String

If curSel = -1 Then Exit Sub
If IsNull(cardList.List(curSel, 2)) Then
    curString = ""
Else
    curString = cardList.List(curSel, 2)
End If
If KeyCode > 47 And KeyCode < 58 Then
    newString = curString & Chr(KeyCode)
ElseIf KeyCode = 8 Then
    If Not curString = "" Then
        newString = Mid(curString, 1, Len(curString) - 1)
    End If
End If

cardList.List(curSel, 2) = newString
End Sub

这段代码工作正常,唯一的问题是当我按退格键时,字符串的最后一个字符被删除了,但是列表框的 selection 也跳到了第一行一些理由。有什么办法可以防止这种情况发生吗?或者有没有更好的方法来创建一个用户可以输入的列表框?

提前致谢

这是列表框的默认行为。您可以使用 KeyCode = 0 取消密钥并防止这种情况发生。

Private Sub cardList_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)

    Dim curSel As Single
    curSel = cardList.ListIndex
    Dim curString As String
    Dim newString As String

    If curSel = -1 Then Exit Sub
    If IsNull(cardList.List(curSel, 2)) Then
        curString = ""
    Else
        curString = cardList.List(curSel, 2)
    End If
    If KeyCode > 47 And KeyCode < 58 Then
        newString = curString & Chr(KeyCode)
    ElseIf KeyCode = 8 Then
        If Not curString = "" Then
            newString = Mid(curString, 1, Len(curString) - 1)
        End If
        KeyCode = 0
    End If

    cardList.List(curSel, 2) = newString
End Sub