我没有为许多列表框(格式相同)编写单独的代码,而是尝试使用通用代码来执行一组操作:
首先,我在模块名称" GLOBALS"中声明了全局变量:
Public glb As Listbox
名为" SCHEDULES" (包含列表框),当我点击列表框时,我有这个代码来设置全局列表框变量:
Private Sub ListBox1_Click()
glb = SCHEDULE.ListBox1 <<<<<<<<<THIS IS WHERE I GET MY ERROR
End Sub
当我按下删除时,我想调用名为DeleteLBItem的代码(删除所选行,然后将所有较低的行向上移动:
Private Sub ListBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 46 Then
If MsgBox("Clear selected event info?", vbOKCancel, "Confirm Event Action") = vbCancel Then
Exit Sub
Else
Call DeleteLBItem
End If
End If
End Sub` `
程序DeleteLBItem位于单独的模块标题中,#34; CORE&#34;:
Sub DeleteLBItem()
Dim i As Integer
i = glb.ListIndex
Do Until i = glb.ListCount - 1
With glb
.List(i, 0) = .List(i + 1, 0)
.List(i, 1) = .List(i + 1, 1)
.List(i, 2) = .List(i + 1, 2)
End With
n = n + 1
Loop
With glb
.List(.ListCount, 0) = ""
.List(.ListCount, 1) = ""
.List(.ListCount, 2) = ""
End With
End Sub
我得到的错误是运行时间13(类型不匹配)。我需要做些什么呢?
答案 0 :(得分:1)
您有多个列表框(例如:LB1,LB2,LB3),并且您正在为每个列表框的事件中添加代码。
' set the global listbox to the clicked one (pseudo-code)
Private Sub LB1_Click()
GLB = LB1
End Sub
Private Sub LB2_Click()
GBL = LB2
End Sub
Private Sub LB3_Click()
GLB = LB3
End Sub
并且您还要向keydown添加内容以执行您的删除子。
我没有尝试过使用这样的全局对象,但它似乎并不适合你。在执行sub时只传递对象的引用会更简单。
Private Sub ListBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 46 Then
If MsgBox("Clear selected event info?", vbOKCancel, "Confirm Event Action") = vbCancel Then
Exit Sub
Else
DeleteLBItem ListBox1 ' dont need brackets here!
End If
End If
End Sub
Sub DeleteLBItem(ByRef LB As Object)
Dim i As Integer
i = LB.ListIndex
Do Until i = LB.ListCount - 1
With LB
.List(i, 0) = .List(i + 1, 0)
.List(i, 1) = .List(i + 1, 1)
.List(i, 2) = .List(i + 1, 2)
End With
i = i + 1 ' this was n?
Loop
With LB
.List(.ListCount, 0) = ""
.List(.ListCount, 1) = ""
.List(.ListCount, 2) = ""
End With
End Sub
我没有对其进行测试,但假设它有效,您不再需要代码来在click
事件中分配全局列表框。
答案 1 :(得分:0)
@ YowE3K感谢您的建议。我从来没有真正理解参数的传递或故意使用它们,所以我做了一些研究,我设法修复了代码
此代码以下列形式出现:
Private Sub ListBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 46 Then
DeleteLBItemSchedule ListBox1
Else
End If
End Sub
此代码显示在单独的模块中:
Sub DeleteLBItemSchedule(glb As MSForms.Listbox)
Dim i As Integer
i = glb.ListIndex
Do Until i = glb.ListCount - 1
With glb
.List(i, 0) = .List(i + 1, 0)
.List(i, 1) = .List(i + 1, 1)
.List(i, 2) = .List(i + 1, 2)
End With
i = i + 1
Loop
With glb
.List(.ListCount - 1, 0) = ""
.List(.ListCount - 1, 1) = ""
.List(.ListCount - 1, 2) = ""
End With
End Sub