vba - 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 的选择也会跳到第一行。有什么办法可以防止这种情况发生吗?或者有没有更好的方法来拥有一个用户可以输入的列表框?
提前致谢
解决方案
这是列表框的默认行为。您可以使用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
推荐阅读
- google-apps-script - 为什么我的排序功能不起作用?(谷歌表)
- javascript - 在“{ [key: string]: AbstractControl; 类型上找不到带有“string”类型参数的索引签名 }
- r - 如何在 R 中构建显示美国 + 夏威夷和阿拉斯加的路线图?
- sybase - 在其他地方单击时输入的文本消失 - Powerbuilder
- rest - 如何有效地使用 azureml.exceptions.WebserviceException 进行高效的 REST API 错误管理?
- vue.js - VueJS - 在模板中显示异步数据
- ios - 通过 BarButton 和 Firebase 保存所有单元格中的数据
- django - django rest框架中不同模型的通用字段
- ionic-framework - Ionic Android 应用程序因 OKHTTP 错误而崩溃
- c++ - 为什么 boost lib 有外部链接,而不是内部链接?(仅标题链接的最佳实践)