How do I create links to my tables in a password protected back end? - vba

I created an install for my database. However it loses the password for the linked tables to the back end.
I need to relink all the tables on load.
I found the below code to add specified table but I need to link all the tables in the back end DB and I don't want to repeat this code for every table.
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim strConnect As String
Dim strDbFile As String
Dim strLinkName As String
Dim strPassword As String
Dim strSourceTableName As String
strDbFile = "c:documents\mydb"
strPassword = "mypw"
strSourceTableName = "tblcaseid"
strLinkName = "link_to_caseid"
strConnect = "MS Access;PWD=" & strPassword & _
";DATABASE=" & strDbFile
Debug.Print strConnect
Set db = CurrentDb
Set tdf = db.CreateTableDef
tdf.Connect = strConnect
tdf.SourceTableName = strSourceTableName
tdf.Name = strLinkName
db.TableDefs.Append tdf
End Sub

Figured out that i dont need to remove the table links and add them again just need to loop through the tables refreshing the link including the password in the strconnect
Sub relink()
Dim strDbFile As String
Dim strPassword As String
Dim strConnect As String
strDbFile = "file location"
strPassword = "database password"
strConnect = "MS Access;PWD=" & strPassword & ";DATABASE=" & strDbFile
Dim tdf As DAO.TableDef
Dim db As DAO.Database
Set db = CurrentDb
For Each tdf In db.TableDefs
' ignore system and temp tables
If Not (tdf.Name Like "MSys*" Or tdf.Name Like "~*" Or tdf.Name Like "exl*") Then
tdf.Connect = strConnect
tdf.RefreshLink
End If
Next
End Sub
this worked

Related

Insert table records from Local MS Access Database to Oracle table

I am trying to Insert records from a local Access database to an Oracle table. Same fields in both tables.
I don't want to loop through the lines if I don't have to. I have to code to connect to the oracle database. Just not sure of the code to select the local Access table called "RET_PARTS" and insert that data to the Oracle table called RET2_PARTS_ORACLE"
Sub subFastUpload()
`enter code here`On Error GoTo Err_subFastUpload
`enter code here`Dim intlength As Integer
`enter code here`intlength = 8
`enter code here`Dim strServer As String
strServer = "MARS"
Const maxItems = 500
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim objRst As New ADODB.Recordset
Dim objCon As New ADODB.Connection
Dim objCmd As New ADODB.Command
Dim strTable As String
Dim intCount As Integer
Set dbs = CurrentDb()
Set rst = dbs.OpenRecordset("Ret2_Parts")
Dim mars_pass As String
'mars_pass = InputBox("Enter MaRS Password")
mars_pass = "XXXXXXX"
intCount = 1
If strServer = "MARS" Then
strTable = Environ("UserName") & ".RET2_PARTS_ORACLE"
objCon.ConnectionString = "Provider=OraOLEDB.Oracle;Data Source=MARSNEW.123;User ID=" & Environ("UserName") & ";Password=" & mars_pass & ";"
strTable = Environ("UserName") & ".RET2_PARTS_ORACLE"
End If
objCon.Open
objCmd.ActiveConnection = objCon
objCmd.CommandType = adCmdText
objCmd.Properties("PLSQLRSet") = False
While Not rst.EOF
If intCount = 1 Then
strSQL = "Select * from RET2_Parts"
Debug.Print strSQL

Inherited MS Access Database, Tracking Sources of Queries

