如何从adodblogging集Excel VBA中的一列中select不同的值?
我有一个ADODB.Recordset rs
,我从数据库中获取。 我现在必须重复使用这个logging集两次。
这是我的logging集的示例:
Mike Client John Manager Karen Client Joe Sub Brian Manager
现在我需要得到所有的标题,所以我想得到:
Client Manager Sub
我知道有rs.Filter
,但我不确定是否可以select不同的。
另外我知道我可以克隆这个Recordset:
Dim rs_clone As ADODB.Recordset Set rs_clone = New ADODB.Recordset rs_clone = rs.getrows()
是否可以克隆不同的logging? 还是有更好的办法? 谢谢
在数据库中激发一个sqlstring,给你很多空间来select你想要返回的东西
小例子(使用后期绑定,我更喜欢在生产代码中),我要求从表列MyColumn
不同的列表
Dim cn As Object Dim rs As Object Set cn = CreateObject("ADODB.Connection") cn.Open strConn cn.CommandTimeout = 0 Set rs = CreateObject("ADODB.Recordset") Set rs.ActiveConnection = cn '===================== rs.Open "SELECT Distinct MyColumn AS C FROM myTable"
需要将strConn
设置为正确的连接string。
编辑
不能在这个post的帮助下在数据库中激发一个sql
stringvba:从数组中获取唯一值我有以下解决scheme。
如果您更喜欢早期绑定,则需要引用以下内容:
- Microsoft ActiveX数据对象(即时通讯使用6.1库)
- 微软脚本运行时(这是我们可以使用一个字典)
代码如下:
Option Explicit Global Const strConn As String = _ "PROVIDER=MySQLprovider;" & _ "P*SSWORD=MyPword;" & _ "USER ID=MyLogin;" & _ "INITIAL CATALOG=MyDB;" & _ "DATA SOURCE=MyServer;" & _ "USE PROCEDURE FOR PREPARE=1;" & _ "AUTO TRANSLATE=True;" Sub getDistinctRecords() Dim cn As ADODB.Connection Set cn = New ADODB.Connection cn.ConnectionTimeout = 0 cn.Open strConn Dim rs As ADODB.Recordset Set rs = New ADODB.Recordset rs.ActiveConnection = cn '>>this mimics your record set with non-distinct members rs.Open _ "SELECT 'a' as MyCol UNION ALL " & _ "SELECT 'a' as MyCol UNION ALL " & _ "SELECT 'b' as MyCol UNION ALL " & _ "SELECT 'b' as MyCol" Dim Arr() As Variant Arr = rs.GetRows() Dim d As Scripting.Dictionary Set d = New Scripting.Dictionary Dim i As Long For i = LBound(Arr, 2) To UBound(Arr, 2) d(Arr(0, i)) = 1 Next i Dim v As Variant For Each v In d.Keys() '>>d.Keys() is a Variant array of the unique values in myArray. '>>v will iterate through each of them. '>>to print to the immediate window Debug.Print v Next v '===================== 'tidy up connection On Error Resume Next Set rs.ActiveConnection = Nothing On Error GoTo 0 If Not (rs Is Nothing) Then If (rs.State And 1) = 1 Then rs.Close Set rs = Nothing End If If Not (cn Is Nothing) Then If (cn.State And 1) = 1 Then cn.Close Set cn = Nothing End If End Sub