In a classic asp script, I have a bunch of sql updates. If there were an sql-error, it was handled by a custom 500 error page, which logged the values of
' get the extended error information
Set ASPErr = Server.GetLastError()
strASPDesc = ASPErr.ASPDescription
strASPNumber = ASPErr.ASPCode
intASPLine = clng(ASPErr.Line)
intASPColumn = clng(ASPErr.Column)
strDesc = ASPErr.Description
strNumber = "0x" & Hex(ASPErr.Number)
strASPFile = ASPErr.File
strERRline = ASPErr.Source
and logs this in to a sql-table. So it is easy to debug in case of errors. However, this could leave the database inconsistent, if some statements were executed, and other not.
So now I have wrapped it in a sub.
on error resume next
conn.beginTrans
do_transaction
if err.number=0 then
conn.commitTrans
response.write "OK"
else
conn.rollbackTrans
Response.write "Error # " & CStr(Err.Number) & " " & Err.Description & vbCrLf
Response.write "Source: " & Err.Source & vbCrLf
end if
err.clear
on error goto 0
'here the actual transaction is done:
sub do_transaction
set rs=conn.execute("SELECT ....")
conn.execute("UPDATE ...")
conn.execute("INSERT ...")
conn.execute("DELETE ...")
end sub
This roll the entire transaction back if there is an error, however I now cannot see which statement caused the error.
The Err object does not contain line or column, and the Server.GetLastError() is not populated, except for a column 78, which does not make any sense at all.
Is there any way of getting what caused the error?
Can I get the sql-statement from the conn object?
Don't think you can retrieve the sql statement in your error handling, but you could stick it in a variable, like lastSql = "SELECT * FROM ..." and then use that variable for error handling purposes, since it would always contain your last statement.
Related
I have a text field, called DateSelector that is formatted as a Short Date, and a subform with a list of entries, one column named ControlDate contains values that are formatted as Short Date as well.
What I want:
If you change the value of DateSelector it is supposed to filter the column ControlDate to between now and the value of DateSelector, or at least be below that of DateSelector.
This is the code I have:
Private Sub DateSelector_AfterUpdate()
On Error GoTo Proc_Error
If Me.DateSelector.Value = "" Then
Me.ListView.Form.filter = ""
Me.ListView.Form.FilterOn = False
Else
MsgBox (Me.DateSelector.Value)
'This is a Check, if the Value is correct.
Me.ListView.Form.filter = "ControlDate >=" & Me.DateSelector.Value
Me.ListView.Form.FilterOn = True
End If
Proc_Exit:
Exit Sub
Proc_Error:
MsgBox "Error " & Err.Number & " when creating Filter:" & vbCrLf & Err.Description
Resume Proc_Exit
End Sub
The error thrown is 3075: Syntax Error. The MsgBox shows the correct date, where the error message shows the date missing the last digit (e.g.: 05.12.2018 --> 05.12.201) and I have absolutely no clue why.
I am thankfull for any answers, thank you for reading,
_Ninsa
You filter will end up as:
"ControlDate >= 01.12.2018"
which Access cannot read. So, apply a proper format of the string expression of the date value:
"ControlDate >= #" & Format(Me!DateSelector.Value, "yyyy\/mm\/dd") & "#"
Thanks in advance for your help.
I am not sure where the problem in my UDF but the excel restarts automatically after executing the program and also shows MsxBox twice with the reference value.
Public queryString As String
Public Function SetIt(RefCell) As String
On Error GoTo CatchBlock
MsgBox RefCell.Value
queryString = RefCell.Value
RefCell.Parent.Evaluate "SetValue(" & RefCell.Address(False, False) & ")"
GoTo Finally
CatchBlock:
MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Error in Function"
Finally:
SetIt = ""
End Function
// For now I am trying to set the cell reference value in some other cell.
Sub SetValue(RefCell As Range)
RefCell.Offset(1, 1).Value = queryString
End Sub
I am still beginner and need to accomplish another big task based on this program code execution.
Please help !!
Excel 64 bit & Office 365 is my environment
Any ideas why I am getting an "Enter Parameter Value" input box when running this code?
Private Sub cmdPrint_Click()
Dim str As String
On Error GoTo ErrHandler
If IsNull(Me.Combo_1) Then
MsgBox "Can't print an unsaved record", _
vbOKOnly, "Error"
Exit Sub
End If
str = "Combo_1 = '" & Me!Combo_1 & "'"
Debug.Print str
DoCmd.OpenReport "rptBarCodeLabels(2)", acViewPreview, , str
Exit Sub
ErrHandler:
MsgBox Err.Number & ": " _
& Err.Description, vbOKOnly, "Error"
End Sub
Edit: The button is being used to print a label of what's currently selected in Combo_1. Once the print button has been clicked, I wanted it to display the single record I chose in the label report I have it referencing. I am using Access 2003 if that means anything.
If a field name in a query contains punctuation (Combo_1), you should enclose in brackets, like so:
str = "[Combo_1] = '" & Me!Combo_1 & "'"
The Report is expecting a parameter, but not getting it because it's not being passed through in the correct manner.
I've found a solution by using some coding that was provided here: http://www.techrepublic.com/article/how-to-print-one-or-more-labels-for-a-single-access-record/
What fixed the error was most likely creating a temporary table and temporary report.
Running Access 2016
I am attempting to import data from an MS Access .mdb table from Excel. (The proprietary software my client uses only recognizes *.mdb files.) When I run this code when the table is closed, I get the error:
Run-Time Error 3061
Too few parameters - Expected 2
If I run the code when the table is open in Access, HALF the time, I get that error and half the time I get:
Run-Time error '3008'
The table 'Daily_Logs_of_Flows' is already opened exclusively by
another user, or it is already open through the user interface
and cannot be manipulated programmatically.
That seems to indicate that VBA gets past the first error sometimes.
I have checked variable names and have used both single quotations in and number signs (#) before and after monthToImport because of this post on StackOverflow. The error went from
Expected 3
to
Expected 2
Here is the code
Sub importPLCDataFromAccess(monthToImport As Date)
Dim myDbLocation As String
myDbLocation = "K:\Users\WWTP Computer\Documents\POV_Projects\PLC Interface\PLC_Data.mdb"
DIM mySQLCall as String
Set myWorkbook = ActiveWorkbook
Set myDataSheet = myWorkbook.Worksheets("Page 1")
Set myEngine = New DAO.DBEngine
'Set myWorkspace = myEngine.Workspaces(0)
Set myDB = myEngine.OpenDatabase(myDbLocation)
' I deleted the workspace
' Set myDB = myWorkspace.OpenDatabase(myDbLocation)
mySQLCall = "SELECT Time_Stamp, GolfVolume, CreekVolume, InfluentVolume FROM Daily_Logs_of_Flows "
' Limit records to month requested...
mySQLCall = mySQLCall & "WHERE (DATEPART(m,Time_Stamp) = DATEPART(m,#" & monthToImport & "#)) "
' ... during the year requested
mySQLCall = mySQLCall & "AND (DATEPART(yyyy,Time_Stamp) = DATEPART(yyyy,#" & monthToImport & "#)) "
mySQLCall = mySQLCall & "ORDER BY Time_Stamp"
Debug.Print "mySQLCall = " & mySQLCall
Debug.Print "monthToImport: " & monthToImport
'Error occurs on next line where execute query & populate the recordset
Set myRecordSet = myDB.OpenRecordset(mySQLCall, dbOpenSnapshot)
'Copy recordset to spreadsheet
Application.StatusBar = "Writing to spreadsheet..."
Debug.Print "RecordSet Count = " & myRecordSet.recordCount
If myRecordSet.recordCount = 0 Then
MsgBox "No data retrieved from database", vbInformation + vbOKOnly, "No Data"
GoTo SubExit
End If
'....
End Sub
Here is the Debug.Print of SQL statement as currently reads:
mySQLCall = SELECT Time_Stamp, GolfVolume, CreekVolume, InfluentVolume FROM Daily_Logs_of_Flows WHERE (DATEPART(m,Time_Stamp) = DATEPART(m,#6/1/2016#)) AND (DATEPART(yyyy,Time_Stamp) = DATEPART(yyyy,#6/1/2016#)) ORDER BY Time_Stamp
Any thoughts on what I am missing here? Thanks in advance for your help.
The problem is that the DATEPART function needs the first parameter in quotes, otherwise it looks for the field yyyy or m.
For example:
DATEPART("yyyy", #6/1/2016#)
or
DATEPART("m", #6/1/2016#)
In total:
SELECT Time_Stamp, GolfVolume, CreekVolume, InfluentVolume _
FROM Daily_Logs_of_Flows
WHERE (DATEPART("m",Time_Stamp) = DATEPART("m",#6/1/2016#))
AND (DATEPART("yyyy",Time_Stamp) = DATEPART("yyyy",#6/1/2016#))
ORDER BY Time_Stamp
To do this in VBA (in case you don't know, but I'm guessing you do), just double up the quotation marks each time you call the DATEPART function...
For example:
mySQLCall = mySQLCall & "AND (DATEPART(""yyyy"",Time_Stamp)...."
Just to be complete, Run-Time error '3008' is actually the first error....Access won't attempt to run any SQL until it can determine that it has the proper permissions.
I am getting a type mismatch with the following syntax in my Access VBA. I am trying to update my table named "Billing" by seeing if any records have a date that looks at a string value in my "Certs" table like "2012-07-01" corresponding to my form's billYear textbox e.g. 2012 and my billMonth textbox e.g. 07. Is there a better way to write the VBA or see an error - many thanks:
Dim sRecert As String
Dim byear As Integer
Dim bmonth As Integer
byear = Me.billYear
bmonth = Me.billMonth
sRecert = "Update Billing set recertifying = -1 where (select certificationExpireDate from certs where Left((certificationExpireDate),4) = " & byear
& " and Mid((certificationExpireDate),6,2) = " & bmonth & ")"
DoCmd.RunSQL sRecert
I may not have explained it well. I created a real Query called from my form:
DoCmd.OpenQuery "updateRecert"
I set up my SQL below as a test on a real date I’m working with. It is in SQL Server (ODBC linked)
My dbo_certs table and my dbo_billing table share only one joinable field peopleID:
UPDATE dbo_Billing AS a INNER JOIN dbo_certs AS b ON a.peopleid = b.peopleid
SET a.recertifying = -1
WHERE b.certificationExpireDate = '2015-08-31 00:00:00.000';
The above gave a data mismatch error.
My bottom line is I have two text boxes on my form to pass in data preferably into my VBA code:
billMonth which in this case is 8 because it is an integer so that is
a problem
billYear is 2015
so I need to update my dbo_billing table’s ‘recertifying’ field with -1 if the dbo_cert’s field ‘certificationExpireDate’ is '2015-08-31 00:00:00.000' but only if that can be gotten from the form.
Is there a better way to write the VBA or see an Error?
Yes. You need Error Handling
I don't think the issue is in the code, I think it's in the SQL.
To troubleshoot your code, wrap it in an good error handler.
Public Sub MyRoutine()
On Error GoTo EH
'put your code here
GoTo FINISH
EH:
With Err
MsgBox "Error" & vbTab & .Number & vbCrLf _
& "Source" & vbTab & .Source & vbCrLf & vbCrLf _
& .Description
End With
'for use during debugging
Debug.Assert 0
GoTo FINISH
Resume
FINISH:
'any cleanup code here
End Sub
When the msgbox shows the error, make note of the Source. This should help you determine where the error comes from.
The lines following 'for use during debugging are helpful. Here's how to use them:
execution will stop on the Debug.Assert 0 line
drag the yellow arrow (which determines which line to run next) to the Resume line
hit {F8} on the keyboard (or use the menu Debug > Step Into)
This will go to the line where the error occurred. In your case, it will probably be the last line of your code.
Error in SQL... but!! Are you sure that certificationExpireDate is string and all the time equal to yyyy-mm-dd pattern?? It's dangerouse to have relation with "not certain" key like you have. I think this is not a good db design.
But, after all, for your case:
VBA:
sRecert = "UPDATE Billing a inner join certs b " & _
"on format(a.imaginary_date_field, """yyyy-mm-dd""") = b.certificationExpireDate " & _
"set a.recertifying = -1 " & _
"where CInt(Left((b.certificationExpireDate),4)) = " & byear & " and CInt(Mid((b.certificationExpireDate),6,2)) = " & bmonth
QueryDef:
PARAMETERS Forms!your_form!byear Short, Forms!your_form!bmonth Short;
UPDATE Billing a inner join certs b
on format(a.imaginary_date_field, "yyyy-mm-dd") = b.certificationExpireDate
set a.recertifying = -1
where CInt(Left((b.certificationExpireDate),4)) = Forms!your_form!byear and CInt(Mid((b.certificationExpireDate),6,2)) = Forms!your_form!bmonth
UPDATED
mismatch error
You get error probable because you have date/time field, not a string. Date in MS Access queries write with # symbol. WHERE b.certificationExpireDate = #2015-08-31 00:00:00.000#;
In your case:
PARAMETERS Forms!your_form!byear Short, Forms!your_form!bmonth Short;
UPDATE dbo_Billing AS a INNER JOIN dbo_certs AS b ON a.peopleid = b.peopleid
SET a.recertifying = -1
WHERE year(b.certificationExpireDate) = Forms!your_form!byear and Month(b.certificationExpireDate) = Forms!your_form!bmonth;
For more info follow this link