vba access append multiple tables into one - vba

First off I'm a novice at programming.
Question I have built the code below from many examples off the internet.
The database is named "Code Holder" at this time I have a table "test" and into that table I want append as many tables as there are in the database.
All columns will be the same for all tables
The table names other than "Test" will change
What I have so far is below,
The code runs fine, but I can't seem to get each table to append into the "Test" table, each table comes up blank in the SQL string
Sub append4()
Dim db As Database
Dim tdf As TableDef
Dim rs As Recordset
Set db = currentdb()
Set rs = db.OpenRecordset("test")
For Each tdf In db.TableDefs
StrSQL = "INSERT INTO " & "test" & " " & _
"SELECT * " & _
"FROM " & "rs!tablename" & " ;"
DoCmd.RunSQL StrSQL
Next tdf
Set db = Nothing
End Sub
I want to say that I haven't set rs. correctly but I'm not certain.
Any help would be appreciated.
Thanks

Afternoon, after posting I came across somthing that really helped. Below is the updated VBA code and after testing it works for me.
Thanks Barett, yes I was referencing a table incorrectly, but that's what happens when you stare at somthing for way too long.
Feel free to copy and use if you'd like
'please note there are a few things that one assumes while using this code
'1 all tables column headers are the same
'2 this was used with Access 2010
Sub testeroony2()
Dim db As DAO.Database
Dim tdf As DAO.TableDef
'you can set this database to other databases if you wanted too
Set db = currentdb
For Each tdf In db.TableDefs
' ignore system and temporary tables
'if you want to use it for your own use then you will need to change "test" that is the main table that gets uploaded too
If Not (tdf.Name Like "MSys*" Or tdf.Name Like "~*" Or tdf.Name Like "test") Then
'you will need to also change "test" below to the main table you want appended too
StrSQL = "INSERT INTO " & "test" & " " & _
"SELECT * " & _
"FROM " & tdf.Name & " ;"
DoCmd.RunSQL StrSQL
End If
Next
Set tdf = Nothing
Set db = Nothing
End Sub

Related

Microsoft Access 2016 Summarize and Merge Table with SQL

I have a table that I need to format for use in a manual upload process. The table is thousands of rows so I need to use a repeatable process to quickly fix the way the data is given to me into what it needs to be. I have zero ability to control the way the data comes to me today. But, I have to format it to use it due to a system limitation. My current table is 4 columns, I need to output it as 3 columns. I have to group up by field names: "brand" and "promotion". Field name: "skus" I need to take and merge them into one continuous string by a single "brand" and "promotion" combination.
There are duplicate "promotion" by a given brand since they are created at a product level. But, the system they go into need to be "brand", "promotion", "skus".
Not really sure if I need to use VBA to do some of this inside Access. Or I can do this in two different queries.
You will need to use a bit of VBA to do this. The VBA will need to loop a recordset of data from the table that is filtered on brand and promotion and build up the sku string. Something like this perhaps:
Function fJoinData(strBrand As String, strPromotion As String) As String
On Error GoTo E_Handle
Dim db As DAO.Database
Dim rsData As DAO.Recordset
Dim strSQL As String
Set db = DBEngine(0)(0)
strSQL = "SELECT skus FROM Table1 " _
& " WHERE Brand='" & strBrand & "' " _
& " AND Promotion='" & strPromotion & "';"
Set rsData = db.OpenRecordset(strSQL)
If Not (rsData.BOF And rsData.EOF) Then
Do
fJoinData = fJoinData & ", " & rsData!skus
rsData.MoveNext
Loop Until rsData.EOF
End If
If Left(fJoinData, 2) = ", " Then fJoinData = Mid(fJoinData, 3)
fExit:
On Error Resume Next
rsData.Close
Set rsData = Nothing
Set db = Nothing
Exit Function
E_Handle:
MsgBox Err.Description & vbCrLf & vbCrLf & "fJoinData", vbOKOnly + vbCritical, "Error: " & Err.Number
Resume fExit
End Function
Rather than inserting into a table, I would suggest just creating a query which can then be exported:
SELECT DISTINCT
T.Brand,
T.Promotion,
fJoinData(T.Brand,T.Promotion) AS skus
FROM Table1 AS T
Regards,

Update a Table field with current time

Good day all,
I have a unbounded form with a subform (its data source is a table named SaleDetail).
On the Main Form there is a text box for the Sales ID also unbounded.
I have created a button with the following code:
Private Sub btnEndSale_Click()
Dim strPostTime As String
strPostTime = "UPDATE SaleDetail " & _
"SET [TIMEOUT] = Time()" & _
"WHERE SaleDetail.SID = Forms!Sales.Form.sSID"
DoCmd.SetWarnings False
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
DoCmd.Requery
End Sub
I am trying to get the current time to update the records in the SalesDetail table once the SID on the Main Form matches the SID in the SalesDetail Table but it is not working, but if I substitute Forms!Sales.Form.sSID with an existing ID (eg 9) it works. Any help will be appreciated.
SetWarnings False suppresses information, so can be an obstacle to trouble-shooting. And it can be totally avoided with a parameter query.
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strUpdate As String
strUpdate = "UPDATE SaleDetail SET [TIMEOUT] = Time() " & _
"WHERE SaleDetail.SID = which_SID;"
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strUpdate)
With qdf
.Parameters("which_SID").Value = Forms!Sales.Form.sSID.Value
.Execute dbFailOnError
End With
MsgBox db.RecordsAffected & " records updated"
Try this:
strPostTime = "UPDATE SaleDetail " & _
"SET [TIMEOUT] = Time()" & _
"WHERE SaleDetail.SID = " & Forms!Sales.Form.sSID
I think that newbieDBBuilder is not asking about SQL Server query which could use parameters. His code is:
DoCmd.RunSQL strSQL
which is MS Access command and queries Access db.

Error 3075-Run Query after multi select listbox is utilized

