I'm working on a program that can take data from one field in a table and put that whole column into an array or even just read from the table itself. The code seems to use a form or something else I would like to use an array.
This will work:
Dim rstData As DAO.Recordset
Dim v As Variant
Set rstData = CurrentDb.OpenRecordset("select FirstName from FaxBook3")
v = rstData.GetRows(rstData.RecordCount)
"v" will now be a array of all first names. The array will/can be multi-dimensional if your query has multiple columns.
-
1You would need to move the recordset to the end, and then back again to fill the array successfully, otherwise you will only get the first row using
rstData.MoveLast rstData.MoveFirst
– krsmith88 Dec 5 '17 at 11:07 -
Here's a simple example of how you could take the contents of a column in a table and dynamically add it to the array:
Option Compare Database
Option Explicit
Public Sub loadIntoArray()
Dim rstTableName As DAO.Recordset 'Your table
Dim myArray() As String 'Your dynamic array
Dim intArraySize As Integer 'The size of your array
Dim iCounter As Integer 'Index of the array
'Open your table
Set rstTableName = CurrentDb.OpenRecordset("Table1")
If Not rstTableName.EOF Then
rstTableName.MoveFirst 'Ensure we begin on the first row
'The size of the array should be equal to the number of rows in the table
intArraySize = rstTableName.RecordCount - 1
iCounter = 0
ReDim myArray(intArraySize) 'Need to size the array
Do Until rstTableName.EOF
myArray(iCounter) = rstTableName.Fields("Field1")
Debug.Print "Item: "; iCounter & " " & myArray(iCounter)
iCounter = iCounter + 1
rstTableName.MoveNext
Loop
End If
If IsObject(rstTableName) Then Set rstTableName = Nothing
End Sub
Another way to do that is using the following statements: Spanish (español): Otra forma de hacerlo es de la siguiente manera:
CLIENTSLIST table: One column
Me.ListFileContent.RowSourceType = "Table/Query"
Me.ListFileContent.RowSource = "CLIENTSLIST"
Note: The ListBox show up all data.
Albert's solution above will work, but you would need to move the recordset to the end and then back again to fill the array fully, otherwise you will only get the first row. Use MoveLast
and MoveFirst
for this.
Dim rstData As DAO.Recordset
Dim v As Variant
Set rstData = CurrentDb.OpenRecordset("select FirstName from FaxBook3")
rstData.MoveLast
rstData.MoveFirst
v = rstData.GetRows(rstData.RecordCount)
GetRows
method which returns an array. See this answer: stackoverflow.com/questions/16223369/… – HansUp Apr 29 '13 at 17:08