簡體   English   中英

如何從adodb記錄集Excel VBA中的一列中選擇不同的值?

[英]How to select distinct values from one column in adodb recordset Excel VBA?

我有一個從數據庫獲取的ADODB.Recordset rs 我現在必須重用此記錄集兩次。

這是我的記錄集的示例:

Mike     Client
John     Manager
Karen    Client
Joe      Sub
Brian    Manager

現在我需要獲取所有標題,所以我想要獲取:

Client
Manager
Sub

我知道這里有rs.Filter ,但是我不確定是否可以選擇與它不同。

我也知道我可以克隆此Recordset:

Dim rs_clone As ADODB.Recordset
Set rs_clone = New ADODB.Recordset
rs_clone = rs.getrows()

是否可以僅克隆不同的記錄? 還是更好的方法? 謝謝

在數據庫中發射一個sql字符串會給您很大的空間來選擇要返回的內容

一個小示例(使用后期綁定,我更喜歡在生產代碼中使用它),在其中我要求從表列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需要設置為正確的連接字符串。


編輯

在這篇vba的幫助下,無法在數據庫中觸發sql字符串:從數組獲取唯一值,我得到了以下解決方案。

如果您希望早期綁定,則需要參考以下內容:

  • Microsoft ActiveX數據對象(Im使用6.1庫)
  • Microsoft Scripting運行時(因此我們可以使用字典)

代碼如下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM