I have two tables, Table: A which is built in Access and Table: Error which is a linked table in Excel. The Error Table has the calculation that is SQL coding that I want to be in the Query within Access. An example of the Error is:
IIf([Table A].[RETURN_DAYS]<>30,"-RETURN POLICY DAYS SHOULD BE 30","")
The Columns in the Errors Table are:
|Audit Name|Error Codes|
|Audit 1 |the code above
|Audit 2 |
Currently I manually Copy and paste the Error Code into the Query within the Field from the Excel table in order for the calculation to take place. This takes an incredibly long time since I have over 150+ Audits and 5 Different Error fields.
I want to be able to select the error from the error column in the linked table that is applicable based on the Audit name and place that error in the field so that when the Query is ran, access completes the calculation. I can not find any information on how to do this or if its possible. Any help is appreciated.
Since I have no idea about what cells you are using, or sheet names, you will need to adjust the following code.
This code will monitor changes to a certain Column (Your SQL) and will change the query in Access. Assumes the query name is in col A, SQL in col B.
Place this code in the sheet where you will make changes.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
'Monitor the range of cells you may be making changes to. I have assumed SQL is in col 2 (B)
If Target.column <> 2 Then Exit Sub ' If change not made in column 'A' then Ignore!
' Assuming you have the query name in Col A and the SQL in Col B
If Target.column = 1 Then
MsgBox "You are changing the query name?"
End If
If Change_SQL(Cells(Target.Row - 1, Target.column), Cells(Target.Row, Target.column)) <> "passed" Then
MsgBox "Update failed."
End If
End Sub
Function Change_SQL(strQueryName As String, strNewSQL As String) As String
'Declare Variables'
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim qdf As DAO.QueryDef
Dim strSQL_Old As String
Dim strSQL_New As String
'Connect to the Database'
On Error GoTo Error_Trap
Set dbs = DBEngine.OpenDatabase("C:\data\Access\xxxxxx.mdb", False, False, _
"MS Access;")
Set qdf = dbs.QueryDefs("Query5")
strSQL_Old = qdf.Sql
Debug.Print "Query Name: " & qdf.Name & vbTab & qdf.Sql
qdf.Sql = strNewSQL
qdf.Close
' You can execute the query if needed....
'Set rst = dbs.OpenRecordset(strNewSQL) ' If it's a select query
'Do While Not rst.EOF
' Do whatever
' rst.MoveNext
'Loop
'rst.Close
'Set rst = Nothing
Set dbs = Nothing
Change_SQL = "passed"
Exit Function
Error_Trap:
Change_SQL = "failed"
Debug.Print Err.Number & vbTab & Err.Description
MsgBox Err.Number & vbTab & Err.Description
Exit Function
Resume
End Function
Related
I am working in MS Access. All the tables and views are linked to a SQL Server database. I want to write a procedure that will retrieve and store all of the formatting information about these objects. A lot of this information is available from the property sheet (I open a table in Design View, and hit F4 for the property sheet). Eg:
Filter
Order By
Filter On Load
Order by On Load
Order by On
How do I retrieve these properties programmatically? I only see them listed for Reports.
Note that I need to retrieve the values, not just set them. I know about the SetFilter method, and that's not what I need.
The linked table exists as a DAO.TableDef in your database's TableDefs collection. So you can check the TableDef.Properties collection for those 5 properties.
However beware that both Filter and OrderBy are user-created instead of default properties, which means they are not included in the Properties collection unless you've assigned them values. Attempting to retrieve one which doesn't exist triggers error 3270, "Property not found". You can trap that error, respond to it as you wish, and continue on for the other properties you're interested in. Or you could first determine whether the property exists and only attempt to retrieve its value when it does exist.
This code sample uses the first approach (trap the error):
Const cstrTable As String = "YourLinkedTableNameHere"
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim strMsg As String
Dim varProp As Variant
Dim varProperties As Variant
On Error GoTo ErrorHandler
varProperties = Array("Filter", "FilterOnLoad", "OrderBy", _
"OrderByOn", "OrderByOnLoad")
Set db = CurrentDb
Set tdf = db.TableDefs(cstrTable)
For Each varProp In varProperties
Debug.Print varProp, tdf.Properties(varProp).Value
Next
ExitHere:
Exit Sub
ErrorHandler:
Select Case Err.Number
Case 3270 ' Property not found.
strMsg = "Property '" & varProp & "' not found."
'MsgBox strMsg
Debug.Print strMsg
Resume Next
Case Else
strMsg = "Error " & Err.Number & " (" & Err.Description & ")"
MsgBox strMsg
Resume ExitHere
End Select
How about something like this? (I've defined "table2" to have two fields, "PropertyName" and "PropertyValue"..."table1" is a placeholder for any of your existing tables)
Dim i As Integer
Dim j As Integer
Dim RS As DAO.Recordset
On Error Resume Next
Set RS = CurrentDb.OpenRecordset("select * from table2")
j = CurrentDb.TableDefs("table1").Properties.Count
For i = 0 To j - 1
RS.AddNew
RS!PropertyName = CurrentDb.TableDefs("table1").Properties(i).Name
RS!PropertyValue = Nz(CurrentDb.TableDefs("table1").Properties(i).Value, "-")
RS.Update
Next i
I have an access db that pulls volumes from a table of exceptions. Each volume has an ID. I've created queries to pull details, for all possible volumes, and saved each one with the same name as each volume ID. Each time the volume exceptions are pulled into this db, the volume IDs can change. So, there is a query that runs that updates the volume table with the new IDs.
Unless you know a way to do this with a query, I need to write Access VBA code that will loop through the volume table, identify the name of each query and then run those queries until it reaches the end of the table. For example, the code needs to look at the first record in the volume table, say it is 1040. This is the name of the query that needs to run. The code then needs to find the query named 1040 and run it. It is a make table query.
The table name is FacilityVolume and it has one field named Volume. The value in the field is shorttext format even though it is numeric.
I've tried a couple of different things. Here is my latest try.
Dim db as Database
Dim vol as Recordset
Dim code as QueryDef
Set db = CurrentDb()
Set vol = db.OpenRecordset("FacilityVolume")
Set Volume = vol.Fields("Volume")
Vol.MoveFirst
Do Until vol.EOF = True
If QueryDef.Name = Volume Then
DoCmd.OpenQuery
Else MsgBox("The query does not exist")
vol.MoveNext
Loop
End Sub
I've searched the internet for a few days and can't find any reference to this particular code. I'm sure other users would like to know how to do this. I'm a novice and still learning VBA so any help you can provide is greatly appreciated.
Your code will loop through, even if you found your query and you do not pass the Query-Name to the OpenQuery command... This won't work...
The collection CurrentDb.QueryDefs knows all existing queries, but there is no "Exists" or "Contains" method.
So: The approach would be a loop (as you tried it) or an Error handling.
It's quite a time ago since I've coded with VBA, but I think you could try:
On Error Resume Next
DoCmd.OpenQuery "YourQueryName"
If Err Then
MsgBox("The query does not exist!")
Err.Clear
End If
On Error Goto 0
I recommend using full DAO in VBA to accomplish your goal. DoCmd.OpenQuery is really a VBA function that mimics the Macro RunQuery action. You don't get much control or true error handling capability.
Here is a complete code function that
Gives you an example of how to select all or some records from your table that lists the queries, including the ability to only select "Active" records, and even sort them in a particular execution sequence
Handles the instances where the query name in your table does not exist
Allows you to display a message about any errors that occur
Allows you to return an exit code to the calling procedure so that you can possibly act on the results of running these queries (such as choosing not to do the next step in your code if this function encounters an error of any kind (returns a non-zero value)
Here is the code. You will need to modify the SQL statement for your correct table name and field names, but this should be a good example to get you on your way.
Public Function lsProcessQuerySet() As Long
On Error GoTo Err_PROC
Dim ErrMsg As String
Dim db As DAO.Database
Dim rstEdits As DAO.Recordset
Dim qdf As DAO.QueryDef
Dim mssql As String
Dim ReturnCode As Long
Set db = CurrentDb()
'============================
'Select the list of Queries you want to process
'============================
mssql = "SELECT tblQueryList.ID, tblQueryList.QueryName, "
mssql = mssql & "tblQueryList.QueryShortDesc "
mssql = mssql & "FROM tblQueryList "
mssql = mssql & "WHERE tblQueryList.QueryActive = True "
mssql = mssql & "ORDER BY tblQueryList.SortOrder;"
Set rstEdits = db.OpenRecordset(mssql, dbOpenDynaset)
DoCmd.Hourglass True
'============================
'Execute each query, allowing processing to continue
'if the query does not exist (an error occurs)
'============================
Do While Not rstEdits.EOF
Set qdf = db.QueryDefs(rstEdits("QueryName"))
qdf.Execute dbSeeChanges
ResumeNextEdit:
rstEdits.MoveNext
Loop
rstEdits.Close
Exit_PROC:
lsProcessQuerySet = ReturnCode
Set qdf = Nothing
Set rstEdits = Nothing
db.Close
Set db = Nothing
DoCmd.Hourglass False
Exit Function
Err_PROC:
Select Case Err.Number
Case 3265 'Item Not Found in this Collection
ReturnCode = Err.Number
ErrMsg = "Query Not Found:" & vbCrLf & vbCrLf
ErrMsg = ErrMsg & rstEdits("QueryName")
DoCmd.Hourglass False
MsgBox ErrMsg, vbOKOnly + vbCritical, "Function lsProcessQuerySet"
Resume ResumeNextEdit
Case Else
ReturnCode = Err.Number
ErrMsg = "Error: " & Err.Number & vbCrLf
ErrMsg = ErrMsg & Err.Description
DoCmd.Hourglass False
MsgBox ErrMsg, vbOKOnly + vbCritical, "Function lsProcessQuerySet"
Resume Exit_PROC
End Select
End Function
The answer of #Shnugo is already good. Just to give you a complete VBA function, this should be working for you.
Public Sub MySub()
On Error GoTo err_mySub
Dim db as Database
Dim vol as Recordset
Set db = CurrentDb()
Set vol = db.OpenRecordset("FacilityVolume", dbOpenDynaset) ' I don't know if you want to run all queries of the table "FacilityVolume".
'So maybe you could also use something like "SELECT Volume FROM FacilityVolume WHERE Volume LIKE ""*10*"""
Vol.MoveFirst
Do Until vol.EOF = True
DoCmd.OpenQuery vol!Volume
vol.MoveNext
Loop
exit_MySub:
Exit Sub
err_MySub:
If Err.Number = 7874 Then
MsgBox "The Query """ & Vol!Volume & """ wasn't found."
Resume Next
Else
MsgBox Err.Description
Resume exit_MySub
End If
End Sub
I am more or less a rookie in using VBA in Access and hope I'm not asking something stupid. Is it possible through VBA to run and save several queries that begin by the same word?
I have an Access file with multiple tables and queries, which are identified by an initial 3 digit code, eg 100QueryName. I am trying to only run the queries that begin with "901".
Hope someone can help me out.
Best regards
Jorge
The following code is a start (depending on what type of queries)...
Create a module and paste the following code. Then execute subroutine 'Test_it'
Option Compare Database
Option Explicit
Sub Test_it()
Dim strPrefix As String
' Ask user for query prefix
strPrefix = InputBox("Please enter query prefix", "Qry Prefix")
MsgBox "Executed " & Run_Queries(strPrefix) & " queries.", vbOKOnly, "COunt of Queries"
End Sub
Function Run_Queries(strPrefix As String) As Integer
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Dim strQryName As String
Dim iQryCt As Integer
Dim iQryRan As Integer
Dim i As Integer
Set dbs = CurrentDb
iQryCt = dbs.QueryDefs.Count
i = Len(strPrefix)
iQryRan = 0
For Each qdf In dbs.QueryDefs
strQryName = qdf.Name
Debug.Print strQryName
If LCase(left(strQryName, i)) = LCase(strPrefix) Then
Debug.Print " ** Run: " & strQryName & vbTab & qdf.Type
If qdf.Type = 0 Then ' Select query
' Open this query to view results
DoCmd.OpenQuery strQryName
ElseIf qdf.Type = 48 Then ' Update query
dbs.Execute strQryName
End If
iQryRan = iQryRan + 1
Else
End If
Next qdf
Set qdf = Nothing
Set dbs = Nothing
Run_Queries = iQryRan
End Function
I am trying to create an Access database that will link together multiple structurally identical databases together. These other databases are exports from a 3D model that have identical tables, but different data in each. What I need to do is report from all the database like they are one big database. How I thought I would approach this is to create queries that would union the individual identical tables from each database into one query, which I could then use in all my other reports. the code I wrote to join the tables together is below. The trouble I'm running into is that , this code gives me an out of stack space error on the "Set QueryDef..." line. Can someone tell me what I'm doing wrong?
Public Sub CreateUnionQueries()
'On Error GoTo Err_CreateUnionQueries
Dim QueryRs As DAO.Recordset
Dim TableRs As DAO.Recordset
Dim QueryDef As DAO.QueryDef
Dim SQLText As String
Dim qry As QueryDef
'Get list of all Foreign Table Names
Set QueryRs = CurrentDb.OpenRecordset("select distinct ForeignName from msysobjects where ForeignName is not null")
'Loop over list to create union queries
If QueryRs.RecordCount <> 0 Then
Do While Not QueryRs.EOF
Set TableRs = CurrentDb.OpenRecordset("select Name from msysobjects where ForeignName = """ & QueryRs![ForeignName] & """")
Do While Not TableRs.EOF
SQLText = SQLText & "select * from " & TableRs![Name]
TableRs.MoveNext
If Not TableRs.EOF Then
SQLText = SQLText & " UNION ALL "
End If
Loop
'Create union query
For Each qry In CurrentDb.QueryDefs
If qry.Name = "Q-" & QueryRs![ForeignName] Then
DoCmd.DeleteObject acQuery, "Q-" & QueryRs![ForeignName]
End If
Next qry
Set QueryDef = CurrentDb.CreateQueryDef("Q-" & QueryRs![ForeignName], SQLText)
QueryDef.Close
Set QueryDef = Nothing
QueryRs.MoveNext
TableRs.Close
Set TableRs = Nothing
Loop
Else
MsgBox "No files are linked currently"
End If
QueryRs.Close
Err_CreateUnionQueries:
MsgBox "We have an error"
Set QueryRs = Nothing
Set TableRs = Nothing
Exit Sub
End Sub
Oh man, I'm an idiot. Found the problem. When I was looping, I wasn't setting SQLText back to empty, so it was appending my query for table group onto the last. Removed that and now it works as expected. Thank you guys for your help.
I'm performing a data cleansing operation on an access database. I have several duplicate records in a table that I want to consolidate down into one single record. In doing this I will need to update all references to the records that I will be consolidating.
If I know the column name that holds the record id is there a way to find all of the tables in access that contain this column?
You can examine the TableDefs collection and determine which tables contain a field with a given name.
Public Sub TablesWithField(ByVal pName As String)
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim strMsg As String
Dim strName As String
On Error GoTo ErrorHandler
Set db = CurrentDb
For Each tdf In db.TableDefs
strName = vbNullString
'ignore system and temporary tables '
If Not (tdf.name Like "MSys*" Or tdf.name Like "~*") Then
strName = tdf.Fields(pName).name
If Len(strName) > 0 Then
Debug.Print tdf.name & ": " & pName
End If
End If
Next tdf
ExitHere:
On Error GoTo 0
Set tdf = Nothing
Set db = Nothing
Exit Sub
ErrorHandler:
Select Case Err.Number
Case 3265 'Item not found in this collection. '
Resume Next
Case Else
strMsg = "Error " & Err.Number & " (" & Err.description _
& ") in procedure TablesWithField"
MsgBox strMsg
GoTo ExitHere
End Select
End Sub
Short answer: Yes. And there are many ways to skin that cat. Two ideas:
(1) Via VBA, make use of: Application.CurrentDb.TableDefs(i).Fields(j).Name
(2) Via Tools==>Analyze==>Documenter, make a report and then search its output (Publish it with MS Word).
Sorry, but Access isn't built like MS SQL Server or DB2 - the MSys* tables really aren't set up for querying table schemas like that. However, others have VBA based solutions that look useful.
You can use Schemas, not exactly a query, but similar:
Function ListTablesContainingField(SelectFieldName) As String
'Tables returned will include linked tables
'I have added a little error coding. I don't normally do that
'for examples, so don't read anything into it :)
Dim cn As New ADODB.Connection
Dim rs As ADODB.Recordset
Dim strTempList As String
On Error GoTo Error_Trap
Set cn = CurrentProject.Connection
'Get names of all tables that have a column called <SelectFieldName>
Set rs = cn.OpenSchema(adSchemaColumns, _
Array(Empty, Empty, Empty, SelectFieldName))
'List the tables that have been selected
While Not rs.EOF
'Exclude MS system tables
If Left(rs!Table_Name, 4) <> "MSys" Then
strTempList = strTempList & "," & rs!Table_Name
End If
rs.MoveNext
Wend
ListTablesContainingField = Mid(strTempList, 2)
Exit_Here:
rs.Close
Set cn = Nothing
Exit Function
Error_Trap:
MsgBox Err.Description
Resume Exit_Here
End Function