I have just inherited a database at my new company. Old DB owner left no good documentation and queries very hard to keep track of. Looking for programmatic answer to track sources of fields in every query (what table it come from). Prefer something can be exported to Excel to study, Access visualization is no good. Am familiar with VBA.
This is pretty messy but could save you time collecting each query's SQL code. The following code exports all SQL stored in the QueryDefs collection into a text file. I have it splitting the code with a space delimiter, but a comma might be preferable. The data will not be normalized, I don't have the time to go to that level of complexity. Just make sure to update strPath before you execute. Hopefully this helps.
Sub PullQuerySQL()
Dim dbs As Database
Dim i As Integer
Dim fso As Object
Dim oFile As Object
Dim varParse() As String
Dim element As Variant
Dim strPath As String
strPath = ".txt"
Set dbs = CurrentDb()
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.CreateTextFile(strPath)
For i = 0 To dbs.QueryDefs.Count - 1
oFile.WriteLine dbs.QueryDefs(i).Name
varParse = Split(dbs.QueryDefs(i).SQL, " ")
For Each element In varParse
oFile.WriteLine element
Next element
Next i
oFile.Close
Set oFile = Nothing
Set fso = Nothing
Set dbs = Nothing
End Sub
I have been through this with many inherited databases. I find it extremely helpful to create an Access table with the fields and the tables/queries that they come from. Try this code below. It will prompt you for the name of the query that you are looking to "map" as I call it. It will then create a new table named "queryName Definitions".
Option Compare Database
Public Sub MapQuery()
Dim strQueryName As String
Dim rst As DAO.Recordset
Dim fld As Field
Dim strSource As String
Dim strField As String
Dim strValue As String
Dim strSQL1 As String
Dim strSQL2 As String
Dim booExists As Boolean
strQueryName = InputBox("Please enter the name of the query that you are looking to map")
Set rst = CurrentDb.OpenRecordset(strQueryName)
On Error GoTo error1
booExists = IsObject(CurrentDb.TableDefs(strQueryName & " Definitions"))
DoCmd.DeleteObject acTable, strQueryName & " Definitions"
continue:
strSQL1 = "CREATE TABLE [" & strQueryName & " Definitions]" & " (FieldName CHAR, SourceName CHAR);"
DoCmd.RunSQL (strSQL1)
DoCmd.SetWarnings False
For Each fld In rst.Fields
strField = fld.Name
strSource = fld.SourceTable
Debug.Print strValue
strSQL2 = "INSERT INTO [" & strQueryName & " Definitions]" & "(FieldName, SourceName) VALUES(""" & strField & """, """ & strSource & """);"
DoCmd.RunSQL (strSQL2)
Next fld
error1:
If Err.Number = 3265 Then
Resume continue
Else
MsgBox Err.Description
End If
DoCmd.SetWarnings True
Exit Sub
DoCmd.SetWarnings True
End Sub

Access SQL Enter Parameter Value when trying to export to excel

I Am trying to run this SQL statement and then export the result to an excel spread sheet. I've looked through the the internet and found this, which seemed to work for other users.
It runs but asks me to "Enter Parameter Value" linking to "selecteduser" on line 4 of the code, the message box shows up at the point where the code starts here: DoCmd.TransferSpreadsheet. If I click ok the excel sheet is created but with nothing in except the titles from the selected columns from the tables in the database. If i put valid data into the text box and press ok, then the excel spreadsheet is created with the correct data showing.
I know that the selected data in the ComboBox is been stored, because if I do a Message box it shows the selected data from the combobox.
Any ideas anyone? It's obvious the data isn't been passed through somewhere, but I can't see where.
Private Sub Command12_Click()
Dim strSQL As String
Dim strQry As String
Dim selecteduser As String
Dim db As DAO.Database
Dim Qdf As QueryDef
selecteduser = Me.Combo6.Column(0)
strSQL = "SELECT tblPra.praNo, tblFolder.folder, tblFolder.fullTitle FROM tblPra INNER JOIN (tblFolder INNER JOIN tblRelationship ON tblFolder.folderID = tblRelationship.folderID) ON tblPra.praID = tblRelationship.praID WHERE (((tblPra.praNo)=selecteduser));"
strQry = "tempuser"
Set db = CurrentDb
Set Qdf = db.CreateQueryDef(strQry, strSQL)
On Error Resume Next
DoCmd.DeleteObject acQuery, "strQry"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, _
strQry, "C:\Users\prc93\Desktop\test.xls", True
DoCmd.DeleteObject acQuery, strQry
End Sub
the selecteduser in your query needs to be outside of the quotes. as it is a string it needs to be in single quotes like 'selecteduser'. Now if you msgbox your query and you should see that the selecteduser equals your column (0). are you sure that selecteduser needs to be a string and not a number e.g. long?
Private Sub Command12_Click()
Dim strSQL As String
Dim strQry As String
Dim selecteduser As String
Dim db As DAO.Database
Dim Qdf As QueryDef
selecteduser = Me.Combo6.Column(0)
strSQL = "SELECT tblPra.praNo, tblFolder.folder, tblFolder.fullTitle FROM " &_
"tblPra INNER JOIN (tblFolder INNER JOIN tblRelationship ON " &_
"tblFolder.folderID = tblRelationship.folderID) ON " &_
"tblPra.praID = tblRelationship.praID " &_
"WHERE (((tblPra.praNo)='" & selecteduser & "'));"
strQry = "tempuser"
Set db = CurrentDb
Set Qdf = db.CreateQueryDef(strQry, strSQL)
On Error Resume Next
DoCmd.DeleteObject acQuery, "strQry"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, _
strQry, "C:\Users\prc93\Desktop\test.xls", True
DoCmd.DeleteObject acQuery, strQry
End Sub

Transfer memo from Excel 2010 to Access 2010 using VBA and DAO

I'm trying to transfer a text from Excel 2010 to Access 2010. Due to the limitation of 256 characters for normal text I want to use memo. Now, after hours of searching I still have no solution to my problem.
To be more specific:
This code reads the data (in this case text) and writes it into an Access data base. Due to the limitation for text I need to use Memo fields in the Access data base but after adjusting everything I couldn't find the data type for this statement (sSQL).
What I want to do is to change the following code: (reduced slightly to the relevant bits)
Dim ws As DAO.Workspace
Dim db As DAO.Database
Dim sDb As String
Dim sSQL As String
Dim qdf As QueryDef
sDb = ActiveWorkbook.Path & "\DataBase.accdb"
Set ws = DBEngine.Workspaces(0)
Set db = ws.OpenDatabase(sDb)
sSQL = "Parameters" _
& " SomeText Text; " _ <<== Here << ==
& "INSERT INTO IT_Ticker (SomeText)" _
& " Values ([ SomeText ])"
Set qdf = db.CreateQueryDef("", sSQL)
qdf.Parameters!SomeText = Worksheets("SomeSheet").Range("A1")
qdf.Execute dbFailOnError
Debug.Print qdf.RecordsAffected
qdf.Close
db.Close
ws.Close
Set qdf = Nothing
Set db = Nothing
Set ws = Nothing
I was thinking about replacing "Text" with "Memo" but it wasn't working. I also tried "LongText" and "String".
I'm assuming that the table into which you are appending data IT_Ticker already exists. You were not specific about the Parameters you're using, but the code below works just fine.
Option Explicit
Sub test()
Dim ws As DAO.Workspace
Dim db As DAO.Database
Dim sDb As String
Dim sSQL As String
Dim qdf As QueryDef
Dim userName As String
Dim longText As String
sDb = ActiveWorkbook.Path & "\DataBase2.accdb"
Set ws = DBEngine.Workspaces(0)
Set db = ws.OpenDatabase(sDb)
'sSQL = "Parameters" _
'& " SomeText Text; " _ <<== Here << ==
'& "INSERT INTO IT_Ticker (SomeText)" _
'& " Values ([ SomeText ])"
userName = Cells(2, 2).Value
longText = Cells(3, 2).Value
sSQL = "INSERT INTO IT_Ticker (UserName, ReallyLongText) Values (""" & _
userName & """,""" & longText & """)"
Set qdf = db.CreateQueryDef("", sSQL)
'qdf.Parameters!SomeText = Worksheets("SomeSheet").Range("A1")
qdf.Execute dbFailOnError
Debug.Print qdf.RecordsAffected
qdf.Close
db.Close
ws.Close
Set qdf = Nothing
Set db = Nothing
Set ws = Nothing
End Sub

DSN-Less Connection with multiple tables

Right now I have an MS SQL database with about 50 or so tables in it with which I'd like to link to MS Access using a DSN Less connection. Below is the basic code where I have a parameter of stRemoteTableName which is the table name of the SQL table to import. I could call this function each time for each table but that would take forever; is there anyway to loop through all tables in an SQL database and pass them to this function so that all tables are imported? I'm having a very hard time finding any code online for something like this, so help is much appreciated.
Private Sub ImportAllTables(stRemoteTableName)
On Error GoTo AttachDSNLessTable_Err
Dim td As TableDef
Dim stConnect As String
stServer = "C:\Location"
stDatabase = "DB"
stLocalTableName = stRemoteTableName
stUsername = ""
For Each td In CurrentDb.TableDefs
If td.Name = stLocalTableName Then
CurrentDb.TableDefs.Delete stLocalTableName
End If
Next
stConnect = "ODBC;DRIVER=SQL Server;SERVER=" & stServer & ";DATABASE=" & stDatabase & ";Trusted_Connection=Yes"
Set td = CurrentDb.CreateTableDef(stLocalTableName, stRemoteTableName, stConnect)
CurrentDb.TableDefs.Append td
Exit Sub
AttachDSNLessTable_Err:
AttachDSNLessTable = False
MsgBox "AttachDSNLessTable encountered an unexpected error: " & Err.Description
End Sub
You can use a pass-through query to list the table names from your SQL Server database. Open a recordset based on that query. Then loop through the recordset rows and link each table.
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strConnect As String
Dim strSelect As String
strSelect = "SELECT t.name FROM sys.tables t;"
'strConnect = <you already have this as stConnect>
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strSelect)
qdf.Connect = strConnect
Set rs = qdf.OpenRecordset
With rs
Do While Not .EOF
' you want to link; I will just list
' the table names
Debug.Print !name
.MoveNext
Loop
.Close
End With
Set rs = Nothing
Set qdf = Nothing
Set db = Nothing