我有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
答案 0 :(得分:1)
尝试使用这样的函数来获取SQL语句。
Function GetSQLFromListbox(lbx As MSForms.ListBox)
Dim i As Long
Dim sIn As String
If lbx.ListIndex <> -1 Then
sIn = " WHERE field IN("
For i = 0 To lbx.ListCount - 1
If lbx.Selected(i) Then
sIn = sIn & "'" & lbx.List(i) & "',"
End If
Next i
sIn = Left$(sIn, Len(sIn) - 1) & ")"
End If
GetSQLFromListbox = "SELECT * FROM table" & sIn
End Function
它应该返回类似
的内容SELECT * FROM table WHERE field IN('2''3')
然后从该语句创建一个记录集并循环遍历它以填充第二个列表框。请注意,如果未选择任何内容,则返回没有WHERE子句的SQL,因此您将获得所有内容。您可能需要根据自己的情况进行调整。