So I'm a little confused as to how to handle an external database and current database within VBA code. Below is a sub whose purpose is to update the current Access database with unique entries found in the external Access database.
The external SourceDBPath and SelectedTable is passed in, and I specify the external database and table with the string variable SourceDBTable. Then, in the SQL, I try to pull out entries with values that don't match their coresponding field so only unique entries between the two DBs are inserted into the source database.
(For Example, where source = external:
NOT EXIST sourceDB.SelectedTable.Field1 = currentDB.SelectedTable.Field1 And sourceDB.SelectedTable.Field2 = currentDB.SelectedTable.Field2 And sourceDB.SelectedTable.Field3 = currentDB.SelectedTable.Field3, etc.)
SO, my questions are:
1) Do I need to specify the current database within the SQL (like currentDB.table.field), or will it default to the current database if a table or field is called without a prefix (just table or field, like in the code below)?
2) Ultimately, am I going about this in the right way?
My code:
Private Sub UpdateDatabaseTable(SourceDBPath As String, SelectedTable As String)
Dim SourceDBTable As String
On Error GoTo DBError
SourceDBTable = "[;DATABASE=" & SourceDBPath & "]." & SelectedTable
Call DoCmd.RunSQL("INSERT INTO " & SelectedTable & " " & _
"SELECT Field1, Field2, Field3 " & _
"FROM " & SourceDBTable & " " & _
"WHERE NOT EXISTS( SELECT * " & _
"FROM " & SourceDBTable & " " & _
"WHERE (Field1=" & SourceDBTable & ".Field1 And Field2=" & SourceDBTable & ".Field2 And Field3=" & SourceDBTable & ".Field3"));")
GoTo EndSub
DBError:
MsgBox "Database Error!" & vbCrLf & "Error #" & Str(Err.Number) & ": " & Err.Source & vbCrLf & Err.Description, vbExclamation, "Database Error"
EndSub:
End Sub
NOTE: I derived my SQL by extrapolating and modifying the code found in the solution HERE
You have 2 main mistakes in your code, otherwise, it should work.
Don't specify the tablename for each field. Use an alias instead
You want to escape both the tablename, and the database name, not only the database name
Private Sub UpdateDatabaseTable(SourceDBPath As String, SelectedTable As String)
Dim SourceDBTable As String
On Error GoTo DBError
SourceDBTable = "[;DATABASE=" & SourceDBPath & "].[" & SelectedTable & "]"
DoCmd.RunSQL "INSERT INTO " & SelectedTable & " t " & _
"SELECT Field1, Field2, Field3 " & _
"FROM " & SourceDBTable & " s" & _
"WHERE NOT EXISTS( SELECT * " & _
"FROM " & SourceDBTable & " s1 " & _
"WHERE (t.Field1=s1.Field1 And t.Field2=s1.Field2 And t.Field3=s1.Field3));"
GoTo EndSub
DBError:
MsgBox "Database Error!" & vbCrLf & "Error #" & Str(Err.Number) & ": " & Err.Source & vbCrLf & Err.Description, vbExclamation, "Database Error"
EndSub:
End Sub
I've also removed the deprecated Call keyword. Optionally, you can adjust this further by using CurrentDb.Execute, but that's not needed
Following code from my db SENDS data to OTHER db:
strExtract = gstrBasePath & "Program\Editing\ConstructionExtract.accdb"
CurrentDb.Execute "INSERT INTO Bituminous IN '" & strExtract & "' SELECT * FROM ConstructionBIT;"
gstrBasePath is a Global constant declared in a general module:
Global Const gstrBasePath = "\\servernamehere\Crm\Lab\Database\"
You can use literal string path within your procedure.
Following PULLS data from OTHER db:
CurrentDb.Execute "INSERT INTO Employees SELECT * FROM Employees IN '\\servername\filename.accdb'"
Related
i had this error when i was trying to INSERT records to a local table with VBA.
I have checked the data type and putting in the quotes for the the short text data type but it doesn't work.
table_newid = "SELECT Cint(t1." & id_name(i) & "_new), " & Replace(select_column_str, local_table_name, "t2") & " FROM " & vbCrLf & _
"(SELECT CInt(DCount(""[" & id_name(i) & "]"", """ & qry_distinct_id_name & """, ""[" & id_name(i) & "]<="" & [" & id_name(i) & "])) as " & id_name(i) & "_new, * FROM " & qry_distinct_id_name & ") AS t1 " & vbCrLf & _
"LEFT JOIN " & local_table_name & "_ALL as t2 " & vbCrLf & _
"ON t1." & id_name(i) & " = t2." & id_name(i) & " " & vbCrLf & _
"WHERE t2.database = '" & database_name & "'"
strQuery = "INSERT INTO " & local_table_name & "_temp (" & temp_field(i) & ", " & Replace(select_column_str, local_table_name & ".", "") & ") " & vbCrLf & table_newid
Debug.Print strQuery
DoCmd.SetWarnings False
db.Execute strQuery
DoCmd.SetWarnings True
From the debug.print, i have got:
INSERT INTO TblLUMachineTypes_temp (MachTypeID_new, MachTypeID, MachTypeCode, MachTypeMod, MachTypeDesc, MachTypeDisc, NewCode, Approved, mttime, CreatedBy, CreatedTS, ModifiedBy, ModifiedTS)
SELECT t1.MachTypeID_new, t2.MachTypeID, t2.MachTypeCode, t2.MachTypeMod, t2.MachTypeDesc, t2.MachTypeDisc, t2.NewCode, t2.Approved, t2.mttime, t2.CreatedBy, t2.CreatedTS, t2.ModifiedBy, t2.ModifiedTS FROM
(SELECT CInt(DCount("[MachTypeID]", "qry_TblLUMachineTypes_id_distinct", "[MachTypeID]<=" & [MachTypeID])) as MachTypeID_new, * FROM qry_TblLUMachineTypes_id_distinct) AS t1
LEFT JOIN TblLUMachineTypes_ALL as t2
ON t1.MachTypeID = t2.MachTypeID
WHERE t2.database = 'CPM-252-2'
When i copied this query and execute it manually, it works fine but not with VBA. Any idea?
Thanks in advance.
Remove all the & vbCrLf from your code, they are not necessary and I assume they corrupt the SQL syntax.
I found the problem. I found that qry_distinct_id_name query table has a Dlookup function in there that returns a string value, which will work when executing the query manual but doesn't work when you run it with VBA. So I have re-written the code to put in the quote before and after dlookup() function.
I am attempting to write an UPDATE function based on values that will be input into dropdown boxes and text boxes by a user
My code is as follows:
Private Sub cmdUpdate_Prices_Click()
Dim SQL_string As String
SQL_string = _
"UPDATE tblPrice " & _
"SET [P/N] = " & Me.txtPartNumber.Column(0) & ", " & _
"Type = " & Me.txtPriceType.Column(0) & ", " & _
"Region = " & Me.txtRegion.Column(0) & ", " & _
"Price = " & Me.txtPrice.Value & ", " & _
"WHERE ID = " & Me.txtID.Value & ";"
DoCmd.RunSQL SQL_string
End Sub
I keep getting a syntax error in the UPDATE function and I'm not sure where it is.
Any help is appreciated. Thanks!
I ran a SQL UPDATE statement in MS Access, but received a error message
Syntax error (missing operator) in query expression
I searched in internet, but any solutions works in my situation.
My code is:
Private Sub Command111_Click()
CurrentDb.Execute " UPDATE test3 " & _
"SET OrderStatus= 'Producing' " & _
"WHERE OrderID='" & Me!cboOrderID1 & "' ProductName='" & Me!ComboProduct1 & "'"
End Sub
Please help me check where is wrong.
Thanks
I am assuming that OrderID is int so it cannot be in '' quotes and must be as number in statement
"WHERE OrderID=" & Me!cboOrderID1 & " AND/OR ProductName='" & Me!ComboProduct1 & "'"
Also you forgot to use AND or OR
Forgot your AND
Private Sub Command111_Click()
CurrentDb.Execute " UPDATE test3 " & _
"SET OrderStatus= 'Producing' " & _
"WHERE OrderID='" & Me!cboOrderID1 & "' AND ProductName='" & Me!ComboProduct1 & "'"
End Sub
Thank you guys! This code works in my situation.
Private Sub Command111_Click()
CurrentDb.Execute " UPDATE test3 " & _
"SET OrderStatus= 'Producing' " & _
"WHERE OrderID='" & Me!cboOrderID1 & "' AND ProductName=" &CStr(Me!ComboProduct1) & ""
End Sub
In my case, the ProductName is sourced from a combo box.
I'm trying to write a query in MS Access 2010 in order to use it to print a report, but it gives me "missing parameter" error in "set qd" line, hereunder is the code i wrote, can you please help me and tell me what is wrong with my code:
`Private Sub Command5_Click()
Dim qd As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strSql As String
Dim strFrom, strTo As String
strFrom = [Forms]![FrmPrintSelection]![txtFrom]
strTo = [Forms]![FrmPrintSelection]![txtTo]
strSql = "SELECT tblInvoiceHead.CustomerNumber,
tblCustomers.AccountName,tblCustomers.Address,
tblCustomers.Phone1, tblCustomers.Phone2," _
& "tblCustomers.Mobile1, tblCustomers.Mobile2, tblInvoiceHead.InvoiceNumber,
tblInvoiceHead.InvoiceDate, tblInvoiceHead.TotalInvoice," _
& "tblInvoiceHead.CashDiscount, TblInvoiceDetails.Item, TblInvoiceDetails.Unit,
TblInvoiceDetails.Qtn, TblInvoiceDetails.Price," _
& "TblInvoiceDetails.[Discount%], TblInvoiceDetails.CashDiscount,
TblInvoiceDetails.NetUnitPrice, TblInvoiceDetails.TotalPrice, tblInvoiceHead.InvoiceType" _
& "FROM (tblCustomers INNER JOIN tblInvoiceHead ON tblCustomers.AccountNumber =
tblInvoiceHead.CustomerNumber) INNER JOIN TblInvoiceDetails" _
& "ON tblInvoiceHead.InvoiceNumber = TblInvoiceDetails.InvoiceNumber" _
& "WHERE (((tblInvoiceHead.InvoiceNumber) Between " & strFrom & " And " & strTo & "))"
Set qd = CurrentDb.CreateQueryDef("RepInv", strSql)
Set rs = qd.OpenRecordset
'DoCmd.OpenQuery "repinv", strSql
Reports!repinvoicetest.RecordSource = "repinv"
DoCmd.OpenReport "repinvoicetest", acViewPreview
End Sub
`
Usually the error "missing parameter" means that you spelled one of your columns wrong. If you take your sql and paste it into a new query (temp, don't save) and run it, the misspelled column will pop up a window asking you to provide a value for that "parameter" (because MSAccess is assuming that you never would misspell a column name).
In your query above, you might have copy/pasted it wrong, but if not, then you don't have enough spaces between your words as you continue them on the next line. For instance, your SQL string would end up having some stuff in it like "InvoiceTypeFROM", because you didn't have an extra (necessary) space in there.
Try this query instead:
strSql = "SELECT tblInvoiceHead.CustomerNumber, " _
& " tblCustomers.AccountName,tblCustomers.Address, " _
& " tblCustomers.Phone1, tblCustomers.Phone2, " _
& " tblCustomers.Mobile1, tblCustomers.Mobile2, tblInvoiceHead.InvoiceNumber, " _
& " tblInvoiceHead.InvoiceDate, tblInvoiceHead.TotalInvoice, " _
& " tblInvoiceHead.CashDiscount, TblInvoiceDetails.Item, TblInvoiceDetails.Unit, " _
& " TblInvoiceDetails.Qtn, TblInvoiceDetails.Price, " _
& " TblInvoiceDetails.[Discount%], TblInvoiceDetails.CashDiscount, " _
& " TblInvoiceDetails.NetUnitPrice, TblInvoiceDetails.TotalPrice, " _
& " tblInvoiceHead.InvoiceType " _
& " FROM (tblCustomers INNER JOIN tblInvoiceHead " _
& " ON tblCustomers.AccountNumber = tblInvoiceHead.CustomerNumber) " _
& " INNER JOIN TblInvoiceDetails " _
& " ON tblInvoiceHead.InvoiceNumber = TblInvoiceDetails.InvoiceNumber " _
& " WHERE (((tblInvoiceHead.InvoiceNumber) Between " & strFrom & " And " & strTo & "))"
Notice how I added a lot of unncessary spaces at the begining and end of each line. All of those extra spaces will be ignored. However, if there are too few, then you will get errors. It is a simple trick that I stick-with.
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).