MYSQL-Access-Macro Error Unknown column in field list - mysql

I am trying to run an Excel macro that imports data from a csv file into an Access database, MySQL front end. The macro code is not new-we've been using this for a couple of years, the table in the Access DB is not new, and the csv files with which the data is used to be brought into the Access table is also unchanged (meaning same rows, same data types).
I am stumped as the error appears to be something of an anomaly and I have tried several fixes to correct the error. I have attached a copy of the error as well as the code below. The issue with the column referenced below as well error message attached, "itemcode", this column is in the database.
Clearly, there is something that I am missing. Any insights are greatly appreciated. Thank you.
'Read in Current .csv file
'Data Services
NumRows = Application.CountA(Range("A:A"))
For iCount = 1 To NumRows
Dim InstData(11)
InstData(1) = Range("A" & iCount) 'Date
invoiceDate = Format(InstData(1), "yyyy/mm/dd")
InstData(2) = Range("B" & iCount) 'Invoice Number
InstData(3) = Range("C" & iCount) 'names
flname() = Split(InstData(3), ",")
lname = flname(0)
fname = flname(1)
InstData(4) = Range("D" & iCount) 'Address1
InstData(5) = Range("E" & iCount) 'Address2
InstData(6) = Range("F" & iCount) 'City
InstData(7) = Range("G" & iCount) 'State
InstData(8) = Format(Range("H" & iCount), "00000") 'postal code
InstData(9) = Range("I" & iCount) 'phone
InstData(10) = Range("J" & iCount) 'email
InstData(11) = Range("K" & iCount) 'amount
Set conn = New ADODB.Connection
Set rec = New ADODB.Recordset
conn.Open "Dsn=HERIpub"
rec.Open ("Insert into tbl_Invoice (invoiceNumber,invoiceDate,invoiceAmount,invoiceDescription,invoiceFAU,invoiceCostCenter,invoiceProject,itemcode,invoicecFName,invoicecLName, invoicecAddr1, invoicecAddr2, invoicecCity, invoicecState, invoicecZIP, invoicecEmail, invoicecPhone) Values ('" & InstData(2) & "','" & invoiceDate & "','" & InstData(11) & "','Data Services','T6','T6','DATASL','40070DATASL','" & fname & "'" & ",'" & lname & "','" & InstData(4) & "', '" & InstData(5) & "', '" & InstData(6) & "', '" & InstData(7) & "', '" & InstData(8) & "', '" & InstData(10) & "', '" & InstData(9) & "')"), conn
macro error

Look at the variable fname , there you have redundant " & " . I think it should be:
rec.Open ("Insert into tbl_Invoice (invoiceNumber,invoiceDate,invoiceAmount,invoiceDescription,invoiceFAU,invoiceCostCenter,invoiceProject,itemcode,invoicecFName,invoicecLName, invoicecAddr1, invoicecAddr2, invoicecCity, invoicecState, invoicecZIP, invoicecEmail, invoicecPhone) Values ('" & InstData(2) & "','" & invoiceDate & "','" & InstData(11) & "','Data Services','T6','T6','DATASL','40070DATASL','" & fname & "','" & lname & "','" & InstData(4) & "', '" & InstData(5) & "', '" & InstData(6) & "', '" & InstData(7) & "', '" & InstData(8) & "', '" & InstData(10) & "', '" & InstData(9) & "')"), conn
Tell me if I'm right, or mark a vote up!

Related

Open Report Use Three Combobox Filter

