首页 > 解决方案 > VBA - 在用户表单上输入 ListBox,处理退格

问题描述

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

我做了以下代码:

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

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

提前致谢

标签: vbalistbox

解决方案


这是列表框的默认行为。您可以使用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

推荐阅读