I have a Microsoft Access 2010 table with 3 columns.
The first column contains the numerical sequential primary key ID
The 2nd contains site names.
The 3rd contains yes/no for each site.
I want to do a loop through the 2nd column to perform an action for every field in column 2 where the entry in column 3 is 'Yes'.
The code I am trying to use which isn't working for me is
Set rs = db.OpenRecordset("table1")
Set rs2 = rs.Fields("Column2")
set rs3 = rs.fields("Column3")
For each fld in rs2
If rs3.fields = "Yes" then
"The action code would follow here etc etc"
Next fld
End if
Loop
The code doesn't seem to like "For each fld in rs2"
I would appreciate any help with this
Many Thanks
The first recordset already has all the fields.
Set rs = db.OpenRecordset("table1")
Do While Not rs.EOF
' Alternatively: rs("Column3")
If rs!Column3 = "Yes" Then
' stuff
End If
' Next record
rs.MoveNext
Loop
But: what you want to do in a Recordset loop can most probably be done easier and more efficient in SQL with an UPDATE query.
Related
I am just looking for some direction as all of my attempts to create a successful loop have failed.
I have a table named "tblContacts" which has 4 fields - ID (primary key), ACCT NUM, CONTACT NAME, CONTACT EMAIL.
Within the same database I have a query named "qryLPContact" which has multiple fields - ID (primary key), ACCT NUM, CONTACT NAME, etc....
The qryContactLP can have the same ACCT NUM on there multiple times but with different information in other fields. My end goal is to Loop through my query results and perform the following:
1. Find the CONTACT EMAIL in tblContact by using the ID field from qryContactLP
2. Loop through the qryContactLP results and find all matching IDs
---stop or pause the loop
3. Create an output as an excel attachment for the ID
4. Move to the next ID on the qryContactLP and output as excel and attach
I have gotten pretty far in the code but still cannot get the above to work. The email and loop work well except for the fact that I get a separate email for every record and it only includes the ID. I need the entire record.
For example qryContactLP results below:
ID ACCT NUM CLIENT NAME EMP ID BRANCH
1 1243567 RUBY 99655 25
2 7654321 PAUL 99622 18
2 7654321 PAUL 99354 18
2 7654321 PAUL 99712 18
3 5678439 SAM 857632 32
The expected result would be for me to have 3 emails generated. However, I receive 5.
Any help would be greatly appreciated, I am on week 2 and I still can't figure this out.
Sub loopTable()
Dim strSQL As String
Dim rs As DAO.Recordset
strSQL = "SELECT *FROM qryContactLP WHERE [ACCT NUM] IN (SELECT [ACCT NUM] FROM qryContactLP WHERE ID = ID)" 'define the SQL result that you want to loop
Set rs = CurrentDb.OpenRecordset(strSQL)
If Not rs.BOF And Not rs.EOF Then
rs.MoveFirst
While (Not rs.EOF)
Debug.Print rs.Fields("ID")
rs.MoveNext
Wend
End If
rs.Close
Set rs = Nothing
End Sub
The nested query criteria makes no sense. Also, missing a space after the * character.
The easiest approach for exporting data is attaching a PDF of the desired dataset and a filtered report is easiest way to do that.
Sub SendEmail()
Dim strSQL As String
Dim rs As DAO.Recordset
strSQL = "SELECT * FROM tblContacts"
Set rs = CurrentDb.OpenRecordset(strSQL)
If Not rs.BOF And Not rs.EOF Then
rs.MoveFirst
Do While Not rs.EOF
DoCmd.OpenReport "reportname", acViewPreview, , "ID = " & rs!ID
DoCmd.SendObject acSendReport, "reportname", acFormatPDF, rs![contact email], , , "subject text here", "message text here", True
DoCmd.Close acReport, "reportname", acSaveNo
rs.MoveNext
Loop
End If
rs.Close
Set rs = Nothing
End Sub
If you want email sent without review, set the EditMessage argument to False.
Some simple reports can export to Excel. So instead of acFormatPDF, try acFormatXLS.
Exporting a dynamic filtered query object would need code using QueryDefs to set the parameters with values. Example in How to send parameters to microsoft access query so that I can import an access parameter query to excel?
Embedding multiple records in email body requires HTML code tags to build a table and also uses Outlook automation. SendObject will not work for this. One example Access VBA To Send Query Results to Outlook Email in Table Format
basic question.
I need to delete all null/blank rows of a table in my database. Trouble is there is no way to know how many fields there are, or the names of the fields before the delete. And I need to verify every field is null/blank before deleting. Not sure how to query for this in Access VBA.
In all the examples I find, they have a field name they can test for blanks.
Thanks in advance.
Change TestTabke to your table name. If you have an AutoNumber field, it must be skipped. I am using DAO. If you want ADO, convert the following code.
Function DeleteEmptyRows()
Dim db As DAO.database
Set db = CurrentDb
Dim rs As DAO.recordSet
Set rs = db.OpenRecordset("TestTable")
Do Until rs.EOF
For inx = 0 To rs.Fields.Count - 1
If IsNull(rs.Fields(inx).Value) Or Len(Trim(rs.Fields(inx).Value)) = 0 Then
Else: Exit For
End If
Next
If rs.Fields.Count = inx Then
rs.Delete
End If
rs.MoveNext
Loop
End Function
I have a query OUTPUT with cols DATE, TYPE, VALUE. I need to gather all the different dates into a variable so I can later create a CSV file for each unique DATE.
I tried creating a record set, and assigning the values of DATE to a variable as such:
Sub GetDates()
Dim rst As Recordset
Dim db As Database
Dim arrDates As Variant
Set db = CurrentDb
Set rst = db.OpenRecordset("SELECT Date FROM OUTPUT GROUP BY DATE; ")
arrDates = rst.GetRows()
but when I do:
For Each Item In arrDates
Debug.Print (Item)
Next
I only get one date printed (11/01/2012). If I run the query in Access, I see all 15 months.
I had to specify the number of rows:
arrDates = rst.GetRows(rst.RecordCount)
A better solution, as recommended by Remou:
Do Until rst.EOF
Debug.Print rst!Date
rst.MoveNext
Loop
Edit: I was reading the wrong MSDN help.
I'm looking to iterate through a set of fields as part of a table that follow a specific format. The table contains N pairs of these fields (Var_1, Value_1, Var_2, Value_2, etc).
I need to iterate through these fields and extract the data to write it out to a text file. I'd like to use a loop, I'd rather not hardcode each field into my VBA as the fields will likely grow in time and not every field will be populated for every record. I guess if there was a way to "evaluate" a field when its name is dynamically created in a string, that would solve my problem.
So, for example...
For i = 1 to FieldCount
' Write data to each field
Initially I thought of something like this
For i=1 to FieldCount
myStr = "!Var_"+CStr(i) + " = " + "!Value_" + CStr(i)
WriteLine(myStr)
but course, it prints the text literally... any way to get Access to evaluate that text first?
Perhaps there is a better way to approach this entirely?
You can use your record set's Fields collection, and refer to the value of any individual field by referencing the field's name.
rs.Fields("field_name").Value
You can generally drop the explicit .Value since that's the field's default property.
Public Sub printFieldPairs()
Dim strSql As String
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim N As Long
strSql = "SELECT * FROM tblJoeS;"
Set db = CurrentDb
Set rs = db.OpenRecordset(strSql)
With rs
Do While Not .EOF
For N = 1 To 3
Debug.Print .Fields("Var_" & N) & " = " & _
.Fields("Value_" & N)
Next N
.MoveNext
Loop
End With
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub
That's what I think you're asking for. However, if the number of field pairs grows, you will have to revise the table structure. So my inclination would be to use a different table structure.
row_identifier fKey fValue
1 Var_1 foo
1 Var_2 bar
1 Var_3 baz
2 Var_1 abcd
As suggested improvement to HansUp answer:
....
Dim fld as DAO.Field
For Each fld in rs.fields
debug.? fld.value
Next fld
I have a Tabular type Form based upon a SELECT * FROM table type of query in MS access.
I would like to:
check / select rows in this form
iterate through the checked / selected rows
You can use the recordset or the recordsetclone.
With Me.Recordsetclone
.MoveFirst
Do While Not .EOF
MsgBox "Field 1 is: " & .Fields(1)
.MoveNext
Loop
End with
You can also allow the user to highlight records and work with those (http://support.microsoft.com/kb/208502).
Function DisplaySelectedCompanyNames()
Dim i As Long
Dim frm As Form
Dim rs As DAO.Recordset
'' Get the form and its recordset.
Set frm = Forms![Customers]
Set rs = frm.RecordsetClone
'' Move to the first record in the recordset.
rs.MoveFirst
'' Move to the first selected record.
rs.Move frm.SelTop - 1
'' Enumerate the list of selected records presenting
'' the CompanyName field in a message box.
For i = 1 To frm.SelHeight
MsgBox rs![CompanyName]
rs.MoveNext
Next i
End Function