I have 3 combobox to filter data, then i want to open in command button to print preview..
Problems I have if i used 2 combobox it works but when i used three combobox the report is blank...there's any problems with the code?? here's the code i used :
Dim strWhereCondition As String
strWhereCondition = "[month] = '" & Me.cbmonth.Value _
& "' and [Works] = '" & Me.cbwork.Value _
& "' and [Works] = '" & Me.cbwork2.Value & "'"
Debug.Print strWhereCondition
DoCmd.OpenReport "Month List", View:=acViewPreview, _
WhereCondition:=strWhereCondition
and the requery for my form
SELECT *
FROM MyTable
WHERE (month = Forms!nameForm!cbmonth
OR Forms!MeForm!cbwork IS NULL)
And (works = Forms!nameForm!cbwork
OR Forms!nameForm!cbwork IS NULL)
AND (works = Forms!nameForm!cbwork2
OR Forms!nameForm!cbwork2 IS NULL);
can anyone help?
Month is a number, so try:
strWhereCondition = "[month] = " & Me.cbmonth.Value _
& " and [Works] = '" & Me.cbwork.Value _
& "' and [Works] = '" & Me.cbwork2.Value & "'"
Edit: Month is text.
However, [Work] is supposed to match two potentially different values:
& "' and [Works] = '" & Me.cbwork.Value _
& "' and [Works] = '" & Me.cbwork2.Value & "'"
Should most likely be:
& "' and [Works] = '" & Me.cbwork.Value _
& "' and [SomeOtherField] = '" & Me.cbwork2.Value & "'"

How I can update attachments and file path?