have a search form in Access 2010 that filters FYs and Quarters based on certain criteria and opens them in a query. One of the criteria is an unbound multi-select list box, SelectTime (Where a person selects "FY15-Q1 and FY15 Q2, for example. The data are stored in a query, z_Basis_QSReport5_Proposal Details. I keep getting an error 3075. Can someone help me with the code?
Private Sub Command56_Click()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim varItem As Variant
Dim strCriteria As String
Dim strSQL As String
Set db = CurrentDb()
Set qdf = db.QueryDefs("z_Basis_QSReport5_Proposal Details_For_Report")
For Each varItem In Me!SelectTime.ItemsSelected
strCriteria = strCriteria & ",'" & Me!SelectTime.ItemData(varItem) & "'"
Next varItem
If Len(strCriteria) = 0 Then
MsgBox "You did not select anything from the list" _
, vbExclamation, "Nothing to find!"
Exit Sub
End If
strCriteria = Right(strCriteria, Len(strCriteria) - 1)
strSQL = "SELECT * FROM z_Basis_QSReport5_Proposal Details " & _
"WHERE z_Basis_QSReport5_Proposal Details.CriteriaFY IN(" & strCriteria & ");"
qdf.SQL = strSQL
DoCmd.OpenQuery "z_Basis_QSReport5_Proposal Details_For_Report"
Set db = Nothing
Set qdf = Nothing
End Sub
I agree with #LiamH that you need to surround your query names with square brackets.
Also it looks like you're trying to change the SQL of a query on the fly - and then call the query before you've saved the changes
qdf.SQL = strSQL
**qdf.close**
DoCmd.OpenQuery "z_Basis_QSReport5_Proposal Details_For_Report"
That being said I think you should be looking at parameter queries or just opening the SQL directly.
When creating query, table, and field names; it is best practice to avoid spaces. However, there is a solution.
When you use SQL and you have a table name with spaces you need to encapsulate it in square brackets. like so:
"SELECT * FROM [z_Basis_QSReport5_Proposal Details] & _
"WHERE [z_Basis_QSReport5_Proposal Details].CriteriaFY .....
EDIT
Before, I mentioned that you should maybe put square brackets around the query name, but if you look at the example here you will see that spaces are acceptable in this instance.
If we go back to your query, strcriteria is a string and therefore you need to put single quotes around it:
strSQL = "SELECT * FROM [z_Basis_QSReport5_Proposal Details] " & _
"WHERE [z_Basis_QSReport5_Proposal Details].CriteriaFY IN('" & strCriteria & "');"
Also, you will need to close your query before you can run it. So qdf.close is required before the docmd.openquery().

Access VBA query to SQL Server

Hello experts I'm having trouble in my update query from SQL Server. Running first a select query then pass the result to currentdb.execute (to update the table of the access file currently using), using Access vba I'm not doing it right. I really hope you could help me. Maybe you guys know much better way to run my procedure:
connect to sql server 2008, run select query.
pass the result of select query to an access database execute command (or if you have a better idea) to update a table in the current access file that is using.
The error I'm getting to the code is Type mismatch and highlighting .OpenSchema.
These is part of the code that I made wrong (and I really have no idea how to do this).
dbObj.Execute ("UPDATE ACCESS.tbl_Name RIGHT JOIN " & _
conn.OpenSchema(adSchemaTables, Array(Empty, Empty, Empty, "SQLSVR.tbl_Name")) & _
" ON ACCESS.tbl_Name.FieldName_access = " & rst!FieldName_sqlsvr & _
" SET ACCESS.tbl_Name.FieldName_access = " & rst!FieldName_sqlsvr)
These is the whole code.
Option Compare Database
Sub LocalSQLServerConn_Test()
Dim dbOjb As DAO.Database
Dim strDBName As String
Dim strUserName As String
Dim strPassword As String
Set dbObj = CurrentDb()
Set conn = New adodb.Connection
Set rst = New adodb.Recordset
strDBName = "DataSet"
strConnectString = "Provider = SQLOLEDB.1; Integrated Security = SSPI; " & _
"Initial Catalog = " & strDBName & "; Persist Security Info = True; " & _
"Workstation ID = ABCDE12345;"
conn.ConnectionString = strConnectString
conn.Open
strSQL = "SELECT DISTINCT SQLSVR.tbl_Name.FieldName_sqlsvr FROM SQLSVR.tbl_Name"
rst.Open Source:=strSQL, ActiveConnection:=conn, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic
If rst.RecordCount = 0 Then
MsgBox "No records returned"
Else
rst.MoveFirst
Do While Not rst.EOF
dbObj.Execute ("UPDATE ACCESS.tbl_Name RIGHT JOIN " & _
conn.OpenSchema(adSchemaTables, Array(Empty, Empty, Empty, "SQLSVR.tbl_Name")) & _
" ON ACCESS.tbl_Name.FieldName_access = " & rst!FieldName_sqlsvr & _
" SET ACCESS.tbl_Name.FieldName_access = " & rst!FieldName_sqlsvr)
rst.MoveNext
Loop
End If
conn.Close
rst.Close
Set dbObj = Nothing
End Sub
You should add a linked table (or a pass-through query) to get the data from SQL Server, create an Update Query in your MDB, using a JOIN to update all rows at once (your can use the query designer for this part) and then execute that query using CurrentDb.Execute.

Updating Access Database from Excel Worksheet Data

I extract data from my Access database into an Excel worksheet using a macro. I first open a connection to the database, define my sql statement in a string var and then dump that data in a recordset:
Dim db As Database
Dim rs As RecordSet
Dim sql As String
Dim dbLocation As String
dbLocation = ThisWorkbook.Path & "\database\data.accdb"
Set db = OpenDatabase(dbLocation)
sql = "Select * FROM [Master Table]"
Set rs = db.OpenRecordSet(sql, dbOpenSnapshot)
If Not rs.EOF Then
Worksheets("Sheet1").Range("A1").CopyFromRecordset rs
End If
rs.Close
Set rs = Nothing
db.Close
Set db = Nothing
This works perfectly. I distribute this to some people and ask them to update fields. I then need to update the Access data with data that is passed back. The simple thing in terms of design is that the extracted excel data mirrors the access db in structure so the update query should be simple. Also there is a primary key, so I would just need to map on that field.
Any ideas how this can be done? Can I load the whole excel datasheet into a recordset and run some snazzy update query?
You need to loop over rows on sheet 1, and for each row make sql string that looks like:
"update [Master table] set
TableField1 = " & Range(Row, Col1).Value & ","
TableField2 = " & Range(Row, Col2).Value & ","
...
where IDTableField = " & Range(Row, IDColNum).Value
and then do
db.Execute thatString
PS: There are may be mistakes in my syntax. And you need to convert cell values to strings when making string.
An extension of shibormot's solution using DAO:
Set objConnection = CreateObject("DAO.DBEngine.36")
Set db = objConnection.OpenDatabase(strDBPath, blnExclusive, blnReadOnly, strPassword)
For Each row In Range("A1:C3").Cells
strSQL = "UPDATE table SET "
strSQL = strSQL & "Field1 = " & Chr(34) & row.Cells(1) & Chr(34) & ","
strSQL = strSQL & "Field2 = " & Chr(34) & row.Cells(2) & Chr(34) & ","
strSQL = strSQL & "Field3 = " & Chr(34) & row.Cells(3) & Chr(34)
Db.Execute
Next
Threw in the chr(34) for string data