How to do a MS Access Update query for a table in external database - sql

Im trying to perform an update query on a table that its on a separate database, so far i have this SQL:
UPDATE [;database=C:\QA_Daily_YTD_Report_Export.accdb].[YTD-Daily_Report] AS EXT_DB
SET EXT_DB.Category1 = "1"
WHERE (EXT_DB.Category1 = "status1");
When i run this it returns an "invalid operation" error. Any idea what im doing wrong?

I would recommend linking the table [YTD-Daily_Report] into your database because you can easily put the update query into your code without having your code execute the connection to the other database.
You can link a table in Access by clicking on the External Data. Then click on the Access symbol.
You should then get a dialog box like this:
Be sure you choose the second radio button because you don't want to import the data from the database, just link it.
Navigate to the location of the Database and click on it. Then make sure your database is shown in the dialog box above and click okay.
You should then get a dialog box like this one that will show the table you won't. Highlight it and click okay. Now you can rename the linked table with any name you want and this will be a much less of a stumbling block for your work.

Try to omit ;database=
UPDATE [C:\QA_Daily_YTD_Report_Export.accdb].[YTD-Daily_Report] AS EXT_DB SET EXT_DB.Category1 = "1" WHERE (EXT_DB.Category1 = "status1");

I ended up using VBA in a form, just in case someone is wondering how here it is:
Dim SQL As String
Dim db_external As Database
Set db_external = OpenDatabase(CurrentProject.Path & "\QA_Daily_YTD_Report_Export.accdb")
SQL = "UPDATE [YTD-Daily_Report]" & Chr(13) & _
"SET [YTD-Daily_Report].Category1 = '" & New_value & "'" & Chr(13) & _
"WHERE ([YTD-Daily_Report].Category1= '" & Look_up_value & "');"
db_external.Execute SQL

Related

Error 2465 in MS Access when running a VBA code