I have created a table where I'm saving attachments(in external folder) and file paths in the table. When I'm trying to update existing attachment with another, it does not work. Please see below "Add file" code and "Update button" code.
Private Sub cmAdd_Click()
On Error Resume Next
Dim strLokacioni As String
Dim strSQL As String
strLokacioni = "C:\Users\HSE\Desktop\datas\" & getFileName(Me.path.Value)
strSQL = "INSERT INTO tbl_tracker(path, filename, IncNo, PATS, SAP, First, Last, IncDate, Description, Location, OshaType, IncType, RootCause,Inspector, Surfaces, WeatherCon, WorkRelated, IncTime)" & _
"VALUES ( '" & strLokacioni & "', '" & Me.path.Value & "', '" & Me.txtInc & "', '" & Me.txtPATS & "', '" & Me.txtSAP & "', '" & Me.txtFirst & "', '" & Me.txtLast & "', '" & Me.txtDate & "', '" & Me.txtDesc & "', '" & Me.cmbLoc & "', '" & Me.cmbOsha & "', '" & Me.cmbType & "', '" & Me.txtCause & "', '" & Me.cmbInsp & "', '" & Me.cmbSur & "', '" & Me.cmbWcon & "', '" & Me.cmbRelated & "', '" & Me.txtTime & "')"
CurrentDb.Execute (strSQL)
MsgBox "Record Added", vbInformation, "Information"
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
fso.CopyFile Me.path.Value, strLokacioni
Set fso = Nothing
Me.tbl_tracker_subform.Form.Requery
End Sub
' Below is update button code
Private Sub Command88_Click()
'On Error Resume Next
Dim strLokacioni As String: strLokacioni = "C:\Users\HSE\Desktop\datas\" & getFileName(Me.path.Value)
Me.path = strLokacioni
CurrentDb.Execute "UPDATE tbl_tracker " & _
" SET IncNo = " & Me.txtInc & _
", path = '" & strLokacioni & "'" & _
", filename = '" & Me.filename & "'" & _
", PATS = '" & Me.txtPATS & "'" & _
", SAP = '" & Me.txtSAP & "'" & _
", First = '" & Me.txtFirst & "'" & _
", Last = '" & Me.txtLast & "'" & _
", IncDate = '" & Me.txtDate & "'" & _
", Location = '" & Me.cmbLoc & "'" & _
", Description = '" & Me.txtDesc & "'" & _
", OshaType = '" & Me.cmbOsha & "'" & _
", Inctype = '" & Me.cmbType & "'" & _
", RootCause = '" & Me.txtCause & "'" & _
", Inspector = '" & Me.cmbInsp & "'" & _
", Surfaces = '" & Me.cmbSur & "'" & _
", WeatherCon = '" & Me.cmbWcon & "'" & _
", WorkRelated = '" & Me.cmbRelated & "'" & _
", IncTime = '" & Me.txtTime & "'" & _
" WHERE IncNo = " & Me.txtInc.Tag
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
fso.CopyFile Me.path.Value, strLokacioni
Set fso = Nothing
MsgBox "Record Updated", vbInformation, "Information"
Me.tbl_tracker_subform.Form.Requery
End sub
And the the value Me.path.Value at the start of Command88_click is coming from :
Public Function getFileName(ByVal strPath As String) As String
If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
getFileName = getFileName(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function
Private Sub cbdBrowse_Click()
On Error Resume Next
Dim f As Object
Set f = Application.FileDialog(msoFileDialogFilePicker)
f.AllowMultiSelect = False
f.Show
Me.path.Value = f.SelectedItems(1)
End Sub
When I use update queries like you have here, I would always use the following syntax.
dim db as database
set db = currentDb
db.execute "UPDATE...."
would you require the same? Or have I been going about this a long way.
Also, I would have left a comment as this may not be the answer. Unfortunately, I cant due to rep<50

Access VBA/Prevent duplicate values

How I can prevent duplicate values to not insert into the table. I have created a code to INSERT, UPDATE and DELETE and I want to display a MsgBox that there is a duplicate value and to cancel it. Thanks. Below you have the code:
Private Sub Command12_Click()
If Me.emID.Tag & "" = "" Then
If (IsNull(Me.emID) Or (Me.emID = "") Or IsNull(Me.emFirst) Or (Me.emFirst = "") Or IsNull(Me.emLast) Or (Me.emLast = "")) Then
Me.emID.BorderColor = vbRed
Me.emFirst.BorderColor = vbRed
Me.emLast.BorderColor = vbRed
MsgBox "Please fill required fields", vbInformation, "Information"
Exit Sub
End If
CurrentDb.Execute "INSERT INTO tblEmployees(emID, first, last, gender, phone, mobphone, city, state, zip, adress, email, comment)" & _
"VALUES ('" & Me.emID & "', '" & Me.emFirst & "', '" & Me.emLast & "', '" & Me.emGender & "', '" & Me.emPhone & "', '" & Me.emMob & "', '" & Me.emCity & "', '" & Me.emState & "', '" & Me.emZip & "', '" & Me.emAdress & "', '" & Me.emEmail & "', '" & Me.emComment & "')"
MsgBox "Record Added", vbInformation, "information"
Else
CurrentDb.Execute "UPDATE tblEmployees " & _
"SET emiD =" & Me.emID & _
", first ='" & Me.emFirst & "'" & _
", last = '" & Me.emLast & "'" & _
", gender ='" & Me.emGender & "'" & _
", phone = '" & Me.emPhone & "'" & _
", mobphone ='" & Me.emMob & "'" & _
", city ='" & Me.emCity & "'" & _
", state ='" & Me.emState & "'" & _
", zip ='" & Me.emZip & "'" & _
", adress ='" & Me.emAdress & "'" & _
", email ='" & Me.emEmail & "'" & _
", comment ='" & Me.emComment & "'" & _
"WHERE emID =" & Me.emID.Tag
MsgBox "Updated!", vbInformation, "Information"
End If
Me.tblEmployees_subform.Form.Requery
End Sub
It sounds like you'd like to update an employee if one exists for the given ID otherwise you'd like to add a new employee. You can prevent adding duplicate employees by first trying to update an employee record with the given ID and if no records were updated only then do you add a new employee record.
Private Sub Command12_Click()
If (IsNull(Me.emID) Or (Me.emID = "") Or IsNull(Me.emFirst) Or (Me.emFirst = "") Or IsNull(Me.emLast) Or (Me.emLast = "")) Then
Me.emID.BorderColor = vbRed
Me.emFirst.BorderColor = vbRed
Me.emLast.BorderColor = vbRed
MsgBox "Please fill required fields", vbInformation, "Information"
Exit Sub
End If
' You must set CurrentDb to a variable otherwise the RecordsAffected
' property used later will be incorrect.
Dim db As DAO.Database
Set db = CurrentDb
' First try to update an existing employee.
db.Execute _
"UPDATE tblEmployees " & _
"SET first ='" & Me.emFirst & "', " & _
"last = '" & Me.emLast & "', " & _
"gender ='" & Me.emGender & "', " & _
"phone = '" & Me.emPhone & "', " & _
"mobphone ='" & Me.emMob & "', " & _
"city ='" & Me.emCity & "', " & _
"state ='" & Me.emState & "', " & _
"zip ='" & Me.emZip & "', " & _
"adress ='" & Me.emAdress & "', " & _
"email ='" & Me.emEmail & "', " & _
"comment ='" & Me.emComment & "'" & _
"WHERE emID =" & Me.emID.Tag & ";"
' If no records were affected by update then add a new employee.
If db.RecordsAffected = 0 Then
db.Execute _
"INSERT INTO tblEmployees(emID, first, last, gender, phone, mobphone, city, state, zip, adress, email, comment) " & _
"VALUES ('" & Me.emID & "', '" & Me.emFirst & "', '" & Me.emLast & "', '" & Me.emGender & "', '" & Me.emPhone & "', '" & Me.emMob & "', '" & Me.emCity & "', '" & Me.emState & "', '" & Me.emZip & "', '" & Me.emAdress & "', '" & Me.emEmail & "', '" & Me.emComment & "');"
MsgBox "Record Added", vbInformation, "Information"
Else
MsgBox "Updated!", vbInformation, "Information"
End If
Me.tblEmployees_subform.Form.Requery
End Sub
Note: In the update query I removed the update to the emID field since that is what the query is based on (in the WHERE clause). If the emID field is changing you won't be able to use the new emID value to find an employee record with the old emID value.
If you never want any duplicates I would also suggest that you add constraints to your database table to prevent duplicates, as suggested by Daniel Cook. I would also suggest looking into using parameterized queries instead of building SQL strings in VBA.
You can change your SQL to use IF EXISTS condition and insert only if the records does not already exists.
Your SQL may look like:
IF NOT EXISTS
(
SELECT ......
)
BEGIN
INSERT INTO tblEmployees ......<insert since employee does not exists>
END

DLookup as ControlSource through VBA code

The below is in my control source and works:
=IIf(Forms!GARF!GARFsubForm![finished_good_#]<>"",DLookUp("[CustomerSKU]","ItemCustomerSKU","ItemNumber = '" & Forms!GARF!GARFsubForm![finished_good_#] & "' AND Customer = '" & Forms!GARF!customer & "' AND Company = '" & Forms!GARF!company & "' AND MarketingSeason = '" & DLookUp("[Code]","IDtoCode","ID = " & Forms!GARF!season_id) & "' AND Season = " & Forms!GARF!GARFyear),"")
I would like to assign it to another control source through VBA code like such:
Forms![GARF]![GARFsubForm]![SKU].ControlSource = (the above code)
Forms![GARF]![GARFsubForm]![SKU] is a column in a datasheet.
UPDATE:
With Remou's help I was able to come up with the below working solution:
The code is on the Form_Load event:
Forms![GARF]![GARFsubForm]![SKU].ControlSource =
"=IIf(Forms!GARF!GARFsubForm![finished_good_#]<>'',"
& "DLookUp(""[CustomerSKU]"",""ItemCustomerSKU"",""ItemNumber = '""
& Forms!GARF!GARFsubForm![finished_good_#] & ""' AND Customer = '" _
& Forms!GARF!customer & "' AND Company = '" _
& Forms!GARF!company & "' AND Season = " & Forms!GARF!GARFyear _
& " AND MarketingSeason = '"
& DLookup("[Code]", "IDtoCode", "ID = " & Forms!GARF!season_id) & "'"")" & ",'')"
There are a few problems. This is what is returned by your string (broken into lines for clarity):
=IIf(Forms!GARF!GARFsubForm![finished_good_#]<>"",
DLookUp([CustomerSKU],ItemCustomerSKU,"ItemNumber = '"
& Forms!GARF!GARFsubForm![finished_good_#]
& " ' AND Customer = '" & Forms!GARF!customer
& "' AND Company = '" & Forms!GARF!company
& "' AND MarketingSeason = '" & DLookUp([Code],IDtoCode,"ID = "
& Forms!GARF!season_id) & "' AND Season = " & Forms!GARF!GARFyear),"")
As you can see, these two are not quoted and they need to be:
DLookUp([CustomerSKU],ItemCustomerSKU,
There is an extra space here:
& " ' AND Customer = '" & Forms!GARF!customer
Is finished_good_# text similarly season_id?
It is often possible to use single quote ' instead of "", especially if you escape any occurrence of ' in the text with two ' eg ='O''Reilly'
EDIT
You are doing this in code, so it should be possible to make life easier, for example:
A = DLookup("[Code]", "IDtoCode", "ID = " & Forms!GARF!season_id)
B = "DLookUp(""[CustomerSKU]"",""ItemCustomerSKU"",""ItemNumber = '" _
& Forms!GARF!GARFsubForm![finished_good_#] & "' AND Customer = '" _
& Forms!GARF!customer & "' AND Company = '" _
& Forms!GARF!company & "' AND Season = " & Forms!GARF!GARFyear _
& " AND MarketingSeason = '" & A & "'"")"
s = "=IIf(Forms!GARF!GARFsubForm![finished_good_#]<>''," & c & ",'')"
Debug.Print s

quickly insert data to remote mysql server in vb.net

I have small application in vb.net
I have one table in msaccess, which is having around 20,000 records,
now, I want to insert these records to remote server of mysql,
I tried as below code, it takes around 3-4 hours to insert data,
Can anyone show me faster way to insert data, i will be very glad..
dst in code is having all records from ms Access
For i As Integer = 0 To dst.Tables(0).Rows.Count - 1
mycmd.Connection = mycn
str = "INSERT INTO tblstudentresults(department_desc, grade, roll_no, name, course_code, course_desc, examination_type, total_marks, obtained_marks)"
/*'str = str & " VALUES('" & cname & "','" & sdr("grade").ToString() & "','" & sdr("st_code").ToString() & "','" & sdr("stName").ToString() & "','" & sdr("Subject_code").ToString() & "','" & sdr("Subject").ToString() & "','" & sdr("ExamTitle").ToString() & "','" & sdr("Maxmark").ToString() & "','" & sdr("score").ToString() & "')" -- Added non-VB comment here to improve readability */
str = str & " VALUES('" & cname & "', '" & dst.Tables(0).Rows(i)("grade").ToString() & "', '" & dst.Tables(0).Rows(i)("st_code").ToString() & "', '" & dst.Tables(0).Rows(i)("stName").ToString() & "', '', '" & dst.Tables(0).Rows(i)("Subject").ToString() & "', '" & dst.Tables(0).Rows(i)("ExamTitle").ToString() & "', '" & dst.Tables(0).Rows(i)("Maxmark").ToString() & "', '" & dst.Tables(0).Rows(i)("score").ToString() & "')"
mycmd.CommandText = str
mycmd.ExecuteNonQuery()
next
It might be faster to construct a multiple-row insert in one large string (or maybe chunks of, say 500 rows), then run the entire insert statement in a single call, something roughly like the following:
Dim firstRow as Boolean = True
str = "INSERT INTO tblstudentresults(...) VALUES"
For i As Integer = 0 To dst.Tables(0).Rows.Count - 1
' Only insert comma after first row, so we don't have comma at the end.
If Not firstRow Then str = str & ","
str = str & "('" & cname & "','" ...
firstRow = False
Next
mycmd.Connection = mycn
mycmd.CommandText = str
mycmd.ExecuteNonQuery()