VBA - Accessing a collection of values - ms-access

I have two access forms. frm_Main and frm_Sub which has data conditionally displayed depending on the selections of the main form. I need to write a select all function for items displayed in frm_Sub. In VBA is there a way that I can get a list of the id's currently being displayed in frm_Sub?
for example, if I do this
me.controls("Svc_Tag_Dim_Tag_Num").value
I get the value for one of rows in the frm_Sub, is there a way to get all of the values?
Maybe I can ask a different way. I have a form that is displayed as a listview, in VBA, is there a way to get all the values from a specific column?

Another option is to write a function that concatenates the PKs of the recordset that the subform displays. Say your main form is Company and your subform lists Employees. You'd have a LinkMasterFields and LinkChildFields properties of the subform control would be CompanyID (PK of the Company table, FK of the Employees table).
Thus, to get the same set of records as is displayed in the subform when the parent is on a particular Company record:
Dim db As DAO.Database
Dim strSQL As String
Dim rst As DAO.Recordset
Dim strEmployeeIDList As String
Set db = CurrentDB
strSQL = "SELECT Employees.* FROM Employees WHERE CompanyID="
strSQL = strSQL & Me!CompanyID & ";"
Set rs = db.OpenRecordset(strSQL)
If rs.RecordCount > 0 Then
With rs
.MoveFirst
Do Until .EOF
strEmployeeIDList = strEmployeeIDList & ", " & !CompanyID
.MoveNext
Loop
End With
strEmployeeIDList = Mid(strEmployeeIDList, 3)
End If
rs.Close
Set rs = Nothing
Set db = Nothing
Now, why would you do this instead of walking through an already-opened recordset (i.e., the subform's RecordsetClone)? I don't know -- it's just that there may be cases where you don't want your lookup to be tied to a particular form/subform. You could fix that by making your function that concatenates accept a recordset, and pass it a recordset declared as I did above, or pass it the subform's RecordsetClone. In that case, you could use the concatenation function either way, without being tied to the form/subform.

If I understand your question you should be able to access the ID value in the control using Column(x) where x indicates the control's row source column starting from 0. For example, if ID is in column 0 with width 0 in. it will be hidden from view but VBA can "see" it as me.controls.["Svc_Tag_Dim_Tag_Num"].column(0).
To get at the sub-form's record source directly from outside the form's class module you could create a function something like:
Public Function test_get_sub_form_record_set() As String
Dim dbs As Database
Dim rst As Recordset
Dim xcat As String
Set dbs = CurrentDb()
Set rst = [Forms]![Your Main Form Name]![Your Sub-form Name].[Form].RecordsetClone
If rst.RecordCount > 0 Then
rst.MoveFirst
xcat = rst!ID
rst.MoveNext
Do While Not rst.EOF
xcat = xcat & ", " & rst!ID
Loop
Else
xcat = ""
End If
test_get_sub_form_record_set = xcat
rst.Close
Set dbs = Nothing
End Function
This would be included in a separate module and when called would return a concatenated, comma separated list of ID's.

Related

MS Access VBA .recordcount returning 0 when records exist, and debug.print returns value

I have an Access table with 10 records and one field of short text. I am using the .recordcount function to return the number of records in this table. Code below:
Dim db as DAO.Database
Dim RS as DAO.Recordset
Dim recCount as Integer
Set db = CurrentDb
Set RS = db.OpenRecordset("Table Name")
RS.MoveFirst
RS.MoveLast
recCount = RS.recordcount
Debug.Print(recCount)
Dim i as Integer
i = 0
RS.MoveFirst
'Option one. Commented out when option two is active and vice verse
Do While i < 10
Debug.Print(RS(i))
i = i + 1
Loop
Do While i < 10
Debug.print(RS![Only Field Name])
i = i + 1
RS.MoveNext
Loop
recCount always prints out to be 0. Attempting to print out the records in the recordset will return the first value only of the recordset and nothing else. After reading the first record, the program throws the error "Item not found in collection." I'm unsure of what could be causing this error, as I use the exact same method with another table in another VBA module, which works just fine.
I look at solutions to this elsewhere and the only one I could find was to add a RS.moveFirst and RS.moveLast after opening, however this does not work. I think this is becuase the opened recordset does not actually contain all the records in the table.
Thanks in advance.
EDIT:
Try this:
Sub Demo_IterateRecords()
Const tblName = "YOUR TABLE NAME HERE"
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset(tblName)
With rs
.MoveLast
.MoveFirst
If MsgBox("Do you want to list all " & .RecordCount & " records?", _
vbOKCancel, "Confirmation") <> vbOK Then GoTo ExitMySub
Do While Not .EOF
Debug.Print .Fields(0), .Fields(1), .Fields(2)
rs.MoveNext
Loop
ExitMySub:
.Close
End With
Set rs = Nothing
End Sub
I used .Fields(_) because I'm not sure what your fields are called, but a better way to refer to them would be by name, like:
Debug.Print !myID, !myEmployeeName, !myEmployeeAddress
Original Answer:
Try this:
RS.MoveLast
RS.MoveFirst
recCount = RS.RecordCount
Debug.Print(recCount)
Access doesn't know how many records there are until you move through them at least once.
If you would have checked the value of RS.RecordCount after your loop, you would have got a number.
Remarks
Use the Recordcount property to find out how many records in a Recordset or TableDef object have been accessed. The RecordCount property doesn't indicate how many records are contained in a dynaset–, snapshot–, or forward–only–type Recordset object until all records have been accessed. Once the last record has been accessed, the RecordCount property indicates the total number of undeleted records in the Recordset or TableDef object. To force the last record to be accessed, use the MoveLast method on the Recordset object. You can also use an SQL Count function to determine the approximate number of records your query will return.
Important Note
Using the MoveLast method to populate a newly opened Recordset negatively impacts performance. Unless it is necessary to have an accurate RecordCount as soon as you open a Recordset, it's better to wait until you populate the Recordset with other portions of code before checking the RecordCount property.
(Source)
See also: MSDN : Recordset.RecordCount Property
I managed to fix this issue but I have no idea why this worked. Instead of creating a new table and typing in the values for the ten records, I instead used an insert query to put the values I wanted from a query into a table. Using this new table, it worked.
You could list the records while counting:
Set RS = db.OpenRecordset("Table Name")
While Not RS.EOF
Debug.Print RS![Only Field Name].Value
i = i + 1
RS.MoveNext
Loop
Debug.Print i & " records found."
Perhaps you could try something similar to this in your sub routine:
Dim db As DAO.Database
Dim RS As DAO.Recordset
Dim recCount As Integer
Set db = CurrentDb
Set RS = db.OpenRecordset("Table Name")
If Not (RS.EOF And RS.BOF) Then
RS.MoveFirst
Do Until RS.EOF = True
RS.MoveNext
Loop
MsgBox ("There are:" & " " & RS.RecordCount & " " & "records in the database")
End If
RS.Close
Set RS = Nothing

VBA Access Object Type Returned For Combobox Field

How can I iterate a record set that returns a field of type field2?
Is there a way to tell how many objects are in the field2 type?
Let me describe the relevant aspects of my table:
The table fields has field NMR which contains a list of possible options a user can select in another table. In the Experiments table, the field NMR is a combobox with populates the options from the other table.
The way I do this is in the Experiments table design, I have set the field this way:
Now in one of my forms, I need to read the value in Experiments!NMR which can be a multiple selections allowed combobox. The recordset rs!NMR is of type Field2.
To get the values, you iterate using an integer (i.e. rs!NMR(0) would return the first selected option). The problem is I don't know how to get the field count and calling !NMR(i) where i is greater than the number of elements will invoke a Run time error '3265', Object doesn't exist in this collection.
Their exist a size method only returns the field width size (4?) and the documentation states this is the size of the data type within the field2 object.
There doesn't seem to be a count method associated with field2 as using !NMR.Count invokes runtime error 438, Object doesn't support this method.
Code:
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim qry As String
qry = "SELECT * FROM Experiments"
Set db = CurrentDb
Set rs = db.OpenRecordset(qry, dbOpenSnapshot)
With rs
Do While Not .EOF
Dim i As Integer
For i = 0 to !NMR.Count ' or SOMETHING - this is the problem
' this is irrelevant, I need to know how to iterate the list
Next i
.MoveNext
Loop
End With
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
I've also tried logic control such as
Do While(!NMR(i) <> vbNullString) since the individual components are strings, but no luck. This issues the same 3265: Item isn't found error. Same for a loop with this check Do While Not IsNull(!NMR(i))
Is there a way to tell how many objects are in the Field !NMR?
You need to assign the complex Field2 to a Recordset2 object and loop through it.
Sub Whatever()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim rsComplex As DAO.Recordset2
Dim qry As String
qry = "SELECT * FROM Experiments"
Set db = CurrentDb
Set rs = db.OpenRecordset(qry, dbOpenSnapshot)
Do While Not rs.EOF
Set rsComplex = rs("NMR").Value
rsComplex.MoveLast
rsComplex.MoveFirst
Dim i As Integer
For i = 0 To rsComplex.RecordCount - 1 ' Asker modified
Debug.Print rsComplex(0)
rsComplex.MoveNext
Next i
rsComplex.Close
Set rsComplex = Nothing
rs.MoveNext
Loop
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
End Sub

Advanced Filter Criteria in Access

The issue is simple but I just cant figure it out.
I have two tables in access, one with records and another with "key words". I need to filter the records containing certain "key words". In other words, use one table field as a filter criteria for the other, but without linking them because the "key words" table just contains random words instead of a whole record.
In excel I can run an advanced filter on my records and just specify as criteria the list of key words (and using wildcards), but in acces I havent found a way to filter according to another table fields.
Any ideas about it?
You may need to create a function that spits out custom SQL with all the keywords in it. Here is an example to get you started.
Public Function fGetTrashRecords()
'add your own error handling
Dim SQL As String
Dim rst As DAO.Recordset
Dim rstTrash As DAO.Recordset
Dim db As DAO.Database
Set db = CurrentDb
Set rst = db.OpenRecordset("SELECT sKeyWord FROM tblBadKeyWords", dbOpenSnapshot)
If Not rst Is Nothing Then
rst.MoveFirst
Do While Not rst.EOF
SQL = SQL & " strFieldContaingKeyWord LIKE *'" & rst!sKeyWord & "'* OR"
rst.MoveNext
Loop
If SQL > "" Then SQL = Left(SQL, Len(SQL) - 2) 'get rid of the last OR
rst.Close
Set rst = Nothing
End If
If SQL > "" Then
Set rstTrash = db.OpenRecordset("SELECT * FROM tblHasKeyWords WHERE " & SQL, dbOpenDynaset, dbSeeChanges)
If Not rstTrash Is Nothing Then
rstTrash.MoveFirst
Do While Not rstTrash.EOF
Debug.Print rstTrash!ID
rstTrash.MoveNext
Loop
rstTrash.Close
Set rstTrash = Nothing
End If
End If
Set db = Nothing
End Function

Accessing all records in a field

Just started using VBA and I'm trying to access all the data in a dummy table I set up called Employees.
This is the code im trying:
Sub getRecords()
Dim dbs As Database
Dim rst As Recordset
Dim sql As String
Set dbs = CurrentDb
sql = "SELECT * FROM Employees"
Set rst = dbs.OpenRecordset(sql)
End Sub
The ultimate aim here is to print the contents to the screen — would this involve breaking down the record set into different components? If so what components could make up a typical record set?
The table format is as follows:
Emp_Id - Number
Emp_Name - Text
Emp_Email - Text
You can iterate through the fields:
Sub getRecords()
Dim dbs As Database
Dim rst As Recordset
Dim sql As String
Set dbs = CurrentDb
sql = "SELECT * FROM Employees"
Set rst = dbs.OpenRecordset(sql)
Do while not rst.eof
For each fld in rst.Fields
Debug.Print fld, fld.name
Next
rst.MoveNext
''You can also edit or add
rst.Edit
rst!Emp_Name = "Something"
rst.UpDate
Loop
End Sub
I would avoid calling variables names that are also properties, such as SQL.
For updates, you are usually best to use an Action query and Execute againt a database object:
db.Execute "UPDATE aTable SET aField = 'Some text'", dbFailOnError
You'll need to start by looping through the records. Try:
Do While Not rst.EOF And Not rst.BOF
...
Loop
To do that. BOF and EOF relate to the beginning and end of the recordset respectively. If there's no data in the table then the whole loop will be skipped.
From there you can look at the fields individually by either using an index to relate to the position of the field in the select list, or by referring to the field name, like so:
Do While Not rst.EOF And Not rst.BOF
Debug.Print rst.Fields("myfield")
Debug.Print rst.Fields(0)
Loop
That's a starting point. Intelisense should really help you with this.
PS: always remember to close your recordset objects afterward to reclaim the memory:
rst.Close()
Set rst = Nothing
Kind regards,
Paul.

Linking Powerpoint and Access through VBA?

I have a Powerpoint slide that contains textboxes. I would like to link those textboxes with a filtered view of a data table in Access.
For ex, if I had a TaskList application in Access that displayed tasks with different priorities and affectations; is there a way to open that file, select that view, and filter it according to a vba (or other) onclick button event triggered from my Powerpoint presentation?
It's certainly possible to get Access data from Powerpoint.
You need to make sure you have the correct references set to theMicrosoft DAO Object Library in your VBA project.
Then, to populate your textbox in your PowerPoint presentation, you can call something like the following function, say, to return a string containing a list of Tasks matching the given TaskPriority.
Function GetTaskListFromAccess(taskPriority as Integer) as String
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim listOfTasks as String
Set db = DBEngine.OpenDatabase(“C:\my_database.accdb”)
Set rs = db.OpenRecordset("SELECT * FROM TaskTable WHERE TaskPriority=" & _
taskPriority, dbOpenSnapshot)
If not rs is nothing then
If rs.RecordCount > 0 then
With rs
While Not .EOF
if listOfTask = "" then
listOfTasks = !TaskName
Else
listOfTasks = listOfTasks & vbCrLf & !TaskName
End If
.MoveNext
Loop
.Close
End With
End If
Set rs = nothing
End If
Set db = nothing
GetTaskListFromAccess = listOfTasks
End Function