I'm not a VBA expert. I simply copy from the net and try to utilize in my program. however, below is my codes. I'm trying to calculate a finish date considering offdays, but the issue is sometime the time required is less than one day in that case it is calculating as 1 day. How can I calculate it by hours. Suppose if the startdate is 1-jan-2019 6:00 am and the required time to produce is 6 hours than the finish time should be 1-jan-2019 12:00pm
Public Function AddFinishDate(StartDate As Date, ReqDays As Double, FriOff As Boolean) As Date
Dim rst As Recordset
Dim db As Database
Dim FinishDate As Date
Dim icount As Integer
On Error GoTo errhandlers:
Set db = CurrentDb
Set rst = db.OpenRecordset("tblHoliday", dbOpenSnapshot)
icount = 0
FinishDate = StartDate
Do While icount < ReqDays
FinishDate = FinishDate + 1
If Weekday(FinishDate, vbSaturday) <> 7 Or FriOff = False Then
rst.FindFirst "(HolidayDate)= #" & FinishDate & "#"
If rst.NoMatch Then
icount = icount + 1
End If
End If
Loop
AddFinishDate = FinishDate
exit_errhandlers:
rst.Close
Set rst = Nothing
Set db = Nothing
AddFinishDate = FinishDate
Exit Function
errhandlers:
MsgBox Err.Description, vbExclamation
Resume Next
End Function
Private Sub Command53_Click()
Dim dbs As DAO.Database
Set dbs = CurrentDb()
dbs.Execute "UPDATE BalFitToFabricate " & "SET used = false , startdate ="""",finishdate ="""";"
Me.Refresh
End Sub
Private Sub Command71_Click()
Dim dbs As DAO.Database, Initrst, rst, rst2 As DAO.Recordset
Dim strSQL
Dim ClientsTableQuery, SalesRepList As TableDef
Dim DataB As Database
Dim ClientQD As QueryDef
Dim rstClient As DAO.Recordset
Dim DurationTotal, Counter, i As Integer
Dim LowDate1, LowDate2 As Date
Dim tmpArray(10), FieldArray(10), TempDate1, TempDate2 As Date
Dim TotalDailyHrs, TempDailyHours As Integer
Dim FirstTimeIn As Boolean
FirstTimeIn = False
TotalDailyHrs = Forms("BalFitToFabricate").Text49.Value
TempDailyHours = TotalDailyHrs
Set dbs = CurrentDb()
ClientsTableQuery = "BalFitToFabricate"
'strSQL = "Select * from Client_Table"
Set DataB = CurrentDb()
Set rstClient = DataB.OpenRecordset(ClientsTableQuery)
rstClient.MoveFirst
Counter = 0
Set Initrst = dbs.OpenRecordset("SELECT * FROM BalFitToFabricate;")
'Set rst = dbs.OpenRecordset("SELECT * FROM BalFitToFabricate;")
Set rst = dbs.OpenRecordset("SELECT * FROM (SELECT * FROM (SELECT * FROM BalFitToFabricate WHERE Used = false)) WHERE FinishDate = (select min(FinishDate) from BalFitToFabricate where Used = false);")
Set rst2 = dbs.OpenRecordset("SELECT * FROM BalFitToFabricate WHERE isnull(StartDate) order by NULLSORTER,Req_Del_Date,Priority;")
'Autonumrst.Requery
'MsgBox Initrst.RecordCount & " " & rst.RecordCount & " " & rst2.RecordCount
'First Loop
Do Until rstClient.EOF = True
If TempDailyHours <= TotalDailyHrs Then
'Autonumrst.Requery
'If FirstTimeIn = False Then
' TotalDailyHrs = TotalDailyHrs - TempDailyHours
'End If
TempDailyHours = Initrst![CreqHours]
Dim Autonumrst, Valuesrst As DAO.Recordset
Dim strSQL2, strSQL3 As String
'strSQL2 = "SELECT [Crew Hours] FROM Table2 where AutoNum = " & Initrst!Autonum & "and used = false;"
strSQL2 = "SELECT [CreqHours] FROM Table2 where Used = False;"
strSQL3 = "SELECT * FROM Table2 where Used = False;"
Set Autonumrst = CurrentDb.OpenRecordset(strSQL2)
Set Valuesrst = CurrentDb.OpenRecordset(strSQL3)
' new code:
'Stopped 2 lines
'TempDailyHours = Autonumrst![Crew Hours]
'Autonumrst.Requery
'Autonumrst.Close
'TempDailyHours = dbs.Execute "select BalFitToFabricate " & "SET startdate = #" & TempDate1 & "# WHERE Autonum = " & Initrst!Autonum & ";"
TotalDailyHrs = TotalDailyHrs - TempDailyHours
If TotalDailyHrs > 0 Then
TempDate1 = Format([Forms]![BalFitToFabricate]![Text51].Value, "mm-dd-yyyy")
'TempDate1 = [Forms]![BalFitToFabricate]![Text68].Value
dbs.Execute "UPDATE BalFitToFabricate " & "SET startdate = #" & TempDate1 & "# WHERE ID = " & Initrst!ID & ";"
TempDate2 = AddFinishDate(Format(TempDate1, "mm-dd-yyyy"), Initrst!ReqDays, Me.FridayOffCheckBox2)
dbs.Execute "UPDATE BalFitToFabricate " & "SET finishdate = #" & TempDate2 & "# WHERE ID = " & Initrst!ID & ";"
'TempDate1 = strSQL59 + (strSQL22 / strSQL57)
'TempDate2 = Format(TempDate1 + (Valuesrst![Total_Req_Manhours] / Valuesrst![Crew Hours]), "dd-mm-yyyy")
'dbs.Execute "UPDATE BalFitToFabricate " & "SET Finishdate = #" & TempDate2 & "# WHERE Autonum = " & Initrst!AutoNum & ";"
dbs.Execute "UPDATE BalFitToFabricate " & "SET Used = True WHERE ID = " & Initrst!ID & ";"
End If
Initrst.MoveNext
'Autonumrst.MoveNext
Else
GoTo ExitLoop1
End If
Loop
ExitLoop1:
'MsgBox rst!Ord_No & " " & rst2!Ord_No
dbs.Execute "UPDATE BalFitToFabricate " & "SET Used = False;"
TotalDailyHrs = Forms("BalFitToFabricate").Text49.Value
TempDailyHours = TotalDailyHrs
'Second Loop
Do Until rstClient.EOF = True
'Counter = Counter + 1
'i = rstClient!Ord_No
'If rstClient.Fields("Duration") <> "" Then
' DurationTotal = DurationTotal + rstClient.Fields("Duration")
'FieldArray(Counter) = rstClient.Fields("End")
'End If
'If DurationTotal >= 15 Then
If TempDailyHours <= TotalDailyHrs Then
'If rstClient!Used = False Then
strSQL3 = "SELECT * FROM Table2 where Finishdate is null;"
Set Valuesrst = CurrentDb.OpenRecordset(strSQL3)
Valuesrst.Requery
'Counter = rst2.RecordCount
Dim temp22 As Integer
temp22 = rst.RecordCount
rst.Requery
rst2.Requery
If rst2.RecordCount <= 0 Then
GoTo ExitLoop2
End If
LowDate1 = "#" & rst!FinishDate & "#"
'LowDate2 = "#" & Valuesrst!finishdate & "#"
'End If
''Set dbs = OpenDatabase("database41.accdb")
TempDate1 = Format(rst!FinishDate, "mm-dd-yyyy")
dbs.Execute "UPDATE BalFitToFabricate " & "SET Used = true WHERE ID = " & rst!ID & ";"
dbs.Execute "UPDATE BalFitToFabricate " & "SET startdate = #" & TempDate1 & "# WHERE ID = " & rst2!ID & ";"
'TempDate1 = Format([Forms]![BalFitToFabricate]![Text59].Value + ([Forms]![BalFitToFabricate]![Text22].Value / [Forms]![BalFitToFabricate]![Text57].Value), "dd-mm-yyyy")
'TempDate1 = Format(Valuesrst![StartDate] + (Valuesrst![Total_Req_Manhours] / Valuesrst![Crew Hours]), "dd-mm-yyyy")
'dbs.Execute "UPDATE BalFitToFabricate " & "SET Finishdate = #" & TempDate1 & "# WHERE Autonum = " & Valuesrst!AutoNum & ";"
TempDate2 = AddFinishDate(Format(TempDate1, "mm-dd-yyyy"), rst!ReqDays, Me.FridayOffCheckBox2)
dbs.Execute "UPDATE BalFitToFabricate " & "SET finishdate = #" & TempDate2 & "# WHERE ID = " & rst2!ID & ";"
End If
'rstClient.MoveNext
Loop
ExitLoop2:
MsgBox "Finished Scheduling " & DurationTotal & "Time: " & Time()
rstClient.Close
[Forms]![BalFitToFabricate].Refresh
End Sub
This is not that easy, if you don't work round the clock. I have an old function that takes off-hours and weekends in consideration, though not holidays:
Public Function WorkhourAdd( _
ByVal datDateStart As Date, _
ByVal intHours As Integer) _
As Date
' Purpose: Add number of working hours to date datDateStart.
' Assumes: 5 working days per week. Adjust cbytWorkdaysOfWeek for other values.
' First workday is Monday.
' Weekend is up to and including Sunday.
' Limitation: Does not count for public holidays.
' May be freely used and distributed.
'
' 2011-01-15. Gustav Brock, Cactus Data ApS, Copenhagen
' Specify begin and end time of daily working hours.
Const cdatWorkTimeStart As Date = #8:00:00 AM#
Const cdatWorkTimeStop As Date = #4:00:00 PM#
Const cbytWorkdaysOfWeek As Byte = 5
Dim intCount As Integer
Dim datDateEnd As Date
datDateEnd = datDateStart
While intCount < intHours
datDateEnd = DateAdd("h", 1, datDateEnd)
If Weekday(datDateEnd, vbMonday) <= cbytWorkdaysOfWeek Then
If DateDiff("h", cdatWorkTimeStart, TimeValue(datDateEnd)) > 0 Then
If DateDiff("h", TimeValue(datDateEnd), cdatWorkTimeStop) >= 0 Then
intCount = intCount + 1
End If
End If
End If
Wend
WorkhourAdd = datDateEnd
End Function
You could modify it to check if time is within a holiday, to find finish time across holidays.
Related
I have three listboxes and a date range on a parameter form. I am able to pass all of the Listbox selections with no problem. I cannot seem to find a way or answer to adding a date range to the where clause.
The Date field is Course_Date, and the textbox control names for the dates are Start_Date and End_Date
Option Compare Database
Option Explicit
Private Sub cmdPreviewReports_Click()
On Error GoTo cmdPreviewReports_Err
Dim blnQueryExists As Boolean
Dim cat As New ADOX.Catalog
Dim cmd As New ADODB.Command
Dim qry As ADOX.View
Dim varItem As Variant
Dim strInstructors As String
Dim strCourseType As String
Dim strCourseTypeCondition As String
Dim strRoleType As String
Dim strRoleTypeCondition As String
Dim strCourse_Date As Date
Dim strDateRange As String
Dim strSql As String
' Check for the existence of the stored query
blnQueryExists = False
Set cat.ActiveConnection = CurrentProject.Connection
For Each qry In cat.Views
If qry.Name = "q_Parameter_Form" Then
blnQueryExists = True
Exit For
End If
Next qry
' Create the query if it does not already exist
If blnQueryExists = False Then
cmd.CommandText = "SELECT * FROM q_jt_MCR_Instructor_Roles"
cat.Views.Append "q_Parameter_Form", cmd
End If
Application.RefreshDatabaseWindow
' Turn off screen updating
DoCmd.Echo False
' Close the query if it is already open
If SysCmd(acSysCmdGetObjectState, acQuery, "q_Parameter_Form") = acObjStateOpen Then
DoCmd.Close acQuery, "q_Parameter_Form"
End If
' Build criteria string for Instructors
For Each varItem In Me.lst_Instructors.ItemsSelected
strInstructors = strInstructors & "," & Me.lst_Instructors.ItemData(varItem) & ""
Next varItem
If Len(strInstructors) = 0 Then
strInstructors = "Like '*'"
Else
strInstructors = Right(strInstructors, Len(strInstructors) - 1)
strInstructors = "IN(" & strInstructors & ")"
End If
' Build criteria string for CourseType
For Each varItem In Me.lst_Course_Type.ItemsSelected
strCourseType = strCourseType & "," & Me.lst_Course_Type.ItemData(varItem) & ""
Next varItem
If Len(strCourseType) = 0 Then
strCourseType = "Like '*'"
Else
strCourseType = Right(strCourseType, Len(strCourseType) - 1)
strCourseType = "IN(" & strCourseType & ")"
End If
' Get CourseType condition
If Me.optAndCourseType.Value = True Then
strCourseTypeCondition = " AND "
Else
strCourseTypeCondition = " OR "
End If
' Build criteria string for RoleType
For Each varItem In Me.lst_Role.ItemsSelected
strRoleType = strRoleType & "," & Me.lst_Role.ItemData(varItem) & ""
Next varItem
If Len(strRoleType) = 0 Then
strRoleType = "Like '*'"
Else
strRoleType = Right(strRoleType, Len(strRoleType) - 1)
strRoleType = "IN(" & strRoleType & ")"
End If
' Get RoleType condition
If Me.optAndRoleType.Value = True Then
strRoleTypeCondition = " AND "
Else
strRoleTypeCondition = " OR "
End If
'Build Criteria String for Course_Date
strDateRange = strSql And " Between Me.[Start_Date] AND Me.[End_Date]"
' Build SQL statement
strSql = "SELECT q_jt_MCR_Instructor_Roles.* FROM q_jt_MCR_Instructor_Roles " & _
"WHERE q_jt_MCR_Instructor_Roles.[InstructorID] " & strInstructors & _
strCourseTypeCondition & "q_jt_MCR_Instructor_Roles.[Course_TypesID] " & strCourseType & _
strRoleTypeCondition & "q_jt_MCR_Instructor_Roles.[Roles_ID] " & strRoleType & ";"
' Apply the SQL statement to the stored query
cat.ActiveConnection = CurrentProject.Connection
Set cmd = cat.Views("q_Parameter_Form").Command
cmd.CommandText = strSql
Set cat.Views("q_Parameter_Form").Command = cmd
Set cat = Nothing
' Open the Query
If Not IsNull(cboReports) And cboReports <> "" Then
DoCmd.OpenReport cboReports, acViewPreview ' use acNormal to print without preview
Else
MsgBox ("Please make a Label selection first from the dropdown list to the left.")
cboReports.SetFocus
End If
cboReports = ""
' If required the dialog can be closed at this point
' DoCmd.Close acForm, Me.Name
'Restore screen updating
cmdPreviewReports_Exit:
DoCmd.Echo True
Exit Sub
cmdPreviewReports_Err:
MsgBox "An unexpected error has occurred." _
& vbCrLf & "Error Number: " & Err.Number _
& vbCrLf & "Error Description:" & Err.Description _
, vbCritical, "Error"
Resume cmdPreviewReports_Exit
End Sub
I am also able to provide the database to look at if you wish?
Thank you for helping !!!!!!
William
It could be:
'Build Criteria String for Course_Date.
strDateRange = " And Course_Date Between #" & Format(Me![Start_Date].Value, "yyyy\/mm\/dd") & "# AND #" & Format(Me![End_Date].Value, "yyyy\/mm\/dd") & "#"
strSql = strSql & strDateRange
Please verify the below code which was build to find unmatched values between two table in MS access ( as there is run-time error 3075 in query expression Count(table1.Inv_No])'
Public Sub subCreateRowDiff()
Dim strSQL As String
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim db As DAO.Database
Dim lngCount As Long
Const TEMP_TABLE As String = "tblNoMatch"
strSQL = "SELECT table1.[Inv_No], table1.[Amt], Count(table1.Inv_No]) As Expr1 GROUP BY table1.[Inv_No], table1.[Amt];"
Set db = CurrentDb
'remove all records
db.Execute "DELETE " & TEMP_TABLE & ".* FROM " & TEMP_TABLE & ";"
'open table1
Set rs1 = db.OpenRecordset(strSQL)
strSQL = Replace(strSQL, "table1", "table2")
'open table2
Set rs2 = db.OpenRecordset(strSQL)
'check for difference
With rs1
If Not (.BOF And .EOF) Then .MoveFirst
While Not .EOF
lngCount = .Fields(2).Value 'the count field
'find matching record in table2
rs2.FindFirst "[Inv_No] = " & .Fields(0) & " AND [Amt] = " & .Fields(1).Value
If rs2.NoMatch Then
'save this record as many times (lngCount)
While lngCount <> 0
db.Execute "Insert Into " & TEMP_TABLE & "(Inv_No, Amt) " & _
"Values(" & .Fields(0).Value & ", " & .Fields(1) & ");"
lngCount = lngCount - 1
Wend
Else
' there is a match
' check the difference
If .Fields(2).Value > rs2.Fields(2).Value Then
lngCount = .Fields(2).Value - rs2.Fields(2).Value
Else
lngCount = rs2.Fields(2).Value - .Fields(2).Value
End If
While lngCount <> 0
db.Execute "Insert Into " & TEMP_TABLE & "(Inv_No, Amt) " & _
"Values(" & .Fields(0).Value & ", " & .Fields(1) & ");"
lngCount = lngCount - 1
Wend
End If
.MoveNext
Wend
End With
' now use table2 as reference
With rs2
If Not (.BOF And .EOF) Then .MoveFirst
While Not .EOF
lngCount = .Fields(2).Value 'the count field
'find matching record in table1
rs1.FindFirst "[Inv_No] = " & .Fields(0) & " AND [Amt] = " & .Fields(1).Value
If rs1.NoMatch Then
'save this record as many times (lngCount)
While lngCount <> 0
db.Execute "Insert Into " & TEMP_TABLE & "(Inv_No, Amt) " & _
"Values(" & .Fields(0).Value & ", " & .Fields(1) & ");"
lngCount = lngCount - 1
Wend
Else
' we already did this before
' so no need
End If
.MoveNext
Wend
End With
rs1.Close: Set rs1 = Nothing
rs2.Close: Set rs2 = Nothing
Set db = Nothing
End Sub
Missing a left bracket [. No brackets are needed in this SQL statement because table and field names do not have spaces.
I am having and issue using update batch. I have a loop that goes through a recordset updating values. I have a minimum of 333 things in the batch. When it gets to the 254th item it bails. is there a limit to a batch.
On Error GoTo Err_cmdProcessAll
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strTableName As String
Dim strSql As String
'
Set cn = New ADODB.Connection
cn.Open "Provider=sqloledb; " & _
"Data Source=" & "BLD-FS-SQLVS04\PRDINST4" & ";" & _
"Initial Catalog=" & "HNFS_NetProv" & ";" & _
"Integrated Security=SSPI;"
cn.CursorLocation = adUseServer
Dim strSortField As String
Dim additionalwhere As String
If cboValue = "pc3Claims" Then
strTableName = "Seq3_PendedClaims_Ranked"
strSortField = "DaysSinceReceivedClaim"
' additionalwhere = " AND (member_eligibility_ud Not Like '%Program%')
strSql = "Select * " & _
"FROM " & strTableName & _
" WHERE (Complete Is Null) And (AssignedTo Is Null)" & additionalwhere & _
" ORDER BY cast( " & strSortField & " as int )" & strSort
ElseIf cboValue = "pc3ContractAssignments" Then
strSortField = "date"
additionalwhere = ""
strSql = "Select * " & _
"FROM " & strTableName & _
" WHERE (Complete Is Null) And (AssignedTo Is Null)" & additionalwhere & _
" ORDER BY CONVERT(varchar(10), CONVERT(datetime, [" & strSortField & "], 111), 121) " & strSort
End If
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
.Source = strSql
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.CursorLocation = adUseClient
.Open
End With
'make change to above to include
Dim i As Long
Dim j As Long
Dim strAssignAssociate As String
Dim lngAllocAmt As Long
For i = 1 To ListView6.ListItems.Count
If ListView6.ListItems(i).Checked Then
strAssignAssociate = ListView6.ListItems(i).SubItems(1)
Debug.Print strAssignAssociate
lngAllocAmt = ListView6.ListItems(i).Text
For j = 1 To lngAllocAmt
Debug.Print rs.Fields("AssignedTo")
rs.Fields("AssignedTo") = strAssignAssociate
Debug.Print rs.Fields("AssignedTo")
rs.MoveNext
Next j
End If
Next i
rs.UpdateBatch
MsgBox "All Finished", vbOKOnly, "Inventory Control"
Set rs = Nothing
Set cn = Nothing
I found the problem. I am using a non-keyed file. I found that I had duplicates in the file. this has been rectified and the above code works fine.
I have a query that generates a table like this:
Row 1 - ID 1 Peter Parker Task 1 $50
Row 2 - ID 1 Peter Parker Task 2 $55
Row 3 - ID 1 Peter Parker Task 3 $60
Row 4 - ID 2 Mary Jane Task 1 $45
Row 5...
I want to be able to send one email to each person with a list of the tasks and amounts, and the total amount:
Peter Parker
Task 1 $50
Task 2 $55
Task 3 $60
Total $165
I've got a module that sends email, but it requires a single recipient per row. I'm thinking I need another loop, but I'm lost as how to do this.
Here's the code I'm using now:
Sub SendMessages(Optional AttachmentPath)
Dim MyDB As Database
Dim MyRS As Recordset
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachments
Dim TheAddress As String
Set MyDB = CurrentDb
Set MyRS = MyDB.OpenRecordset("qry_TeacherPayment - Round 2")
MyRS.MoveFirst
' Create the Outlook session.
Set objOutlook = CreateObject("Outlook.Application")
Do Until MyRS.EOF
'Set loop variables
Dim currentRecord As Integer
Dim oldRecord As Integer
Dim totalAmt As Double
currentRecord = MyRS![ID]
totalAmt = 0
If (currentRecord = MyRS![ID]) Then
' Create the e-mail message.
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
oldRecord = currentRecord
TheAddress = MyRS![WorkEmail]
With objOutlookMsg
' Add the To recipients to the e-mail message.
Set objOutlookRecip = .Recipients.Add("TheAddress")
objOutlookRecip.Type = olTo
' Set the from address.
objOutlookMsg.SentOnBehalfOfName = "email"
' Set the Subject, the Body, and the Importance of the e-mail message.
.Subject = "Subject"
objOutlookMsg.BodyFormat = olFormatHTML
body text
.HTMLBody = .HTMLBody & "</table></body></html>"
.Importance = olImportanceNormal 'Normal importance
' Resolve the name of each Recipient.
For Each objOutlookRecip In .Recipients
objOutlookRecip.Resolve
If Not objOutlookRecip.Resolve Then
objOutlookMsg.Display
End If
Next
.Send
End With
End If
MyRS.MoveNext
Loop
Set objOutlookMsg = Nothing
Set objOutlook = Nothing
DoCmd.SetWarnings True
End Sub
Here is my final code that works a treat. A huge thanks to maxhugen for putting me on the right path!!
Cheers!
Jason
Sub SendNewPaymentEmail(Optional AttachmentPath)
Dim MyDB As Database
Dim MyRS As Recordset
Dim LastTeacherID As Integer
Dim EmailBody As String
Dim TotalAmount As Double
Dim TheAddress As String
Dim TeacherFirstName As String
Dim FinalTeacherID As Integer
Set MyDB = CurrentDb
Set MyRS = MyDB.OpenRecordset("qry_TeacherPayment - Round 2")
MyRS.MoveFirst
LastTeacherID = MyRS![ID]
Do Until MyRS.EOF
If MyRS![ID] = LastTeacherID Then
TheAddress = MyRS![WorkEmail]
TeacherFirstName = MyRS![FirstName]
FinalTeacherID = MyRS![TeacherID]
EmailBody = EmailBody & "<tr><td>" & MyRS![Subject] & " Year " & MyRS![Year] & "</td><td>" & MyRS![TaskName] & "</td><td>$" & MyRS![Teacher Payment] & "</td></tr>"
TotalAmount = TotalAmount + Nz(MyRS![Teacher Payment], 0)
DoCmd.SetWarnings False
DoCmd.RunSQL "Update [tbl_Judging Standards Project round 2] SET [PaymentEmailSent] = -1 WHERE [TeacherID] = " & MyRS![ID] & " AND [TaskIDTRIM] LIKE '" & MyRS![TaskIDTRIM] & "'"
DoCmd.RunSQL "Update [tbl_Judging Standards Project round 2] SET [PaymentEmailSentDate] = Now() WHERE [TeacherID] = " & MyRS![ID] & " AND [TaskIDTRIM] LIKE '" & MyRS![TaskIDTRIM] & "'"
DoCmd.SetWarnings True
Else
Call CreateEmail(EmailBody, TotalAmount, TeacherFirstName)
DoCmd.SetWarnings False
DoCmd.RunSQL "INSERT INTO [tbl_Payments]([TeacherID],[PaymentType],[Amount],[Description],[PaymentFormSent],[PaymentFormSentDate]) VALUES(" & FinalTeacherID & ", 'Individual Payment'," & TotalAmount & ",'Judging Standards Project Phases 2 and 3 - Payment for work samples - Round 2', -1, NOW())"
DoCmd.SetWarnings True
'reset variables
EmailBody = ""
TotalAmount = 0
'start again
TheAddress = MyRS![WorkEmail]
TeacherFirstName = MyRS![FirstName]
LastTeacherID = MyRS![ID]
FinalTeacherID = MyRS![TeacherID]
EmailBody = EmailBody & "<tr><td>" & MyRS![Subject] & " Year " & MyRS![Year] & "</td><td>" & MyRS![TaskName] & "</td><td>$" & MyRS![Teacher Payment] & "</td></tr>"
TotalAmount = TotalAmount + Nz(MyRS![Teacher Payment], 0)
DoCmd.SetWarnings False
DoCmd.RunSQL "Update [tbl_Judging Standards Project round 2] SET [PaymentEmailSent] = -1 WHERE [TeacherID] = " & MyRS![ID] & " AND [TaskIDTRIM] LIKE '" & MyRS![TaskIDTRIM] & "'"
DoCmd.RunSQL "Update [tbl_Judging Standards Project round 2] SET [PaymentEmailSentDate] = Now() WHERE [TeacherID] = " & MyRS![ID] & " AND [TaskIDTRIM] LIKE '" & MyRS![TaskIDTRIM] & "'"
DoCmd.SetWarnings True
End If
MyRS.MoveNext
If (MyRS.EOF) Then
Call CreateEmail(EmailBody, TotalAmount, TeacherFirstName)
DoCmd.SetWarnings False
DoCmd.RunSQL "INSERT INTO [tbl_Payments]([TeacherID],[PaymentType],[Amount],[Description],[PaymentFormSent],[PaymentFormSentDate]) VALUES(" & FinalTeacherID & ", 'Individual Payment'," & TotalAmount & ",'Judging Standards Project Phases 2 and 3 - Payment for work samples - Round 2', -1, NOW())"
DoCmd.SetWarnings True
End If
Loop
End Sub
Assuming MyRS is returning fields something like PersonID, TaskID, TaskAmt, you need to loop through MyRS and add the Task and Amt to a string variable (eg 'strBody') UNTIL the PersonID changes - at which point you prepare and send the email using objOutlookMsg.
Set MyRS = ...
LastPersonID=MyRS!PersonID
Do Until MyRS.EOF
If MyRS!PersonID=LastPersonID Then
' concatenate to strBody
strBody = strBody & TaskID & " " & TaskAmt
' add Amt to Person's Total
decTotal = decTotal + nz(TaskAmt,0)
Else
' add the Total
strBody = strBody & "Total: " & decTotal
' send email using another function, or GoTo a named line,
' using LastPersonID and strBody
GoTo send_email
' reset the variables
strBody = ""
decTotal = 0
' concatenate to strBody
strBody = strBody & TaskID & " " & TaskAmt & "<br/>"
' add Amt to Person's Total
decTotal = decTotal + nz(TaskAmt,0)
End If
MyRS.MoveNext
Loop
Error #-2147467259
ODBC--call failed.
(Source: Microsoft JET Database Engine)
(SQL State: 3146)
(NativeError: -532940753)
No Help file available
What happened? What is the reason of this? I can make a query to a different sql server via odbc linked table(uat env), but when I go to prod server, this error come out.
I am using ms access 2000, and built a form within it, then make a query to the server when a button was pressed. The prod server get A LOT of records, while the uat server only have 3000 records, however I don't think that is a problem...
Thank to any possible help!!
This is the part of the queries:
Sub extractInboundCdr()
On Error GoTo Error_Handling
Dim conConnection As New ADODB.Connection
Dim cmdCommand As New ADODB.Command
Dim rstRecordSet As New ADODB.Recordset
Dim Err As ADODB.Error
Dim strError As String
Dim eventPlanCode As String
Dim visitedCountry As String
Dim startDateTxt As String
Dim startDate As Date
Dim endDate As Date
Dim imsi As String
Dim currentMonth As String
Dim nextMonth As String
Dim currentYear As String
Dim nextYear As String
Dim temp As Integer
Dim i As Integer
Dim j As Integer
With conConnection
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = CurrentDb.Name
.Open
End With
conConnection.CommandTimeout = 0
With cmdCommand
.ActiveConnection = conConnection
.CommandText = "SELECT * FROM Opt_In_Customer_Record;"
.CommandType = adCmdText
End With
With rstRecordSet
.CursorType = adOpenStatic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open cmdCommand
End With
If rstRecordSet.EOF = False Then
rstRecordSet.MoveFirst
Do
eventPlanCode = rstRecordSet!Event_Plan_Code
visitedCountry = rstRecordSet!Visited_Country
startDateTxt = rstRecordSet!start_date
imsi = rstRecordSet!imsi
currentMonth = Mid$(startDateTxt, 1, 3)
currentYear = Mid$(startDateTxt, 8, 4)
nextMonth = ""
If (currentMonth = "Jan") Then
currentMonth = "01"
nextMonth = "02"
ElseIf (currentMonth = "Feb") Then
currentMonth = "02"
nextMonth = "03"
ElseIf (currentMonth = "Mar") Then
currentMonth = "03"
nextMonth = "04"
ElseIf (currentMonth = "Apr") Then
currentMonth = "04"
nextMonth = "05"
ElseIf (currentMonth = "May") Then
currentMonth = "05"
nextMonth = "06"
ElseIf (currentMonth = "Jun") Then
currentMonth = "06"
nextMonth = "07"
ElseIf (currentMonth = "Jul") Then
currentMonth = "07"
nextMonth = "08"
ElseIf (currentMonth = "Aug") Then
currentMonth = "08"
nextMonth = "09"
ElseIf (currentMonth = "Sep") Then
currentMonth = "09"
nextMonth = "10"
ElseIf (currentMonth = "Oct") Then
currentMonth = "10"
nextMonth = "11"
ElseIf (currentMonth = "Nov") Then
currentMonth = "11"
nextMonth = "12"
ElseIf (currentMonth = "Dec") Then
currentMonth = "12"
nextMonth = "01"
Else
GoTo Error_Handling
End If
temp = Val(currentYear)
temp = temp + 1
nextYear = CStr(temp)
Exit Do
Loop Until rstRecordSet.EOF = True
End If
Set cmdCommand = Nothing
Set rstRecordSet = Nothing
Set connConnection = Nothing
With conConnection
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = CurrentDb.Name
.Open
End With
conConnection.CommandTimeout = 0
Dim thisMonthTable As String
Dim nextMonthTable As String
thisMonthTable = "dbo_inbound_rated_all_" & currentYear & currentMonth
If (currentMonth = "12") Then
nextMonthTable = "dbo_inbound_rated_all_" & nextYear & nextMonth
Else
nextMonthTable = "dbo_inbound_rated_all_" & currentYear & nextMonth
End If
With cmdCommand
.ActiveConnection = conConnection
.CommandText = "(SELECT A.IMSI_NUMBER, A.CALL_DATE, A.CALL_TIME, A.VOL_KBYTE, A.TOTAL_CHARGE ,datevalue(A.call_date), A.Service_Code As theDate FROM " & thisMonthTable & " AS A INNER JOIN Opt_In_Customer_Record AS B on A.imsi_number = B.imsi where A.Service_Code = 'GPRS' and Datevalue(A.call_date) >= Datevalue(B.start_date) And Datevalue(A.call_date) < (Datevalue(B.start_date) + val(LEFT(B.event_plan_code, 1))) ) " & _
"UNION " & _
"(SELECT A.IMSI_NUMBER, A.CALL_DATE, A.CALL_TIME, A.VOL_KBYTE, A.TOTAL_CHARGE ,datevalue(A.call_date), A.Service_Code As theDate FROM " & nextMonthTable & " AS A INNER JOIN Opt_In_Customer_Record AS B on A.imsi_number = B.imsi where A.Service_Code = 'GPRS' and Datevalue(A.call_date) >= Datevalue(B.start_date) And Datevalue(A.call_date) < (Datevalue(B.start_date) + val(LEFT(B.event_plan_code, 1))) ) " & _
"Order by A.IMSI_NUMBER, theDate"
.CommandType = adCmdText
End With
With rstRecordSet
.CursorType = adOpenStatic
.CursorLocation = adUseClient
.LockType = adLockReadOnly
.Open cmdCommand
End With
If rstRecordSet.EOF = False Then
rstRecordSet.MoveFirst
Do
Dim sql As String
sql = "insert into IB_CDR values ("
For j = 0 To rstRecordSet.Fields.Count - 3 '''''Last 2 fields is not inserted
If (j = 3 Or j = 4) Then '''''These fields are number
sql = sql & rstRecordSet.Fields(j) & ","
Else
sql = sql & "'" & rstRecordSet.Fields(j) & "',"
End If
Next
sql = Left(sql, Len(sql) - 1) '''''Remove the last ','
sql = sql & ");"
CurrentDb.Execute sql
rstRecordSet.MoveNext
Loop Until rstRecordSet.EOF = True
End If
conConnection.Close
Set conConnection = Nothing
Set cmdCommand = Nothing
Set rstRecordSet = Nothing
Exit Sub
Error_Handling:
For Each Err In conConnection.Errors
strError = "Error #" & Err.Number & vbCr & _
" " & Err.Description & vbCr & _
" (Source: " & Err.Source & ")" & vbCr & _
" (SQL State: " & Err.SQLState & ")" & vbCr & _
" (NativeError: " & Err.NativeError & ")" & vbCr
If Err.HelpFile = "" Then
strError = strError & " No Help file available"
Else
strError = strError & _
" (HelpFile: " & Err.HelpFile & ")" & vbCr & _
" (HelpContext: " & Err.HelpContext & ")" & _
vbCr & vbCr
End If
Debug.Print strError
Next
Resume Next
Set conConnection = Nothing
Set cmdCommand = Nothing
Set rstRecordSet = Nothing
Exit Sub
End Sub
The most common cause of this error is incorrect permissions on the folder containing the Access database. You will need to set write permissions.