I need to import tables from various databases on a monthly basis. Once the tables are imported, the databases are archived and not looked at again.
I have the following VBA code which works fine when a DB is not password protected:
Private Sub ImportTheData(ByVal dbImport As String)
DoCmd.SetWarnings False 'Turn OFF display alerts
'Import the full activity & comments table from the Import DB to a temporary table
DoCmd.TransferDatabase acImport, "Microsoft Access", dbImport, acTable, "tbl_Activity", "tbl_TempActivity", True
DoCmd.TransferDatabase acImport, "Microsoft Access", dbImport, acTable, "tbl_Comments", "tbl_TempComments", True
'code continues ...
The last parameter (storelogin) is set to true, but there seems to be no way to programmatically set those login parameters (password).
When I run the code, the user is prompted to enter the password (despite the SetWarnings = False). As I'm importing dozens of files each time this is not a viable solution.
Is there a way to programatically import tables using DoCmd.TransferDatabase when a file is password protected and if so how?
Open the database with DAO, supplying the password, then you can import the tables.
Public Sub ImportEncr()
Const dbImport = "D:\DbEncr.accdb"
Const sPassword = "foobar"
Dim DB As DAO.Database
Set DB = DBEngine.OpenDatabase(Name:=dbImport, Options:=False, ReadOnly:=False, Connect:=";PWD=" & sPassword)
DoCmd.TransferDatabase acImport, "Microsoft Access", dbImport, acTable, "tblEncr", "tblEncr", False
DB.Close
Set DB = Nothing
End Sub
StoreLogin applies to linking tables from ODBC databases.
You can use SQL and build a SQL statement and .RunSQL that I believe.
An example SQL would be
SELECT * into tblIMPORT
FROM xyz IN '' '; database=C:\Workspace\Database1.accdb;PWD=test';
Hope this helps.
Related
I have an Access data file that contains tables.
that access file linked with other access files (the executive file that contains the forms and the operations).
I added the following code inside the tables file inside a module:
Public Function MyFun()
On Error Resume Next
Dim xCounter As Integer
xCounter = DLookup("xcounter", "tblfs1", "[xid] = 1")
xCounter = xCounter + 1
Dim xSql As String
xSql = "update tblfs1 set [xcounter] = " & xCounter & " where [xid] = 1"
CurrentDb.Execute xSql
If xCounter >= 300 Then
DoCmd.Rename "Tbl_FS", acTable, "FS"
DoCmd.Rename "Tbl_All", acTable, "All"
DoCmd.Rename "Tbl_Customers", acTable, "Customers"
DoCmd.Rename "Tbl_Rates", acTable, "Rates"
DoCmd.Rename "Tbl_Temp", acTable, "Temp"
DoCmd.Rename "Tbl_Users", acTable, "Users"
End If
End Function
and I created a macro to run that function in a startup (RunCode) and I named the macro (AutoExec).
my problem is when I open (the access tables file) by clicking, the code works but when I use the executive file that linked with (the access tables file), the code doesn't work!!
how to make the code run when I work on the executive file without open (the access tables file) and without doing that from the executive file.
That is not possible - the backend (data) file is "dead" in this regard.
The closest you can get some action in the backend, is to create data macros.
I'm trying to automate exporting of query results from Access 2010 to Excel 2010. It is not easy because Access is using linked tables (SQL Server 2008 R2). I know that is can be done manually but I would really like to automate this process.
When I tried to step though the following VBA code located in Access, I get to this line and then it just running and running and never gets past this point
Set wbTarget = XL.Workbooks.Open("H:\TATData\Test.xlsx")
(no error messages)
I've tested the query before I copied it into the VBA Editor, so I know the query works and it's very fast, but not with automation. I also set up MS Excel library in Access that is needed.
Please help to figure out what needs to be done to get this to work.
I had to kill Access to get it to stop running.
Here is my code:
Public Sub ExportToExcel()
'Step 1: Declare your variables
Dim XL As Excel.Application
Dim excelApp As Object
Dim wbTarget As Workbook
Dim sht As Worksheet
Dim qdfTestData As QueryDef
Dim rsTestData As Recordset
Dim strSQL As String
Dim i As Integer
strSQL = "SELECT dbo_Patient.firstnm, dbo_Patient.lastnm, dbo_Sample.SampleDt, dbo_Test.TestTypeCd "
strSQL = strSQL & "FROM (dbo_Patient INNER JOIN dbo_Sample ON dbo_Patient.PatientId = dbo_Sample.PatientId) INNER JOIN dbo_Test ON dbo_Sample.SampleID = dbo_Test.SampleId "
strSQL = strSQL & "WHERE (((dbo_Test.TestTypeCd)='FL_XM_ALLO'));"
'set up reference to the query to export
CurrentDb.QueryDefs.Delete ("qrTest")
'set up reference to the query to export
Set qdfTestData = CurrentDb.CreateQueryDef("qrTest", strSQL)
'Execute the query
Set rsTestData = qdfTestData.OpenRecordset()
'Create a new Excel instance.
Set excelApp = CreateObject("Excel.Application")
'Set reference to the export workbook
'Set wbTarget = XL.Workbooks.Open("H:\TATData\Test.xlsx")
Set wbTarget = excelApp.Workbooks.Add
Set sht = wbTarget.Worksheets("Sheet1")
'clear excel sheet
On Error GoTo 0
excelApp.Visible = True
On Error GoTo Errorhandler
wbTarget.Worksheets("Sheet1").Cells.ClearContents
'Use paste from recordset to put in excel sheet
wbTarget.Worksheets("Sheet1").Cells(2, 1).CopyFromRecordset rsTestData
'clear excel sheet
Errorhandler:
DoCmd.SetWarnings True
MsgBox Err.Description, vbExclamation, Err.Number
Exit Sub
'wbTarget.Save
End Sub
You're doing this in a more difficult way than necessary. To directly export your query qrTest, use
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "qrTest", _
"H:\TATData\Test.xlsx", True
(this will create an unformatted sheet)
or
DoCmd.OutputTo acOutputQuery, "qrTest", acFormatXLSX, "H:\TATData\Test.xlsx", False
(this will create a formatted sheet)
Side note: If
Set wbTarget = XL.Workbooks.Open("H:\TATData\Test.xlsx")
doesn't work, this cannot be caused by your query or anything in Access. Does this file itself have any ODBC connections?
I have an Access 2003 database with linked tables to a SQL Server 2005 database. The user information (the password) that is used to create an ODBC connection between Access and SQL Server was recently updated.
When I open the Access database, and try to edit the Linked table information I am then able to open the tables and see my data. However, when I close Access and and reopen the Access database it appears the password informtion has revereted back and I get an ODBC connection error.
Anyone know what I am doing incorrectly?
As a follow up, it appears we have about a dozen Access databases with numerous linked tables that all need this update. Is this the best way to update this information? The linked tables seem to have been created using different machines as the Workstation-ID specified in the ODBC connection is different.
Write a routine, that update the Connect Property from the TableDef and save the change with RefreshLink.
The problem with Linked Table Manager (LTM), is when you have linked tables that are in fact links to SQL Views. In that case, LTM will relink the "tables" without reassigning them the proper PK, and they will become non updatable.
I have written some code that I used to start from VBE, it is a quick and dirty thing, but you could surely adapt that if you need it.
There are 2 subs, one for the tables, and one for the passthru queries.
Option Compare Database
option explicit
Const kOld = "remote.g" 'string to identify old server
'new server odbc string
Const kConnLux = "ODBC;DRIVER=SQL Server Native Client 10.0;SERVER=xxxx;UID=yyyy;PWD=zzzz;"
Sub UpdateTables()
Dim db As Database, td As TableDef
Dim hasIndex As Boolean, strSql As String
Set db = CurrentDb
For Each td In db.TableDefs
If InStr(1, td.Connect, kOld) > 0 Then 'lien vers CE serveur ?
If td.Name Like "dbo_vw*" And td.Indexes.count = 1 Then 'table = vue attachee --> pbl de clef primaire
strSql = "CREATE INDEX " & td.Indexes(0).Name & " ON [" & td.Name & "](" & td.Indexes(0).Fields & ")"
' convert field list from (+fld1;+fld2) to (fld1,fld2)
strSql = Replace(strSql, "+", "")
strSql = Replace(strSql, ";", ",")
hasIndex = True
Else
hasIndex = False
End If
td.Connect = kConnLux
td.RefreshLink
Debug.Print td.Name
If hasIndex And td.Indexes.count = 0 Then
' if index now removed then re-create it
CurrentDb.Execute strSql
End If
End If
Next td
Debug.Print "Done"
End Sub
Sub UpdateQueries()
Dim db As Database
Dim td As QueryDef
Set db = CurrentDb
For Each td In db.QueryDefs
If InStr(1, td.Connect, kOld) > 0 Then
td.Connect = kConnLux
Debug.Print td.Name, td.Connect
End If
Next td
End Sub
I have an Access 2002 application which links an Oracle table via ODBC with this code:
Set HRSWsp = CreateWorkspace("CONNODBC", "", "", dbUseODBC)
Set HRSConn = HRSWsp.OpenConnection("HRSCONN", dbDriverPrompt, , "ODBC;")
DoCmd.TransferDatabase acLink, "Database ODBC", HRSConn.Connect, acTable, "SCHEMA.TABLE", "TABLE", False, True
Unfortunately, Access 2007 doesn't accept this syntax anymore, saying that ODBCDirect is no more supported (Runtime error 3847) and suggesting to use ADO instead of DAO.
Could someone please tell me how can I modify this code to satisfy Access 2007?
I found that I could solve my problem in a very simple way, by deleting the first two statements and modifying the third this way:
DoCmd.TransferDatabase acLink, "ODBC Database", "ODBC;DRIVER=Microsoft ODBC for Oracle;SERVER=myserver;UID=myuser;PWD=mypassword", acTable, "SCHEMA.TABLE", "TABLE", False, True
This way the table would be linked without prompting for anything. If I leave the connect string a simple "ODBC", instead, Access will ask to specify the odbc connection and the other missing parameters, thus obtaining the same thing I tried to perform with the previous statements.
Try this:
Dim tbl As New ADOX.Table
Dim cat As New ADOX.Catalog
cat.ActiveConnection = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=[x:\your_access_db.mdb];Jet OLEDB:Engine Type=4"
tbl.NAME = "[Access_table_name]"
Set tbl.ParentCatalog = cat
tbl.Properties("Jet OLEDB:Create Link") = True
tbl.Properties("Jet OLEDB:Link Provider String") = "ODBC;Driver={Microsoft ODBC For Oracle};Server=OracleServerName;Uid=[user];Pwd=[password];"
tbl.Properties("Jet OLEDB:Cache Link Name/Password") = True
tbl.Properties("Jet OLEDB:Remote Table Name") = "[Oracle_Schema].[Table]"
cat.Tables.Append tbl
cat.ActiveConnection.Close
Replace text in brackets ([]) with your info.
i want to create a number of databases in ms-access using a code or any option of ms-access, but i want delete databases also.
Please help me
You could have an empty database named "db1.mdb", and then add this code inside a module in another Access database:
Set fso = CreateObject("scripting.filesystemobject")
fso.CopyFile "c:\db.mdb", "c:\db_copy1.mdb", True
fso.CopyFile "c:\db.mdb", "c:\db_copy2.mdb", True
fso.CopyFile "c:\db.mdb", "c:\db_copy3.mdb", True
fso.DeleteFile "c:\db.mdb"
To create an Access database from Access interface:
createDatabase "myNewMDB.mdb", dbLangGeneral
To delete a database:
kill "myNewMDB.mdb"
It works without initial mdb file or extra dlls
for multiple databases
public Function createDeleteDatabase(howManyDatabases as integer) as boolean
''output is by default False
createDeleteDatabase = False
on error goto createDeleteDatabase_Error
Dim i as integer
For i = 1 to howManyDatabases
createDatabase "myMDBNumber_" & str(i,0) & ".mdb", dbLangGeneral
Next i
For i = 1 to howManyDatabases
kill "myMDBNumber_" & str(i,0) & ".mdb"
Next i
''if no errors in the fonction, set the output to True
createDeleteDatabase = True
Exit function
createDeleteDatabase_Error:
'' your error treatment
End function