Read through a few of the previously asked posts about this error but still cannot understand it.
The error text is "Run-time error '2465' CASREP reporting tool can't find the field '|1' referred to in your expression
I have a form to assign parts to certain supply reports. We have a form where users can manually hyperlink the parts to the request if they fall in the cracks. There is a check box feature, followed by the use of an "Assign" button to achieve this.
Every time a box is checked and a user selects "Assign" the error pops up. The string of code that pops up with the bug is as follows:
strSQL_del = "DELETE FROM [tbl_Temp_Assign] " & _
"WHERE [jcn_cd]= '" & Forms![Parts: Assign Unit].[tblTemp_Assign subform1].Form.[jcn.cd] & "'
AND [CASREP #] = '" & strCASREP & "' AND [doc_num_cd] = '" & Forms![Parts: Assign Unit].[tblTemp_Assign subform1].Form.[doc_num_cd] & "'
AND [last_updated_dte] = #" & Forms![Parts: Assign Unit].[tblTemp_Assign subform1].Form.[last_updated_dte] & "#
AND [PMOMsgDte] = #" & Forms![Parts: Assign Unit].[tblTemp_Assign Unit].Form.[PMOMsgDte] & "#" 'Intentionally left off AssignDte
Any help is greatly appreciated. I'm lost on what is wrong.
The error is related to the SQL string concatenation, but that string is quite long, it's hard to say if you have a space between ' and the first AND condition. Also, after the first continuation character _, is all that a single line?
Anyway, I would strongly advise to setup a delete query where you pass the form values as parameters and in VBA you just execute the query. It will be easier to update later on if needed.
The query:
PARAMETERS [prmTextField] Text (50), [prmDateField] DateTime, [prmNumberField] Long;
DELETE *
FROM T
WHERE T.TextField = [prmTextField]
AND T.DateField = [prmDateField]
AND T.NumberField = [prmNumberField];
Then, in VBA just execute the query.
With CurrentDb().QueryDefs("QueryName")
.Parameters("[prmTextField]").Value = '[Value from Form (text)]
.Parameters("[prmDateField]").Value = '[Value from Form (date)]
.Parameters("[prmNumberField]").Value = '[Value from Form (number)]
.Execute dbFailOnError
End With
By the way, do you really need to pass all those parameters to delete a record? Usually, just the record id is needed.

Is there a simple code to allow certain user(s) access to see command buttons?

Okay, I am having difficulties coding security behind my user form. Let me give you guys the rundown. I created this make table "tblPermissionTypes" that basically has two field in there "ID" & "EmployeeType_ID". The ID field represents Security level of access 0 through 2, and EmployeeType_ID is the title: 0 = Requestor, 1 = Admin, and 2 = Printer.
With that being said I have another table "tblEmployees" with the same field "EmployeeType_ID", I manually set the 0s, 1s, & 2s. This table also contains all employees UserNames
Finally, I have another table "tblPermission" that contains three fields "EmployeeType_ID", "FormName", and "HasAccess"
My end result is being whenever this tblPermission has a Checkbox under the field HasAccess I want to grant access based on the EmployeeType_ID field to communicate back to the table "tblEmployees", but in this case I want them to only be able to see a button that contains that certain form.
Private Sub cmdClick_Click()
Dim strSQL As String
Dim permission As String
If permission = ("fOSUserName") = True Then
Run strSQL
strSQL = "SELECT * FROM tblEmployees WHERE "
strSQL = strSQL & "tblEmployees.Five2 =" & ("fOSUserName") & """, = False
Then
MsgBox "You do not have permission!", vbExclamation
Else'
cmdButton.Visible True
End If
NOTE: fOSUserName, is a function I created basically the same thing as
Environ("UserName")
Debug.Print strSQL
Function calls should not be within quote marks. You construct an SQL statement but then don't properly use it. You declare and use variable permission but don't set the variable - it is an empty string. Need form name as a search criteria. Couple of other syntax errors but they will go away with this suggested code. Run this code in form Open event to disable button and don't even give unauthorized users opportunity to click. Don't annoy them with a popup message that emphasizes their lowly status in hierarchy.
You need to build a query that joins tblEmployees to tblPermission so that UserName, FormName, HasAccess fields are all available then reference that query in search for permission.
A DLookup could serve here.
Me.buttonNameHere.Visible = Nz(DLookup("HasAccess", "queryNameHere", _
"UserName='" & fOSUserName & "' AND FormName='FormNameHere'"), 0)

MS Access - SetFocus on multiple text boxes to check if data exists via SQL

The problem I'm facing:
I try to check if inserted text from multiple text boxes is already existing in a table before saving the records to avoid duplicates.
I created a form to enter new members and save them into a table. The key to avoid duplicates is to check the combination of given name, last name and birth date with existing records. (It's most likely that there won't be two person with all three criteria matching)
I have no problem to check the existence for only one text box by setting the focus on the desired box and use the SQL query IF EXISTS...
But since I would need to set focus on several text boxes(IMO) the problem occurs.
Is there a way to set focus on multiple text boxes?
The idea would be to use an IF EXISTS...AND EXISTS statement and I would need to implement the .SetFocus statement for each text box before checking its existence.
I hope you get my point and I would be glad if someone could share some knowledge. :)
Thanks in advance
There seems to be some missing information in order to find the best solution to your problem. so the below response will be based on assumptions as to how your form is working.
I'm assuming you are using an unbound form with unbound text boxes? if this is the case, then you must have a button that is the trigger for checking/adding this information to your table. lets say your command button is called "Save". You can use the following code without the need to .setfocus to any textbox.
Private Sub Save_Click()
Dim db as DAO.Database
Dim rst as DAO.Recordset
Dim strSQL as string
set db = currentdb 'This is the connection to the current database
'This is the SQL string to query the data on your table
strsql = "SELECT * " & _
"FROM [Yourtablename] " & _
"WHERE ((([YourTableName].[FirstName]) ='" & me.FormFirstNameField & "' AND ([YourTableName].[LastName]) ='" & me.FormLastNameField & "' AND ([YourTableName].[DOB]) =#" & me.FormDOBField & "#));"
set rst = db.openrecordset(strsql) 'This opens the recordset
if rst.recordcount <> 0 then
'Enter code to inform user information already exists
else
'Enter code if information does not exits
end if
rst.close 'Closes the recordset
set rst = nothing 'Frees memory
set db = nothing 'Frees Memory
End Sub
Let me know if this code works or if I need to make changes based on your scenario.

Referencing Variable for Functions

Every two weeks there will be a new table with new data coming in to me, I need to update that onto a master table. I want to automate this process.
I would like to declare a variable that a user can input the date the data is from, and based on that date update to the appropriate field on the master table. I have no clue how to make SQL functions use variables to locate tables with the syntax, not even sure if this can be done. Any help would be appreciated.
As I am inexperienced, I am making a VBA Macro and embedding the SQL code from the access query I made.
Sub UpdateFieldX()
Dim SQL As String
SQL = "UPDATE [15-Jun-16] " & _
"RIGHT JOIN MasterSPI " & _
"ON [15-Jun-16].[SR#] = MasterSPI.[SR#] " & _
"SET MasterSPI.[30-Jun-16] = [15-Jun-16].[SPI]; " _
DoCmd.RunSQL SQL
End Sub
I've done something similar to this and used an Update Query and Insert Query.
It sounds like you're trying to just update any existing records that may need updating and then adding new records into the table.
For an update, I'd try creating a query in SQL view and type something like:
UPDATE MasterSPI SET MasterSPI.SRnumber = [newtablename]![SRnumber] etc.
and do that for each field in your table.
For inserting you could do something like:
INSERT INTO MasterSPI SELECT * FROM newtablename
That may help you get started.
I know many of you are advanced users but I found an answer that fit my quick needs. As a notice and disclaimer for other people, it will be in no way secure, it is more for personal use such that I do not need to spend an hour doing append and updates to several master tables repetitively.
To do this, I made a global string variable called name, then I made another variable called strung that translated it into a readable string for referencing. I then made an SQL string that references that strung variable. This allows the user to submit an input for the global variable, which translates into a readable string for the RunSQL method.
Here's a snippet of the parts that were most relevant, I hope it helps whoever comes next with the same scenario.
**
Public name As String 'global variable declared so that the new field to be created can be used elsewhere
name = InputBox("Name of Month", "InputBox") 'variable that takes user input and it will be name for new fields to be added
Dim SQLa As String 'creates a string variable such that it will be read as an SQL line by the RunSQL method
strung = "[" & name & "]" 'sets strung as global varible name, which is user input on the specific table being used to update
'the following lines runs a query such that it updates the master table with new data and does the grouping by SR number
SQLa = "UPDATE " & strung & " " & _
"RIGHT JOIN MasterSPI " & _
"ON " & strung & "." & "[SR#] = MasterSPI.[SR#] " & _
"SET MasterSPI." & strung & " = " & strung & "." & "[SPI]; " _
DoCmd.RunSQL SQLa 'executes the SQL code in VBA **

Microsoft Access 2010 - Dynamic query

I have an access web database that several users will need to log in to. The database contains a table of products.
The challenge is, every user needs to only see a subset of these products and never see the whole list.
At the moment i have some code to modify an existing query based on the logged in user's details. As they log in, some tempvars are created and these are used to modify the query criteria.
This works well when the first user logs in, but the moment the next user logs in, the query is modified again and the product list refreshes and now his products are shown and not the first users! Im thinking i need to dynamically create a permanent query for each user on log in?
Or is a better way to accomplish what im trying ? im quite new to access and struggling. Can anyone assist please?
Here is my code so far:
Button on login form has the following code that collects the user's details
Private Sub cmdLoginMine_Click()
Dim ID as long, strEmpName as string,strZondsc as string,strgrpdsc as string
ID = DLookup("ID", "Employees", "Login='" & Me.txtUser.Value & "'")
strEmpName = DLookup("FullName", "Employees", "Login='" & Me.txtUser.Value & "'")
strgrpdsc = DLookup("MyGrpdscs", "Employees", "Login='" & Me.txtUser.Value & "'")
strzondsc = DLookup("MyZondscs", "Employees", "Login='" & Me.txtUser.Value & "'")
TempVars.Add "tmpEmployeeID", ID
TempVars.Add "tmpEmployeeName", txtUser.Value
I then call a function that modifies the existing query, populating it with this users details for the criteria
qryEdit strgrpdsc, strzondsc, ID
Sub qryEdit(strgrpdsc As String, strzondsc As String, ID As Long)
Dim qdf As DAO.QueryDef
Dim qdfOLD As String
Set qdf = CurrentDb.QueryDefs("InventoryQryforDS")
With qdf
.SQL = "SELECT Products.ProductCode, Products.ProductName, Products.GRPDSC, Categories.Category, Inventory.Available " & _
"FROM (Categories INNER JOIN Products ON Categories.ID = Products.CategoryID) INNER JOIN Inventory ON Products.ID = Inventory.ProductID " & _
"WHERE Products.GRPDSC in (" & strgrpdsc & ") and Categories.Category in (" & strzondsc & ") and products.ownersid =" & ID & _
" ORDER BY Products.ProductCode"
End With
Set qdf = Nothing
End Sub
The results of the query are shown on a form, which is what is currently requerying and showing the wrong data.
Thanks
EDIT - THe data is shown on a form, linked to one of the new style navigation buttons as shown.The recordsource property of the form is the query that's populated as described above.
I have a few suggestions/corrections to your approach to solving this issue.
When using DLookup, make sure they are enclosed within Nz() function, if the value you are looking for is not found you might be facing troubles of assigning a Null value to a Data Type that cannot handle Null. Anything other than Variant type will suffer.
You seem to do not one but four DLookup's on the table. This could be very expensive. This could be minimized by using a simple RecordSet Object.
I would not use TempVars much as they could be tricky to understand and implement.
Why are you editing the Query? This could again be a bit expensive in terms of memory. How are you showing the list of Products? In DataSheet or ComboBox or LsitBox? You could yet again change the RecordSource or RowSource of the Objects rather than editing the Query itself.
Finally, your users should all have a separate copy of the Front End file. Not one copy used by 20-30 people. If the files is restricted to be used by one person, then the code should work regardless of being modified. As the user will have access to the right data at all times.