Copy MS Access table to different MS Access - vb.net

Please help; I wanted to copy an MS Access table and its data into another table at different MS Access database. I came across hundreds of access databases which has to be reformatted, I decided to write VB.Net code and format one table so that it can be copy to other hundreds instant of formatting one by one.
Here is my trial code:
Dim cmdCreate as New OleDb.OleDbCommand("SELECT * INTO [Hierarchy] IN "c:\hierarchy.pdb" FROM [Hierarchy] WHERE 0=1", con1)
cmdCreate.ExecuteNonQuery
Note: con1 datasource is deference with table2 directory.

here is a function in Access you can put a loop around with appropriate args. The dbSource and dbTarget are the full path names.
Public Function ExportTableToDatabase (TableName As String, dbSource As String, dbTarget As String, Optional Append As Boolean = False) As Boolean
On Error GoTo Error_Trap
Dim SQL As String
Dim db As DAO.Database
Set db = CurrentDb()
If Append Then
'The sql will use APPEND TO TABLE syntax
SQL = "INSERT INTO " & TableName & " IN """ & dbTarget & """ " _
& "SELECT " & TableName & ".* FROM " & TableName & " IN """ & dbSource & """ "
Else
'The sql will use CREATE TABLE syntax
SQL = "SELECT " _
& TableName & ".* INTO " & TableName & " " _
& "IN """ & dbTarget & """ " _
& "FROM " & TableName & " " _
& "IN """ & dbSource & """ "
End If
db.Execute SQL, dbFailOnError + dbSeeChanges
ExportTableToDatabase = True
Cleanup:
set db = nothing
Exit Function
Error_Trap:
msgbox Err.Number, Err.Description
Resume Cleanup
Resume
End Function

Related

Error 424 object required after NULL SQL query

I am running some EXCEL VBA code to update the contents of an ACCESS database table along the lines suggested here:
IF ##Rowcount = 0 -- SQL Syntax Error in Access
. When I execute the SELECT query, EXCEL VBA gives this error message:
Run-time error 424: Object required
I extracted the SQL string from the VBA Watch window and ran it as a Query in ACCESS. The first time I did this, there were no records becasue the table was empty, so I ran the INSERT query in ACCESS and then tried running the VBA code but got the same error message.
The code is here:
Public db As DAO.Database
' Open database
Public Sub OpenMdtDatabase()
Set db = DBEngine(0).OpenDatabase("SL_MDT_data_v1.accdb")
End Sub
' Update DB table
Sub UpdateDb()
' Initialise
Dim rs As DAO.Recordset
Set xlSht = Sheets("plot_data")
' Open database
Call OpenMdtDatabase
' Get the data to store
sname = xlSht.Cells(6, "R").Value
xfill = xlSht.Cells(6, "S").Value
xedge = xlSht.Cells(6, "T").Value
xstyl = xlSht.Cells(6, "U").Value
xsize = xlSht.Cells(6, "V").Value
' SQL stuff
sqlTxtSelect = "SELECT SeriesName FROM SeriesProperties WHERE SeriesName ='" & sname & "';"
sqlTxtUpdate = "UPDATE SeriesProperties " & _
sqlTxtUpdate = "SET SeriesFill = " & xfill & ", " & _
sqlTxtUpdate = "SeriesEdge = " & xedge & ", " & _
sqlTxtUpdate = "SeriesStyle = " & xstyl & ", " & _
sqlTxtUpdate = "SeriesSize = " & xsize & " " & _
sqlTxtUpdate = "WHERE SeriesName = '" & sname & "';"
sqlTxtInsert = "INSERT INTO SeriesProperties('" & sname & "') " & _
sqlTxtInsert = "VALUES(" & xfill & ", " & xedge & ", " & xstyl & ", " & xsize & ");"
Set rs = db.OpenRecordset(sqlTxtSelect)
If rs.RecordCount = 0 Then
DoCmd.RunSQL (sqlTxtInsert)
Else
DoCmd.RunSQL (sqlTxtUpdate)
End If
End Sub
I am guessing that there is something wrong with the SQL SELECT string. I tried setting this directly using
SELECT SeriesName FROM SeriesProperties WHERE SeriesName ='14/10-2:F2F_SLMC'
but still get the same error message. I have also tried removing the colon ...
The problem lies with the statement
DoCmd.RunSQL (sqlTxtInsert)
If I change this to
db.Execute (sqlTxtInsert)
then everything is fine. Should have scrolled to the end of the answer at the original link ....

Update SQL MS Access 2010

This is wrecking my brains for 4 hours now,
I have a Table named BreakSked,
and I this button to update the table with the break end time with this sql:
strSQL1 = "UPDATE [BreakSked] SET [BreakSked].[EndTime] = " & _
Me.Text412.Value & " WHERE [BreakSked].AgentName = " & Me.List423.Value _
& " AND [BreakSked].ShiftStatus = '1'"
CurrentDB.Execute strSQL1
Text412 holds the current system time and List423 contains the name of the person.
I'm always getting this
"Run-time error 3075: Syntax Error (missing operator) in query
expression '03:00:00 am'
Any help please?
EDIT: Thanks, now my records are updating. But now its adding another record instead of updating the record at hand. I feel so silly since my program only has two buttons and I can't figure out why this is happening.
Private Sub Form_Load()
DoCmd.GoToRecord , , acNewRec
End Sub
Private Sub Command536_Click()
strSQL1 = "UPDATE BreakSked SET BreakSked.EndTime = '" & Me.Text412.Value & "',BreakSked.Duration = '" & durationz & "' " & vbCrLf & _
"WHERE (([BreakSked].[AgentID]='" & Me.List423.Value & "'));"
CurrentDb.Execute strSQL1
CurrentDb.Close
MsgBox "OK", vbOKOnly, "Added"
End Sub
Private Sub Command520_Click()
strSql = "INSERT INTO BreakSked (ShiftDate,AgentID,StartTime,Status) VALUES ('" & Me.Text373.Value & "', '" & Me.List423.Value & "', '" & Me.Text373.Value & "','" & Me.Page657.Caption & "')"
CurrentDb.Execute strSql
CurrentDb.Close
MsgBox "OK", vbOKOnly, "Added"
End Sub
You wouldn't need to delimit Date/Time and text values if you use a parameter query.
Dim strUpdate As String
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
strUpdate = "PARAMETERS pEndTime DateTime, pAgentName Text ( 255 );" & vbCrLf & _
"UPDATE BreakSked AS b SET b.EndTime = [pEndTime]" & vbCrLf & _
"WHERE b.AgentName = [pAgentName] AND b.ShiftStatus = '1';"
Debug.Print strUpdate ' <- inspect this in Immediate window ...
' Ctrl+g will take you there
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strUpdate)
qdf.Parameters("pEndTime").Value = Me.Text412.Value
qdf.Parameters("pAgentName").Value = Me.List423.Value
qdf.Execute dbFailOnError
And if you always want to put the current system time into EndTime, you can use the Time() function instead of pulling it from a text box.
'qdf.Parameters("pEndTime").Value = Me.Text412.Value
qdf.Parameters("pEndTime").Value = Time() ' or Now() if you want date and time
However, if that is the case, you could just hard-code the function name into the SQL and dispense with one parameter.
"UPDATE BreakSked AS b SET b.EndTime = Time()" & vbCrLf & _
As I said in my comment you need to wrap date fields in "#" and string fields in escaped double quotes
strSQL1 = "UPDATE [BreakSked] SET [BreakSked].[EndTime] = #" & _
Me.Text412.Value & "# WHERE [BreakSked].AgentName = """ & Me.List423.Value & _
""" AND [BreakSked].ShiftStatus = '1'"

MS.Access VBA - Error 3061: Too Few Parameters.Expected 2

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).

Counter field in MS Access, how to generate?

How can I generate counter field like this 0001A, 0002A... becouse in standart it is 0,1,2,3,4.... how to change this?
Adding to #HansUp's excellent answer, you could hide the IDENTITY column and at the same time expose the formatted column using a SQL VIEW: you could then revoke privileges on the table so that users work with the VIEW and do not 'see' the table e.g. demo:
copy+paste into any VBA module, no references nor Access UI/object model required, creates a new mdb in the temp folder e.g. use Excel:
Sub YourView2()
On Error Resume Next
Kill Environ$("temp") & "\DropMe.mdb"
On Error GoTo 0
Dim cat
Set cat = CreateObject("ADOX.Catalog")
With cat
.Create _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb"
With .ActiveConnection
Dim Sql As String
Sql = _
"CREATE TABLE YourTable ( " & _
"ID INTEGER IDENTITY(1, 1) NOT NULL UNIQUE, " & _
"data_col VARCHAR(20) NOT NULL);"
.Execute Sql
Sql = _
"CREATE VIEW YourView AS " & _
"SELECT FORMAT$(ID, '0000') & 'A' AS formatted_ID, " & vbCr & _
" data_col " & vbCr & _
" FROM YourTable;"
.Execute Sql
Sql = _
"INSERT INTO YourView (data_col) VALUES ('one');"
.Execute Sql
Sql = _
"INSERT INTO YourView (data_col) VALUES ('day');"
.Execute Sql
Sql = _
"INSERT INTO YourView (data_col) VALUES ('when');"
.Execute Sql
Sql = "SELECT * FROM YourView;"
Dim rs
Set rs = .Execute(Sql)
MsgBox rs.GetString
End With
Set .ActiveConnection = Nothing
End With
End Sub
I think this one would be even better if you include DDL GRANT/REVOKE samples to manage the privileges
Here's the updated code to do just that:
Sub YourView2()
On Error Resume Next
Kill Environ$("temp") & "\DropMe.mdb"
Kill Environ$("temp") & "\DropMeToo.mdw"
On Error GoTo 0
' Create workgroup and db
Dim cat As ADOX.Catalog
Set cat = CreateObject("ADOX.Catalog")
With cat
.Create _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Jet OLEDB:Engine Type=4;" & _
"Data Source=" & _
Environ$("temp") & "\DropMeToo.mdw;" & _
"Jet OLEDB:Create System Database=-1"
.Create _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Jet OLEDB:Engine Type=4;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb;" & _
"Jet OLEDB:System Database=" & _
Environ$("temp") & "\DropMeToo.mdw;"
' Add table with data and user with privileges
With .ActiveConnection
Dim Sql As String
Sql = _
"CREATE TABLE YourTable ( " & _
"ID INTEGER IDENTITY(1, 1) NOT NULL UNIQUE, " & _
"data_col VARCHAR(20) NOT NULL);"
.Execute Sql
Sql = _
"CREATE VIEW YourView AS " & _
"SELECT FORMAT$(ID, '0000') & 'A' AS formatted_ID, " & vbCr & _
" data_col " & vbCr & _
" FROM YourTable WITH OWNERACCESS OPTION;"
.Execute Sql
.Execute "CREATE USER onedaywhen pwd Chri5tma5;"
.Execute "GRANT ALL PRIVILEGES ON YourView TO onedaywhen;"
.Execute "REVOKE ALL PRIVILEGES ON YourTable FROM onedaywhen;"
End With
End With
' Test user can connect
Dim con As ADODB.Connection
Set con = New ADODB.Connection
With con
.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Jet OLEDB:Engine Type=4;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb;" & _
"Jet OLEDB:System Database=" & _
Environ$("temp") & "\DropMeToo.mdw;" & _
"User ID=onedaywhen;Password=pwd;"
.Open
On Error Resume Next
' Attempt to insert to table (no privileges)
Sql = _
"INSERT INTO YourTable (data_col) VALUES ('one');"
.Execute Sql
If Err.Number <> 0 Then
MsgBox _
Err.Number & ": " & _
Err.Description & _
" (" & Err.Source & ")"
End If
On Error GoTo 0
Dim rs
On Error Resume Next
' Attempt to read table (no privileges)
Sql = _
"SELECT * FROM YourTable;"
Set rs = .Execute(Sql)
If Err.Number <> 0 Then
MsgBox _
Err.Number & ": " & _
Err.Description & _
" (" & Err.Source & ")"
End If
On Error GoTo 0
' From here, work only with VIEW
Sql = _
"INSERT INTO YourView (data_col) VALUES ('one');"
.Execute Sql
Sql = _
"INSERT INTO YourView (data_col) VALUES ('day');"
.Execute Sql
Sql = _
"INSERT INTO YourView (data_col) VALUES ('when');"
.Execute Sql
Sql = "SELECT * FROM YourView;"
Set rs = .Execute(Sql)
MsgBox rs.GetString
Set con = Nothing
End With
End Sub
The simplest solution would be to use a standard autonumber field (long integer). Let Access maintain those values for you. Then anytime you need those values in your "0001A" format, use the Format() function to add the leading zeros, and concatenate an "A".
This is trivially easy. If your autonumber field is named ID, you could do that transformation with this query:
SELECT Format(ID, "0000") & "A" AS formatted_ID
FROM YourTable;
Similarly you can apply the same expression to the control source property of a text box on a form or report.
One solution, that works for forms only!
create a GetId() function that calculates your counter (using DMax generally)
Use the Before insert event in your form to set the value of the field using GetId()
Drawback: in a multiuser environment, if another User2 starts addind a record after User1, but saves it before User1 saves his, there will be a duplicate problem. You will need to use the FormError event to regenerate the ID and resume the save process.

Why do brackets in SQL around field name not work in Access VBA ADO?

In MS Access QBE if I paste the following SQL, it works correctly and I get 2 records back-
SELECT [tmp_binning].[bn_faibash] FROM [tmp_binning] WHERE key2='0210043-HOU-STOR' ORDER BY [tmp_binning].[bn_faibash];
But if I programmatically run the same query in VBA from an ADO object I get (incorrectly) no records. If I change the SQL to remove brackets around the field name, it does correctly return the 2 records in VBA ADO.
SELECT [tmp_binning].bn_faibash FROM [tmp_binning] WHERE key2='0210043-HOU-STOR' ORDER BY [tmp_binning].bn_faibash;
I've been unsuccessful googling to figure why this happens on my own, can anyone tell me why?
Thanks.
First, the brackets aren't required, either in the in Access UI or via ADO. Simply omit them in all environments and the problem should go away. (If it is the Access QBE thing that is adding the brackets then consider another tool or hand crafting your SQL code!)
Second, even with the brackets I can't reproduce the error using your SQL code e.g.
Sub gjskdjs()
On Error Resume Next
Kill Environ$("temp") & "\DropMe.mdb"
On Error GoTo 0
Dim cat
Set cat = CreateObject("ADOX.Catalog")
With cat
.Create _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb"
With .ActiveConnection
Dim Sql As String
Sql = _
"CREATE TABLE tmp_binning" & vbCr & "(" & vbCr & " bn_faibash VARCHAR(255)," & _
" " & vbCr & " key2 VARCHAR(255)" & vbCr & ");"
.Execute Sql
Sql = _
"INSERT INTO tmp_binning (bn_faibash, key2)" & _
" VALUES ('002', '0210043-HOU-STOR');"
.Execute Sql
Sql = _
"INSERT INTO tmp_binning (bn_faibash, key2)" & _
" VALUES ('001', '0210043-HOU-STOR');"
.Execute Sql
Sql = _
"SELECT [tmp_binning].bn_faibash " & vbCr & " FROM" & _
" [tmp_binning] " & vbCr & " WHERE key2 = '0210043-HOU-STOR'" & _
" " & vbCr & " ORDER " & vbCr & " BY [tmp_binning].bn_faibash;"
Dim rs
Set rs = .Execute(Sql)
MsgBox rs.GetString
End With
Set .ActiveConnection = Nothing
End With
End Sub
Consider posting your schema as SQL DDL with sample data.