Re: Copy a recordset (multiple rows) into an array by McKirahan
McKirahan
Fri May 12 01:12:02 CDT 2006
"Dan" <danncasey@gmail.com> wrote in message
news:1147397587.678730.175970@y43g2000cwc.googlegroups.com...
[snip]
> Is there any way to store the recordset so that i can access it by
> record number and fieldname?
> ie: strMyName = aryRecords(intRecNum)("Name")
Will this help or at least give you an idea? Watch for word-wrap.
This builds an array by (FieldNamePosition,RecordNumber)
and uses a Dictionary to resolve both.
Option Explicit
'*
'* Declare Constants
'*
Const cVBS = "whose.vbs"
Const cMDB = "who.mdb"
Const cDSN = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
'*
'* Declare Globals
'*
Dim arrRST()
ReDim arrRST(3,0)
arrRST(1,0) = "NameID"
arrRST(2,0) = "LastName"
arrRST(3,0) = "FirstName"
Dim intRS1
Dim intRS2
'*
'* Lookup()
'*
Dim objDIC
Set objDIC = CreateObject("Scripting.Dictionary")
'*
Call Build()
MsgBox "Lookup('FirstName',7) = " &
Lookup("FirstName",7),vbInformation,cVBS
MsgBox "Lookup('LastName',3) = " &
Lookup("LastName",3),vbInformation,cVBS
'*
Set objDIC = Nothing
Sub Build()
'*
'* Declare Variables
'*
Dim strSQL
strSQL = "SELECT"
For intRS1 = 1 To UBound(arrRST,1)
objDIC.Add arrRST(intRS1,0), intRS1
strSQL = strSQL & " " & arrRST(intRS1,0)
If intRS1 < UBound(arrRST,1) Then strSQL = strSQL & ","
Next
intRS1 = 0
intRS2 = 0
strSQL = strSQL & " FROM [who] ORDER BY NameID"
'*
'* Declare Objects
'*
Dim objADO
Set objADO = CreateObject("ADODB.Connection")
objADO.Open cDSN & cMDB
Dim objRST
Set objRST = objADO.Execute(strSQL)
'*
'* Read Table and Build Array
'*
Do While Not objRST.EOF
intRS2 = intRS2 + 1
ReDim Preserve arrRST(UBound(arrRST,1),intRS2)
For intRS1 = 1 To UBound(arrRST,1)
arrRST(intRS1,intRS2) = objRST(arrRST(intRS1,0)).Value
Next
objDIC.Add objRST(arrRST(1,0)).Value, intRS2
objRST.MoveNext
Loop
'*
'* Destroy Objects
'*
Set objRST = Nothing
objADO.Close
Set objADO = Nothing
End Sub
Function Lookup(fld,rec)
Lookup = ""
'*
If Not objDIC.Exists(fld) _
Or Not objDIC.Exists(rec) Then Exit Function
'*
Dim intFLD
intFLD = objDIC.Item(fld)
Dim intREC
intREC = objDIC.Item(rec)
'*
Lookup = arrRST(intFLD,intREC)
End Function
In my example, the "NameID" is an AutoNumber field (MS-Access)
and this presumes that it is used for RecordNumber rather than the
physical (sequential) record number. Is this what you want?
The database table's FieldNames are declared once in the array and
referenced elsewhere by their array position