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

VBA-在用户窗体上的列表框中键入,处理退格,vba,listbox,Vba,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 Di

我在用户表单上有一个列表框,我希望用户能够在表单的第三列中键入数值。前两列中有一些预定义值,我希望用户选择要修改的行,然后在第三列中键入数字

我编写了以下代码:

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
Private Sub cardList_KeyDown(ByVal KeyCode作为MSForms.ReturnInteger,ByVal Shift作为Integer)
单色暗斜线
curSel=cardList.ListIndex
像字符串一样模糊的字符串
将新闻字符串变暗为字符串
如果curSel=-1,则退出Sub
如果为空(cardList.List(curSel,2)),则
curString=“”
其他的
curString=cardList.List(curSel,2)
如果结束
如果KeyCode>47且KeyCode<58,则
newString=curString&Chr(键码)
ElseIf KeyCode=8则
如果不是curString=“”,则
newString=Mid(curString,1,Len(curString)-1)
如果结束
如果结束
列表(游标,2)=新字符串
端接头
这段代码运行得很好,唯一的问题是当我按backspace键时,字符串的最后一个字符会被删除,但出于某种原因,列表框的选择也会跳到第一行。有没有办法防止这种情况?还是有更好的方法让用户可以在列表框中键入内容


提前感谢

这是列表框的默认行为。您可以使用
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
Private Sub cardList_KeyDown(ByVal KeyCode作为MSForms.ReturnInteger,ByVal Shift作为Integer)
单色暗斜线
curSel=cardList.ListIndex
像字符串一样模糊的字符串
将新闻字符串变暗为字符串
如果curSel=-1,则退出Sub
如果为空(cardList.List(curSel,2)),则
curString=“”
其他的
curString=cardList.List(curSel,2)
如果结束
如果KeyCode>47且KeyCode<58,则
newString=curString&Chr(键码)
ElseIf KeyCode=8则
如果不是curString=“”,则
newString=Mid(curString,1,Len(curString)-1)
如果结束
KeyCode=0
如果结束
列表(游标,2)=新字符串
端接头