我有两个列表框(lfmVocabulary 和 lfmVocabularyAssign)。它们都与表单没有绑定,我在实现代码设计的某些方面遇到了困难。
到目前为止,我可以通过查询记录集使用值填充第一个列表表单,但我无法将项目从一个框传输到另一个框。
为了实现这一目标,我将代码放置在模块中,如下所示
Option Compare Database
Public Sub MoveListBoxItems(lfmVocabularyAssign As ListBox, _
lfmVocabulary As ListBox)
Dim intListX As Integer
For intListX = lfmVocabulary.ListCount = -1 To 0
If lfmVocabulary.Selected(intListX) Then
lfmVocabularyAssign.AddItem lfmVocabulary.List(intListX)
lfmVocabulary.RemoveItem intListX
End If
Next
End Sub
在表单中,我有以下代码:
Option Explicit
Dim db As Database
Dim rs As Recordset
Private Sub cmdAdd_Click()
MoveListBoxItems lfmVocabulary, lfmVocabularyAssign
End Sub
Private Sub cmdSelectAll1_Click()
Dim n As Integer
With Me.lfmVocabulary
For n = 0 To .ListCount - 1
.Selected(n) = True
Next n
End With
End Sub
Private Sub Form_Load()
Set db = CurrentDb
Set rs = db.OpenRecordset("qryVocabularyDefinitions")
Me.lfmVocabulary.RowSource = ""
Do Until rs.EOF
Me.lfmVocabulary.AddItem rs!Vocabulary
rs.MoveNext
Loop
End Sub
一般来说,我对访问和编码有点陌生,我一直在互联网上寻找解决方案。
我会对任何可以帮助我的人致以一千分的感谢:D
您犯了多个小错误,并且没有考虑到一些复杂性,这是正确的代码:
Public Sub MoveListBoxItems(lstDestination As ListBox, lstSource As ListBox)
Dim intListX As Integer
Dim selectedItems As Collection
Set selectedItems = New Collection
For intListX = 0 To lstSource.ListCount - 1 'Start with 0, then iterate through the whole list
If lstSource.Selected(intListX) Then
lstDestination.AddItem lstSource.ItemData(intListX) 'Add items first
End If
Next intListX 'Increment intListX by 1
Do While intListX >= 0
If lstSource.Selected(intListX) Then
selectedItems.Add intListX 'Add the items to be removed to a collection, in reverse order
End If
intListX = intListX - 1
Loop
Dim iterator As Variant
For Each iterator In selectedItems
lstSource.RemoveItem iterator 'And then remove them
Next iterator
End Sub
复杂性包括:从列表框中删除项目会取消选择所有项目,因此您应该将所选项目存储在集合中。此外,您需要以相反的顺序删除项目,因为删除一项会更改索引较高的每一项的索引(数字)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)