INSERT INTO - errors, but allows input into table - vba

For reasons I cannot see I get the following error message:
Compile error: Method or data member not found
when I use the following:
Private Sub cmd_Add_Click()
Dim strSQL As String
strSQL = " INSERT INTO BERTHAGE " _
& "(BOAT, LOCATION, BERTH_WEEK, BERTH_YEAR, BERTHED) VALUES " _
& Me.Add_Boat & "','" _
& Me.LOCATION & "','" _
& Me.txt_week & "','" _
& Me.txt_year & "','" _
& Me.In_Port & "');"
cmd_Clear_Click
End Sub
Once I click OK and use the refresh button the entry is put into the database, but each time I do an entry I have to go to the same process.
I would like to figure out what method or data is missing?
I should add that there is an outnumber primary key field on this table (Berth_ID), and each time I use the cmd_Add button a new ID number is created for the new record. This includes creating a new ID number for the new record that triggers the error.
Here is all the VBA associated with this form
Private Sub Form_Load()
DoCmd.RunCommand acCmdRecordsGoToLast
End Sub
Private Sub LOCATION_Change()
Me.txt_Cur_Flo = Me.LOCATION.Column(1)
Me.txt_Cur_Doc = Me.LOCATION.Column(2)
Me.txt_Cur_Ori = Me.LOCATION.Column(3)
End Sub
Private Sub cmd_Add_Click()
Dim strSQL As String
strSQL = " INSERT INTO BERTHAGE " _
& "(BOAT, LOCATION, BERTH_WEEK, BERTH_YEAR, BERTHED) VALUES " _
& Me.Add_Boat & "','" _
& Me.LOCATION & "','" _
& Me.txt_week & "','" _
& Me.txt_year & "','" _
& Me.In_Port & "');"
cmd_Clear_Click
End Sub
Private Sub cmd_Clear_Click()
Me.Add_Boat = ""
Me.LOCATION = ""
Me.txt_Cur_Flo = ""
Me.txt_Cur_Doc = ""
Me.txt_Cur_Ori = ""
Me.Add_Boat.SetFocus
End Sub
Private Sub cmd_Close_Click()
DoCmd.Close
End Sub

Consider the best practice of parameterization and not string concatenation of SQL mixed with VBA variables. Due to missing quotes, the compiler attempts to reference a column name and not its literal value. Instead, consider parameterization with defined types which is supported with Access SQL using QueryDefs. Notice below, SQL and VBA are complete separate.
SQL (save as stored query)
PARAMETERS prmBoat TEXT, prmLoc INT, prmBerthed INT;
INSERT INTO BERTHAGE (BOAT, LOCATION, BERTHED)
VALUES(prmBoat, prmLoc, prmBerthed)
VBA
Dim db As Database
Dim qdef As QueryDef
Dim strSQL As String
Set db = CurrentDb
Set qdef = db.QueryDefs("mySavedParamQuery")
' BIND PARAM VALUES
qdef!prmBoat = Me.Add_Boat
qdef!prmLoc = Me.LOCATION
qdef!prmBerthed = Me.In_Port
' EXECUTE ACTION QUERY
qdef.Execute
Set qdef = Nothing
Set db = Nothing
Even better, save your query with form controls intact and simply call OpenQuery:
SQL (save as stored query)
INSERT INTO BERTHAGE(BOAT, LOCATION, BERTHED)
VALUES(Forms!myForm!Add_Boat, Forms!myForm!LOCATION, Forms!myForm!In_Port)
VBA
Private Sub cmd_Add_Click()
Dim strSQL As String
DoCmd.SetWarnings False ' TURN OFF APPEND PROMPTS
DoCmd.OpenQuery "mySavedActionQuery"
DoCmd.SetWarnings True ' RESET WARNINGS
Call cmd_Clear_Click
End Sub

Missing opening parenthesis after VALUES. Also missing apostrophe in front of Me.Add_Boat. These special characters must always be in pairs, an even number by counting.
If Berth_Week and Berth_Year are number fields (and should be), don't use apostrophe delimiters.
If In_Port is a Yes/No field, don't use apostrophe delimiters.

