我有 2 个列表框,lbA 和 lbB。我正在使用运行良好的 SQL 脚本填充 lbA。现在我想做的是,当我从 lbA 中选择一个项目时,lbB 会再次从 SQL 脚本中填充。它在仅从 lbA 中选择一个项目但选择两个或更多或取消选择一个项目时起作用,然后它会添加重复的项目或不从 lbB 中删除项目。我很困惑如何解决这个问题。有人可以帮忙吗?
这是到目前为止的代码:
Private Sub lbA_Change()
Dim Num As Integer
Dim lngIndex As Long
If Me.lbA.ListIndex <> -1 Then
For lngIndex = 0 To lbA.ListCount - 1
If lbA.Selected(lngIndex) Then
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
Dim strConn As String
strConn = "PROVIDER=SQLOLEDB;"
strConn = strConn & "DATA SOURCE=MSSQLSERVER2008;INITIAL CATALOG=MyDB;"
strConn = strConn & " INTEGRATED SECURITY=sspi;"
cnPubs.Open strConn
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
With rsPubs
.ActiveConnection = cnPubs
.Open "My SQl Statement"
End With
If rsPubs.EOF Or rsPubs.BOF Then
Exit Sub
End If
rsPubs.MoveFirst
With Me.lbB
.Clear
Do
.AddItem rsPubs![strName]
rsPubs.MoveNext
Loop Until rsPubs.EOF
End With
rsPubs.Close
End If
Next
End If
End Sub