I have the following code (which a very helpful person on here wrote based on a previous question). It loops through two tables to determine if an interview is valid and then loops though a gift card table for an unused card. This all works as expected. However, I now realize I need to add a new record to a third table (Receipts) everytime a card is assigned. I have tried using "INSERT INTO..." in the loop but it never puts anything into the Receipts table. The data going to the Receipts table will need to selected from both the Interviews table and the Giftcards table.
On Error GoTo E_Handle
Dim db As DAO.Database
Dim rsInterview As DAO.Recordset
Dim rsGiftcard As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT * FROM [SOR 2 UNPAID Intake Interviews]" _
& " WHERE InterviewTypeId='1' " _
& " AND ConductedInterview=1 " _
& " AND StatusId IN(2,4,5,8)" _
& " AND IsIntakeConducted='1' " _
& " ORDER BY InterviewDate ASC;"
Set rsInterview = db.OpenRecordset(strSQL)
If Not (rsInterview.BOF And rsInterview.EOF) Then
strSQL = "SELECT * FROM Giftcard_Inventory_Query" _
& " WHERE CardType=1 " _
& " AND Assigned=0 " _
& " AND Project=3 " _
& " ORDER BY DateAdded ASC, CompleteCardNumber ASC;"
Set rsGiftcard = db.OpenRecordset(strSQL)
If Not (rsGiftcard.BOF And rsGiftcard.EOF) Then
Do
rsGiftcard.Edit
rsGiftcard!DateUsed = Format(Now(), "mm/dd/yyyy")
rsGiftcard!Assigned = "1"
rsGiftcard.Update
db.Execute " INSERT INTO [SOR 2 Intake Receipts] " _
& "(PatientID,GiftCardType,GiftCardNumber,GiftCardMailedDate,InterviewDate,CreatedBy,GpraCollectorID) VALUES " _
& "(rsInterview!PatientID, rsGiftcard!CardType, rsGiftcard!CompleteCardNumber, Now(), rsInterview!InterviewDate, rsInterview!CreatedBy, rsInterview!GpraCollectorID);"
rsGiftcard.MoveNext
rsInterview.MoveNext
Loop Until rsInterview.EOF
End If
End If
sExit:
On Error Resume Next
rsInterview.Close
rsGiftcard.Close
Set rsInterview = Nothing
Set rsGiftcard = Nothing
Set db = Nothing
Exit Sub
E_Handle:
MsgBox Err.Description & vbCrLf & vbCrLf & "sAssignGiftCards", vbOKOnly + vbCritical, "Error: " & Err.Number
Resume sExit
I figured it out. Thanks to everyone who pushed me in the correct direction.
On Error GoTo E_Handle
Dim db As DAO.Database
Dim rsInterview As DAO.Recordset
Dim rsGiftcard As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT * FROM [SOR 2 UNPAID Intake Interviews]" _
& " WHERE InterviewTypeId='1' " _
& " AND ConductedInterview=1 " _
& " AND StatusId IN(2,4,5,8)" _
& " AND IsIntakeConducted='1' " _
& " ORDER BY InterviewDate ASC;"
Set rsInterview = db.OpenRecordset(strSQL)
If Not (rsInterview.BOF And rsInterview.EOF) Then
strSQL = "SELECT * FROM Giftcard_Inventory_Query" _
& " WHERE CardType=1 " _
& " AND Assigned=0 " _
& " AND Project=3 " _
& " ORDER BY DateAdded ASC, CompleteCardNumber ASC;"
Set rsGiftcard = db.OpenRecordset(strSQL)
If Not (rsGiftcard.BOF And rsGiftcard.EOF) Then
Do
rsGiftcard.Edit
rsGiftcard!DateUsed = Format(Now(), "mm/dd/yyyy")
rsGiftcard!Assigned = "1"
rsGiftcard.Update
db.Execute " INSERT INTO [SOR 2 Intake Receipts] " _
& "(PatientID,GiftCardType,GiftCardNumber,GiftCardMailedDate,InterviewDate,CreatedBy,GpraCollectorID) VALUES " _
& "('" & rsInterview("PatientID") & "', '" & rsGiftcard("CardType") & "', '" & rsGiftcard("CompleteCardNumber") & "', Now(), '" & rsInterview("InterviewDate") & "', '" & rsInterview("CreatedBy") & "', '" & rsInterview("GpraCollectorID") & "');"
rsGiftcard.MoveNext
rsInterview.MoveNext
Loop Until rsInterview.EOF
End If
End If
sExit:
On Error Resume Next
rsInterview.Close
rsGiftcard.Close
Set rsInterview = Nothing
Set rsGiftcard = Nothing
Set db = Nothing
Exit Sub
E_Handle:
MsgBox Err.Description & vbCrLf & vbCrLf & "sAssignGiftCards", vbOKOnly + vbCritical, "Error: " & Err.Number
Resume sExit
Related
I am using MS Access 2010. I am trying to search a table and determine if the record exists based on First and Last name, If the record exists then update the record, and if it does not exist, then insert the new record. I am not getting any errors but I always get a recordcount of 1 even if I enter a name that I know does not exist in the table.
Private Sub txtSearchFirstName_Exit(Cancel As Integer)
Dim strSQL As String
Dim db As Database
Dim rs As DAO.Recordset
Dim recordCount As Long
Set db = CurrentDb
Set rs = Nothing
Stop
''Check if a keyword entered or not
If IsNull(Me.txtSearchlastName) = "" Then
MsgBox "Please type in your search keyword.", vbOKOnly, "Keyword Needed"
Else
strSQL = "SELECT COUNT(*) " & _
"FROM tblBobbettesMarketBulletin_CustNum " & _
"WHERE tblBobbettesMarketBulletin_CustNum.Last = " & Chr(34) & txtSearchlastName & Chr(34) & _
" AND tblBobbettesMarketBulletin_CustNum.First = " & Chr(34) & txtSearchFirstName & Chr(34)
Debug.Print strSQL
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
If (rs.BOF And rs.EOF) Then
recordCount = 0
Else
rs.MoveLast
recordCount = rs.recordCount
End If
If recordCount > 0 Then MsgBox ("Record exists")
If recordCount = 0 Then MsgBox ("Record does not exist")
rs.Close
Set rs = Nothing
End If
End Sub
#HansUp describes your problem perfectly.
If you want to simplify the code and use this feature, assign a field name to your Count(*) and then query and use its value in one step
strSQL = "SELECT COUNT(*) AS NumFound " & _
"FROM tblBobbettesMarketBulletin_CustNum " & _
"WHERE tblBobbettesMarketBulletin_CustNum.Last = " & Chr(34) & txtSearchlastName & Chr(34) & _
" AND tblBobbettesMarketBulletin_CustNum.First = " & Chr(34) & txtSearchFirstName & Chr(34)
Debug.Print strSQL
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
MsgBox ("Found " & rs!NumFound & " Record(s)")
Public Sub UpdateTermFeedbackAddlReqt(ByVal runid As Integer, ByVal BHTerm As String, ByVal username As String, ByVal currtime As Double)
Dim db As DAO.Database
Dim rs As DAO.Recordset
DoCmd.SetWarnings False
Set db = CurrentDb
sql = "SELECT tbl_SCG_ExpectedTraffic.BHTerm, Sum(tbl_SCG_ExpectedTraffic.CurrSent2) AS SumOfCurrSent2, iif(Sum([CurrSent2]) = 0, 0, Sum([Accepted])/Sum([CurrSent2])) AS [Term Accept Rate], Sum(tbl_SCG_ExpectedTraffic.Accepted) AS SumOfAccepted, Sum(tbl_SCG_ExpectedTraffic.Rejected) AS SumOfRejected, Sum(tbl_SCG_ExpectedTraffic.Modified) AS SumOfModified, Sum(tbl_SCG_ExpectedTraffic.CurrCalledin) AS SumOfCalledin, Sum([ExpTotal])-Sum([CurrSent2]) AS [Need to Send]" & _
" FROM tbl_SCG_ExpectedTraffic" & _
" GROUP BY Date(), tbl_SCG_ExpectedTraffic.BHTerm, tbl_SCG_ExpectedTraffic.OptRunID" & _
" HAVING (((tbl_SCG_ExpectedTraffic.OptRunID)=" & runid & ") And BHTerm= """ & BHTerm & """);"
Set rs = db.OpenRecordset(sql, dbOpenDynaset, dbSeeChanges)
DoCmd.RunSQL ("Update tbl_SCG_TerminalFeedback set [CurrentSend2] = " & rs![SumOfCurrSent2] & ", [Term Accept Rate] =" & rs![Term Accept Rate] & ", Accepted= " & rs![SumOfAccepted] & ", Rejected = " & rs![SumOfRejected] & ", Modified =" & rs![SumOfModified] & ", Calledin = " & rs![SumOfCalledin] & ", AddlReqst =" & rs![Need To Send] & _
",[Last Update User] =""" & username & """, [Last Update Time]= " & currtime & " , HrDiff = iif( isnull(DLookup(""SubmissionDT"", ""tbl_SCG_OptRunSummary"", ""OptRunID = " & runid & """)), 0, Round((" & currtime & " - DLookup(""SubmissionDT"", ""tbl_SCG_OptRunSummary"", ""OptRunID =" & runid & """)) * 24, 1))" & _
" where OptRunID = " & runid & " And Term = """ & BHTerm & """")
DoCmd.SetWarnings True
rs.Close
db.Close
End Sub
In Access 2010 I have tables, e.g. Employee(Pracownicy). I can update the data in the table using the subform and the update button.
Updating the data in the subform automatically generates an Outlook mail containing the data in the updated record.
I need to change font color for updated data in the mail body.
The code to update the data and generate e-mail:
Private Sub cmdUpdate2_Click()
CurrentDb.Execute "update Pracownicy" & _
" SET Identyfikator='" & Me.txtID & "'" & _
", Imie='" & Me.txtImie & "'" & _
", Nazwisko ='" & Me.txtNazwisko & "'" & _
", Wiek ='" & Me.txtWiek & "'" & _
", Data_urodzenia ='" & Me.txtData & "'" & _
", Miejsce_urodzenia ='" & Me.txtMiejsce & "'" & _
", Miejscowosc ='" & Me.txtMiejscowosc & "'" & _
", Plec ='" & Me.txtPlec & "'" & _
" where Identyfikator='" & Me.txtID & "'"
'------------------------------------SEND EMAIL----------------------
'Dim varName As Variant
'Dim strUCC As String
Dim varSubject As Variant
Dim varBody As Variant
Dim Poczta As Object
Dim MojMail As Object
On Error Resume Next
'varName = ""
varSubject = "Employer List "
varBody = "Hello" & _
"<br><br>Employer List: " & _
"<br><br><B>Identyfikator:</B> " & Me.txtID & " " & _
"<br><B>Imie:</B> " & Me.txtImie & " " & _
"<br><B>Nazwisko:</B> " & Me.txtNazwisko & " " & _
"<br><B>Wiek:</B> " & Me.txtWiek & " " & _
"<br><B>Data urodzenia:</B> " & Me.txtData & " " & _
"<br><B>Miejsce urodzenia:</B> " & Me.txtMiejsce & " " & _
"<br><B>Miejscowosc:</B> " & Me.txtMiejscowosc & " " & _
"<br><B>Plec:</B> " & Me.txtPlec & " "
Set Poczta = CreateObject("outlook.application")
Set MojMail = Poczta.createitem(0)
With MojMail
'.To =
'.BCC =
.subject = varSubject
'.ReadReceiptRequested = True
'.originatorDeliveryReportRequested = True
.htmlbody = varBody & "<br>"
.display
'.send
End With
Set Poczta = Nothing
Set MojMail = Nothing
If Err.Number <> 0 Then
MsgBox ("Atention")
End If
On Error GoTo 0
'------------------------------------------------------------------------
DoCmd.Close
MsgBox ("End Update")
End Sub
I think this becomes more of an HTML question rather than VBA. Try adding a FONT tag to the following line and see if that works for you.
"<br><br><B><font color="red">Identyfikator:</font></B> " & Me.txtID & " " & _
I have a macro that pulls from an Access DB and writes the recordset to the spreadsheet based upon dates that are entered into a userform. However, if I enter in "3/2/2105" and "3/5/2015" it returns all the records from 3/2-3/5 and then 3/20-3/31. I cannot think of any reason why it would do this. If anybody could point me in the right direction/make suggestions it would be greatly appreciated.
Sub pullfrommsaccess()
queryform.Show
Dim conn As Object
Dim rs As Object
Dim AccessFile As String
Dim SQL As String
Dim startdate As String
Dim enddate As String
Dim i As Integer
Sheet2.Cells.Delete
Application.ScreenUpdating = False
AccessFile = ThisWorkbook.Path & "\" & "mdidatabase.accdb"
On Error Resume Next
Set conn = CreateObject("ADODB.connection")
If Err.Number <> 0 Then
MsgBox "Connection was not created!", vbCritical, "Connection Error"
Exit Sub
End If
On Error GoTo 0
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & AccessFile
If tblname = "Attainments" Then
If shift1 = "1" Then
SQL = "SELECT [Line],[Area],[Shift],[Attainment Percentage],[Date] FROM " & tblname & " WHERE Shift='1' and Date Between " & "'" & pastdate & "' " & "and" & " '" & currentdate & "'"
End If
If shift2 = "2" Then
SQL = "SELECT [Line],[Area],[Shift],[Attainment Percentage],[Date] FROM " & tblname & " WHERE Shift='2' and Date Between " & "'" & pastdate & "' " & "and" & " '" & currentdate & "'"
End If
If shift1 = "1" And shift2 = "2" Then
SQL = "SELECT [Line],[Area],[Shift],[Attainment Percentage],[Date] FROM " & tblname & " WHERE Date Between " & "'" & pastdate & "' " & "and" & " '" & currentdate & "'"
End If
End If
If tblname = "MDItable" Then
If shift1misses = "1" Then
SQL = "SELECT [Date],[Area],[Shift],[Line],[Quantity],[Issue] FROM " & tblname & " WHERE Shift='1' and Date Between " & "'" & pastdatemisses & "' " & "and" & " '" & currentdatemisses & "'"
End If
If shift2misses = "2" Then
SQL = "SELECT [Date],[Area],[Shift],[Line],[Quantity],[Issue] FROM " & tblname & " WHERE Shift='2' and Date Between " & "'" & pastdatemisses & "' " & "and" & " '" & currentdatemisses & "'"
End If
If shift1misses = "1" And shift2misses = "2" Then
SQL = "SELECT [Date],[Area],[Shift],[Line],[Quantity],[Issue] FROM " & tblname & " WHERE Date Between " & "'" & pastdatemisses & "' " & "and" & " '" & currentdatemisses & "'"
End If
End If
On Error Resume Next
Set rs = CreateObject("ADODB.Recordset")
If Err.Number <> 0 Then
Set rs = Nothing
Set conn = Nothing
MsgBox "Recordset was not created!", vbCritical, "Recordset Error"
Exit Sub
End If
On Error GoTo 0
rs.CursorLocation = 3
rs.CursorType = 1
rs.Open SQL, conn
If rs.EOF And rs.BOF Then
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
Application.ScreenUpdating = True
MsgBox "There are no records in the recordset!", vbCritical, "No Records"
Exit Sub
End If
For i = 0 To rs.Fields.Count - 1
Sheet2.Cells(1, i + 1) = rs.Fields(i).Name
Next i
'Copy From RecordSet to Excel and Reset
Sheet2.Range("A2").CopyFromRecordset rs
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
MsgBox "The records from " & pastdate & " and " & currentdate & " were successfully retrieved from the '" & tblname & "' table!", vbInformation, "Done"
End If
Call TrimALL
End Sub
You have a field named Date, try renaming that and reworking the code as in first instance that's a reserved word and is a bad idea for starters!
When working with dates, see Allen Browne's comments on the matter here for consistency;
http://allenbrowne.com/ser-36.html
You have your dates declared as string, but in your SQL query you're surrounding them with a ' not a #. It should read;
Date Between " & "#" & pastdate & "# " & "and" & " #" & currentdate & "#"
All of the above should sort you out, if not comment and I'll take a much closer look for you!
I'm new to VBA. Right now, I want to create editable crosstab table using temp table. I have problem when I want to update the normalize table based on edited data. When I run my codes, I get this error, Error 3061: Too Few Parameters.Expected 2.Can somebody help me to check my codes? Thanks in advance
Public Sub Normalize()
Dim rs As DAO.Recordset
On Error GoTo EH
'delete existing data from temp table
CurrentDb.Execute "DELETE * FROM tblNormalize;", dbFailOnError + dbSeeChanges
'get a recordset of the column headers
Set rs = CurrentDb.OpenRecordset("SELECT DISTINCT newvalue FROM Table1;")
Debug.Print
rs.MoveFirst
Do While rs.EOF = False
' "un" crosstab the data from crosstab table into Normalize table
CurrentDb.Execute "INSERT INTO tblNormalize (product, spec, descr,newvalue, Rate )" & Chr(10) & _
"SELECT product,spec,descr, " & rs.Fields("newvalue") & ", [" & rs.Fields("newvalue") & "]" & Chr(10) & _
"FROM tblCrosstab;", dbFailOnError + dbSeeChanges
Debug.Print rs.Fields("newvalue")
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
'update the original normalized dataset
CurrentDb.Execute "UPDATE tblNormalize INNER JOIN Table1 t1 ON (tblNormalize.newvalue = t1.newvalue) " & _
" AND (tblNormalize.product = t1.product) AND (tblNormalize.spec = t1.spec) " & _
" AND (tblNormalize.descr = t1.descr)" & _
" SET Table1.Rate = tblNormalize.Rate;", dbFailOnError + dbSeeChanges
Exit Sub
EH:
MsgBox "Error " & Err.Number & ": " & Err.Description, vbOKOnly, "Error"
End Sub
You are creating a world of hurt for yourself. Apart from that, this:
"INSERT INTO tblNormalize (product, spec, descr,newvalue, Rate )" & Chr(10) & _
"SELECT product,spec,descr, " & rs.Fields("newvalue") & ", [" & rs.Fields("newvalue") & "]" & Chr(10) & _
"FROM tblCrosstab;"
Is going to come out all wrong.
Try:
"INSERT INTO tblNormalize (product, spec, descr,newvalue, Rate )" & _
" SELECT product,spec,descr, " & rs.Fields("newvalue") & ", [" _
& rs.Fields("newvalue") & "] FROM tblCrosstab;"
Also, use Debug.Print to write the string to the immediate window (Ctrl+G) and check if it works in the query design window. That error is usually due to misspelling of missing fields (columns).