The issue appears to be that I was doubling up the inputs into the 'week' and 'year' field. this was happening (I believe) because those text box fields were already accessing the week and year information directly from the default value on the BERTHAGE table. Essentially I went through each input and would run it individually waiting for the error to occur. Once it occurred I took it out of the INSERT INFO statement. With the removal of week and year, everything is working. That was a painful exercise, and still not complete, but I am back to a function form/DB so I'll take the small victories when they occur.
Private Sub cmd_Add_Click()
Dim strSQL As String
CurrentDb.Execute " INSERT INTO BERTHAGE " & "(BOAT, LOCATION, BERTHED) VALUES ('" & Me.Add_Boat & "'," _
& Me.New_Loc & "," _
& Me.In_Port & ");"
cmd_Clear_Click
DoCmd.Requery
End Sub`

Related

Looping through table to find value from a textbox

I'm trying to loop through a column inside a table from a form in Access to find out whether a "Case Name" already exists or not, and if it does not, then add the new record to the table. I want the criteria to be based on the input value of a text box. The good news is I have figured out how to add a new record to the table with the code below. I'm just stuck on how to loop through a table to find out if a record already exists. Thanks in advance!
Private Sub SaveNewCase_Click()
If Me.txtNewCaseName.Value <> "Null" And Me.txtCaseDepth.Value <> "Null" And Me.txtCaseHeight2.Value <> "Null" And Me.txtCaseWeight.Value <> "Null" And Me.txtCaseWidth <> "Null" And Me.cboCaseCategory.Value <> "Null" Then
'I think the loop should go here, but not sure'
CurrentDb.Execute "INSERT INTO tblCases(CaseName, CaseWidth, CaseHeight, CaseCasters, CaseWeight, CaseDepth, CaseCategory) " & _
" VALUES ('" & Me.txtNewCaseName & "'," & Me.txtCaseWidth & "," & Me.txtCaseHeight2 & ",'" & Me.chkboxCasters & "'," & Me.txtCaseWeight & "," & Me.txtCaseDepth & ",'" & Me.cboCaseCategory & "')"
Else
MsgBox "Please enter all new case criteria."
End If
End Sub
Firstly, use parameters!
Concatenating values supplied by a user directly into your SQL statement exposes your to SQL injection, either intentional (i.e. users entering their own SQL statements to sabotage your database) or unintentional (e.g. users entering values containing apostrophes or other SQL delimiters).
Instead, represent each of the field values with a parameter, for example:
With CurrentDb.CreateQueryDef _
( _
"", _
"insert into " & _
"tblcases (casename, casewidth, caseheight, casecasters, caseweight, casedepth, casecategory) " & _
"values (#casename, #casewidth, #caseheight, #casecasters, #caseweight, #casedepth, #casecategory) " _
)
.Parameters("#casename") = txtNewCaseName
.Parameters("#casewidth") = txtCaseWidth
.Parameters("#caseheight") = txtCaseHeight2
.Parameters("#casecasters") = chkboxCasters
.Parameters("#caseweight") = txtCaseWeight
.Parameters("#casedepth") = txtCaseDepth
.Parameters("#casecategory") = cboCaseCategory
.Execute
End With
Since the value of each form control is fed directly to the parameter within the SQL statement, the value will always be interpreted as a literal and cannot form part of the SQL statement itself.
Furthermore, you don't have to worry about surrounding your string values with single or double quotes, and you don't have to worry about formatting date values - the data is used in its native form.
Where testing for an existing value is concerned, you can either use a domain aggregate function, such as DLookup, or you could use a SQL select statement and test that no records are returned, e.g.:
Dim flg As Boolean
With CurrentDb.CreateQueryDef _
( _
"", _
"select * from tblcases where " & _
"casename = #casename and " & _
"casewidth = #casewidth and " & _
"caseheight = #caseheight and " & _
"casecasters = #casecasters and " & _
"caseweight = #caseweight and " & _
"casedepth = #casedepth and " & _
"casecategory = #casecategory " _
)
.Parameters("#casename") = txtNewCaseName
.Parameters("#casewidth") = txtCaseWidth
.Parameters("#caseheight") = txtCaseHeight2
.Parameters("#casecasters") = chkboxCasters
.Parameters("#caseweight") = txtCaseWeight
.Parameters("#casedepth") = txtCaseDepth
.Parameters("#casecategory") = cboCaseCategory
With .OpenRecordset
flg = .EOF
.Close
End With
End With
If flg Then
' Add new record
Else
' Record already exists
End If
Finally, you're currently testing the values of your form controls against the literal string "Null", which will only be validated if the user has entered the value Null into the control, not if the control is blank.
Instead, you should use the VBA IsNull function to check whether a variable holds a Null value.

MS Access. VBA. How to create a temporary table with 1 record only if it not exist

I am looking for a way to Create a table when Form is opening.
Table should be created just once. So if it exists new one should not be created.
In the same form I would like to save some data from combo boxes in created table.
To do that I tried to use a code:
Sub ViaVBA()
Const strSQLCreateFoo_c As String = _
"CREATE TABLE Foo" & _
"(" & _
"MyField1 INTEGER," & _
"MyField2 Text(10)" & _
");"
Const strSQLAppendBs_c As String = _
"INSERT INTO Foo (MyField1, MyField2) " & _
"SELECT Bar.MyField1, Bar.MyField2 " & _
"FROM Bar " & _
"WHERE Bar.MyField2 Like 'B*';"
If Not TableExists("foo") Then
CurrentDb.Execute strSQLCreateFoo_c
End If
CurrentDb.Execute strSQLAppendBs_c
End Sub
Private Function TableExists(ByVal name As String) As Boolean
On Error Resume Next
TableExists = LenB(CurrentDb.TableDefs(name).name)
End Function
Unfortunately it is not saving selected values from combo boxes.
It seems that the table has no records and it doesn't want to save the values.
When I add at least one record that combo boxes are storing correct values.
How to create a table with one record with some dummy info using the code posted above?
Concatenate variable input. Delimit parameters for text field with apostrophes. Use VALUES clause instead of SELECT. Use If Then instead of WHERE clause to test value of form control. Don't use reserved word Name as variable.
Consider:
Sub ViaVBA()
If Not TableExists("foo") Then
CurrentDb.Execute "CREATE TABLE Foo(MyField1 INTEGER, MyField2 Text(10));"
End If
If Forms!Bar.MyField2 LIKE "B*" Then
CurrentDb.Execute "INSERT INTO Foo (MyField1, MyField2) " & _
"VALUES(" & Forms!Bar.MyField1 & ", '" & Forms!Bar.MyField2 & "')"
End If
End Sub
Private Function TableExists(ByVal strName As String) As Boolean
On Error Resume Next
TableExists = LenB(CurrentDb.TableDefs(strName).Name)
End Function

syntax error in insert into statement on access and vb.net [duplicate]

This question already has answers here:
vb.net escape reserved keywords in sql statement
(2 answers)
Closed 5 years ago.
Im having a error but i dont know what part but i check my tables but it is the exact column im using ms access2010 as database and every time i add a new record theres a msgbox that show (syntax error in insert into statement) heres my code:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
Private Sub GroupBox1_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GroupBox1.Enter
End Sub
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim add As String = "insert into setplan(ma,planqty,side,start,end,total,remarks) values ('" & cmbshift.SelectedItem & "','" & txtplqty.Value & "','" & cmbside.SelectedItem & "','" & timestart.Text & "','" & timeend.Text & "','" & txttotal.Text & "','" & txtrem.Text & "')"
Dim connection As String = "Provider=Microsoft.Ace.Oledb.12.0; Data Source=C:\Users\Administrator\Documents\plan.mdb; Persist Security Info=False;"
Using conn As New OleDb.OleDbConnection(connection)
Try
conn.Open()
If cmbshift.SelectedItem = "" Then
MsgBox("Please Select Shift Schedule")
ElseIf txtplqty.Value = 0 Then
MsgBox("Please Input Plan Quantity")
ElseIf cmbside.SelectedItem = "" Then
MsgBox("Please select Side")
ElseIf timestart.Text = "" Then
MsgBox("Please Select A Start Time")
ElseIf timeend.Text = "" Then
MsgBox("Please Select A Start Time")
ElseIf timeend.Text = timestart.Text Then
MsgBox("Time end must not be equal to Time Start")
Else
MsgBox(add)
Dim cmd As New OleDb.OleDbCommand(add, conn)
cmd.ExecuteNonQuery()
MsgBox("New Schedule Added")
End If
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Sub
Private Sub timestart_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timestart.ValueChanged
End Sub
End Class
start and end words are unique for sql so those keywords might cause the problem. Try to switch those column names into something like startTime and endTime and check if that works.
As has been addressed in the comments, it would be much better if you were to make this a parameterized query instead of concatenating the strings into an explicit SQL command. That being said, however, using your example, there are a couple of things that could be causing the error you describe, some of which have been mentioned in the comments (and the answer from Atilla).
Start and End are reserved keywords in SQL. Using them as column names can cause unexpected behavior when executing a query against those columns from a .NET application through OleDb. There are basically two ways to get around this:
Rename these columns in the database - Atilla suggested StartTime and EndTime, which would probably work nicely.
If renaming the columns is not an option (these columns are used by some other system/process you have in place), your best bet is to modify the query. Since it appears that you're working with an Access database (.mdb) file, you can enclose the column names in your query in square brackets (e.g., [Start] and [End]).
I've actually taken to enclosing all of my table and column names this way when working with Access databases because we have some databases with column names that include spaces and such, so this helps tremendously.
You also need to take into account the actual data types of the columns into which you're attempting to INSERT the data. Again, since it seems that you're using an Access database file, there are a couple of syntactical things to look at.
Values being inserted into a Date/Time field should be wrapped with the # character instead of the ' character.
Numeric field types (e.g., Number or Currency) should not be wrapped with the ' character (or any other characters, for that matter).
If the string values you intend to insert into text fields (e.g., Short Text or Long Text) contain any of a number of "special/invalid characters" including single and/or double quotation marks, these need to be "cleaned up" before executing the query. If this is the case (or potentially could be the case), you could create a method to clean up the string value prior to use in your SQL command. See an example at the bottom of this post in which most, if not all of the potentially invalid characters are simply stripped from the string value.
Please note that, for the purposes of this answer, I've used the data type names from the MS Access UI rather than the actual OleDb/Odbc data types to try to simplify things.
Without knowing the actual data types used in your database table or the values that are coming from the form controls, I can only make assumptions, but, if I absolutely had to use this type of query building (meaning, it's not possible to make it parameterized for some reason), I would probably create the query to looks something more like this:
Dim add As String = "INSERT INTO setplan " & _
"([ma], [planqty], [side], [start], [end], [total], [remarks]) " & _
"VALUES ('" & cmbshift.SelectedItem & "', " & _
txtplqty.Value & ", " & _
"'" & cmbside.SelectedItem & "', " & _
"#" & timestart.Text & "#, " & _
"#" & timeend.Text & "#, " & _
txttotal.Text & ", " & _
"'" & txtrem.Text & "')"
This assumes that the [start] and [end] columns are Date/Time columns, and the [planqty] and [total] columns are some type of Number columns (Integer, Single, etc.).
HOWEVER: as mentioned above, it would be much preferred to make this a parameterized query. Check out the accepted answer to this SO question for more information on how to do this: VB.Net - Inserting data to Access Database using OleDb
Example of cleanup function for String values when concatenating SQL command:
Friend Function CleanStringForSQL(ByVal DirtyString As String) As String
Dim CleanString As String = DirtyString.Replace("'", "")
CleanString = CleanString.Replace("""", "")
CleanString = CleanString.Replace("*", "")
CleanString = CleanString.Replace("\", "")
CleanString = CleanString.Replace("/", "")
CleanString = CleanString.Replace(";", "")
CleanString = CleanString.Replace("%", "")
CleanString = CleanString.Replace("#", "")
CleanString = CleanString.Replace("(", "")
CleanString = CleanString.Replace(")", "")
CleanString = CleanString.Replace("[", "")
CleanString = CleanString.Replace("]", "")
Return CleanString
End Function
Which could then be used in your declaration statement for the SQL command string like:
...
"VALUES ('" & CleanStringForSQL(cmbshift.SelectedItem) & "', " & _
...

SQL Program UPDATE Record Error

I'm working in a small SQL Database program. The programs just there to view, edit and update the database records. Everything is working remarkably well considering I've never tried something like this before. I've managed to get the Add Records, Refresh Records and Delete Records functions working flawlessly. However, I've hit a little bump when trying to UPDATE a selected record.
To clarify, the SQL Table is displayed in a list view, from this list view the end-user can select a particular-record and either edit or delete it.
The edit button opens a new form window with text fields which are automatically filled with the current information of that record.
The code for the edit record form is:
Private Sub frmEdit_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
intDB_ID_Selected = CInt(frmMain.lvRec.SelectedItems(0).Text)
Call dispCaption()
Call dispInfo() 'Display the info of the selected ID
End Sub
Private Sub dispInfo()
SQL = "Select * from PersonsA " & _
"where Members_ID=" & intDB_ID_Selected & ""
With comDB
.CommandText = SQL
rdDB = .ExecuteReader
End With
If rdDB.HasRows = True Then
rdDB.Read()
Me.midtxt.Text = rdDB!Members_ID.ToString.Trim
Me.gttxt.Text = rdDB!Gamer_Tag.ToString.Trim
Me.sntxt.Text = rdDB!Screenname.ToString.Trim
Me.fntxt.Text = rdDB!First_Name.ToString.Trim
Me.lntxt.Text = rdDB!Last_Name.ToString.Trim
Me.dobtxt.Text = rdDB!DoB.ToString.Trim
Me.dobtxt.Text = rdDB!DoB.ToString.Trim
Me.emailtxt.Text = rdDB!E_Mail_Address.ToString.Trim
Me.teamptxt.Text = rdDB!Position.ToString.Trim
Me.ugctxt.Text = rdDB!Cautions.ToString.Trim
Me.recordtxt.Text = rdDB!Record.ToString.Trim
Me.eventatxt.Text = rdDB!Event_Attendance.ToString.Trim
Me.Mstattxt.Text = rdDB!Member_Status.ToString.Trim
End If
rdDB.Close()
End Sub
Private Sub dispCaption()
End Sub
Private Sub cmdUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdUpdate.Click
Call disControl()
'Validation
If invalidUpdateEntry() = True Then
Call enaControl()
Exit Sub
End If
'Prompt the user if the record will be updated
If MsgBox("Are you sure you want to update the selected record?", CType(MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2 + MsgBoxStyle.Question, MsgBoxStyle), "Update") = MsgBoxResult.Yes Then
'Update query
SQL = "Update PersonsA" & _
"SET Members_ID='" & Me.midtxt.Text.Trim & "'," & _
"Gamer_Tag='" & Me.gttxt.Text.Trim & "'," & _
"Screenname='" & Me.sntxt.Text.Trim & "'," & _
"First_Name='" & Me.fntxt.Text.Trim & "'," & _
"Last_Name='" & Me.lntxt.Text.Trim & "'," & _
"DoB='" & Me.dobtxt.Text.Trim & "'," & _
"E_Mail_Address='" & Me.emailtxt.Text.Trim & "'," & _
"Position='" & Me.teamptxt.Text.Trim & "'," & _
"U_G_Studio='" & Me.ugptxt.Text.Trim & "'," & _
"Cautions='" & Me.ugctxt.Text.Trim & "'," & _
"Record='" & Me.recordtxt.Text.Trim & "'," & _
"Event_Attendance='" & Me.eventatxt.Text.Trim & "'," & _
"Member_Status='" & Me.Mstattxt.Text.Trim & "'" & _
"WHERE Members_ID='" & intDB_ID_Selected & "'"
Call execComDB(SQL) 'Execute the query
Me.Close()
'*** Refresh the list
SQL = "Select * from PersonsA "
Call frmMain.dispRec(SQL)
'--- End of refreshing the list
Exit Sub
Else
Call enaControl()
End If
End Sub
As I've said, I've been able to do everything else using an extremely similar method, but when I try to UPDATE the record I get an error saying
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near 'Members_ID'.
I know it's this line that's the problem
"WHERE Members_ID='" & intDB_ID_Selected & "'"
Call execComDB(SQL) 'Execute the query
But referencing 'intDB_ID_Selected' has always worked before, and it's been set-up on the update form records load as intDB_ID_Selected = CInt(frmMain.lvRec.SelectedItems(0).Text)
I know this is a huge thread but if anyone could steer me in the right direction WITHOUT telling me to re-write the entire statement I'd be forever grateful.
EDIT1: I fixed the comma before the WHERE clause, but I'm still getting the same error.
Missing a space between
"Update PersonsA " & _
"SET Members_ID= ....
and (as already pointed out) a comma not needed before the WHERE
Said that, do a favor to yourself and to your users. Do not use string concatenation to build a sql command. Use always a parameterized query.
Just as an example
SQL = "Update PersonsA SET Members_ID=#id, Gamer_Tag=#tag, Screenname=#screen," & _
"First_Name=#fname,Last_Name=#lname,DoB=#dob,E_Mail_Address=#email," & _
"Position=#pos,U_G_Studio=#studio,Cautions=#caution,Record=#rec," & _
"Event_Attendance=#event, Member_Status=#stat " & _
"WHERE Members_ID=#id"
SqlCommand cmd = new SqlCommand(SQL, connection)
cmd.Parameters.AddWithValue("#id", Me.midtxt.Text.Trim)
..... so on for the other parameters defined above ....
cmd.ExecuteNonQuery();
Change "Member_Status='" & Me.Mstattxt.Text.Trim & "'," & _
to "Member_Status='" & Me.Mstattxt.Text.Trim & "'" & _
Looks like it was just an extra rogue comma!
On any error like this, use debugging provided with Visual Studio. Inspect the value of SQL, paste into MS SQL Management Studio - it has syntax highlight, and you should be able to spot the error easily.
To prevent further issues (including SQL injection vulnerability), separate this query into an embedded resource, and use parameters. Then it's easy to view, maintain (you can copy/paste between SQL Mgmt Studio and VS), and ultimately use it in code.
A side note, you don't need to use Call in VB.NET, just put a method name with parenthesis.

Inserting into a different table from a form

I am trying to make an event when iputing data in a form on access, after the text box looses focus, if the box is not null I want the ID and the value to get stored into another table. After trying with the code below I get "Runtime error 3061 Too few parameters Expected 1". I have checked in debug mode and the values are getting carried over and brought to the string.
Private Sub Consolidate_LostFocus()
Dim queryString As String
queryString = "INSERT INTO [ReportMasterTable]([#], [Notes]) VALUES(" & [#].Value & ", " & [Consolidate].Value & ")"
If Consolidate.Text <> vbNullString Then
CurrentDb.Execute (queryString)
End If
End Sub
If either the # or the Notes fields in ReportMasterTable is text data type, you must add quotes around the values you attempt to INSERT.
For example, if both fields are text type:
queryString = "INSERT INTO [ReportMasterTable]([#], [Notes])" & vbCrLf & _
"VALUES ('" & [#].Value & "', '" & [Consolidate].Value & "')"
The situation will be more complicated if either [#].Value or [Consolidate].Value contains a single quote. You could double up the single quotes within the inserted values. However it might be easier to just switch to a parameterized query ... the quoting problem would go away.
Dim db As DAO.database
Dim qdf As DAO.QueryDef
Dim strInsert As String
strInsert = "PARAMETERS hash_sign Text (255), note_value Text (255);" & vbCrLf & _
"INSERT INTO [ReportMasterTable]([#], [Notes])" & vbCrLf & _
"VALUES (hash_sign, note_value)"
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strInsert)
qdf.Parameters("hash_sign").value = Me.[#]
qdf.Parameters("note_value").value = Me.[consolidate]
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
You could also save the SQL statement as a named query and open and execute that instead of rebuilding the statement every time your procedure runs.
Is there any reason why you do not wish ti bind the form to the ReportMasterTable?
If you really have a control and field called #, you are facing a world of trouble.
If you have bound the form to ReportMasterTable and are also updating in a query, you are going to run into problems.
The lost focus event is a very bad event to choose, any time anyone tabs through the form, the code will run. After update would be better.
You are updating a text data type, but you have not used quotes.
"INSERT INTO [ReportMasterTable]([#], [Notes]) VALUES(" & [#].Value _
& ", '" & [Consolidate].Value & "')"