I have a procedure where the ultimate objective is to update all tables on a server backend database from a laptop. Once this is complete, I want to delete the local (laptop) mdb and replace the deleted file (mdb) with the server mdb.
All seems to work well except I can't delete the local version even though I have re-linked the laptop front end to the server backend. Here is my code:
Call CloseALLFormsReports
Call RelinkTables("K:\Proposals\Northway\Data\Northway Data.accdb")
******************************************
'backup current c: database
tBackupfile = "C:\Proposals\backup\Northway DATA" & Format(Now(), "yyyymmdd hhmm") & ".accdb"
Call TransferBEData("C:\Proposals\Northway DATA.accdb", tBackupfile)
'now overwrite c:drive file
Call TransferBEData("K:\Proposals\Northway\Data\Northway Data.accdb", "C:\Proposals\Northway DATA.accdb")
Call RelinkTables("C:\Proposals\Northway DATA.accdb")
*************HERE IS THE TransferBEDate function:
Function TransferBEData(ByVal tSource As String, ByVal tDestination As String)
If FileExists(tDestination) Then
Kill tDestination
End If
FileCopy tSource, tDestination
End Function
************HERE IS MY Relinking Function
Public Sub RelinkTables(strNewPath As String)
Dim dbs As DAO.Database
Dim tdf As TableDef
Dim intCount As Integer
Dim frmCurrentForm As Form
Dim relink As Boolean
DoCmd.Hourglass True
On Error GoTo ErrLinkUpExit
'Me.lblMsg.Visible = True
'Me.cmdOK.Enabled = False
Set dbs = CurrentDb
For intCount = 0 To dbs.TableDefs.Count - 1
Set tdf = dbs.TableDefs(intCount)
If tdf.Connect <> "" Then
'Me.lblMsg.Caption = "Refreshing " & tdf.Name
DoEvents
tdf.Connect = ";DATABASE=" & strNewPath
tdf.RefreshLink
End If ' tdf.Connect <> ""
Next intCount
Set dbs = Nothing
Set tdf = Nothing
DoCmd.Hourglass False
MsgBox ("The file: " & strNewPath & " was successfully linked.")
'Me.lblMsg.Caption = "All Links were refreshed!"
relink = True
'Me.cmdOK.Enabled = True
Exit Sub
ErrLinkUpExit:
DoCmd.Hourglass False
Select Case Err
Case 3031 ' Password Protected
MsgBox "Back End '" & strNewPath & "'" & " is password protected"
Case 3011 ' Table missing
DoCmd.Hourglass False
MsgBox "Back End does not contain required table '" & _
tdf.SourceTableName & "'"
Case 3024 ' Back End not found
MsgBox "Back End Database '" & strNewPath & "'" & " " & _
"Not Found"
Case 3051 ' Access Denied
MsgBox "Access to '" & strNewPath & "' Denied " & _
vbCrLf & _
" May be Network Security or Read Only Database"
Case 3027 ' Read Only
MsgBox "Back End '" & strNewPath & "'" & " is Read " & _
"Only "
Case 3044 ' Invalid Path
MsgBox strNewPath & " Is Not a Valid Path"
Case 3265
MsgBox "Table '" & tdf.Name & "'" & _
" Not Found in ' " & strNewPath & "'"
Case 3321 ' Nothing Entered
MsgBox "No Database Name Entered"
Case Else
MsgBox "Uncaptured Error " & Str(Err) & " " & _
Err.Description
End Select
Set tdf = Nothing
relink = False
'******************Get rid of blank records
DoCmd.SetWarnings False
DoCmd.OpenQuery "Delete_Blank_Material_Records"
DoCmd.SetWarnings True
'********************************************
End Sub
Function TransferBEData(ByVal tSource As String, ByVal tDestination As String)
If FileExists(tDestination) Then
Kill tDestination
End If
FileCopy tSource, tDestination
End Function
The reason this doesn't work, is because re-linking the tables to another source will not delete the entry from the .mdw lock file (or security equivalent in later versions than 03). You would need to close your front-end database and then re-open in order to unlock the local .mdb file.
Related
Is there a way wherein I will be able to compare data types of 2 tables in MS Access? I have one table with 66 columns with specified names (Like ID, Name, ETc...) and another table that will be autogenerated based on an extract with the same number of columns but the field names default (F1, F2, F3, ... F66) so would like to check if there is a way in access that I can compare the data types of 66 columns from both tables? Thanks Much! :D
You can use some VBA to loop the Fields collection of each table. Something like this should get you started:
Sub sCompareTables(strTable1 As String, strTable2 As String)
On Error GoTo E_Handle
Dim db As DAO.Database
Dim tdf1 As DAO.TableDef
Dim tdf2 As DAO.TableDef
Dim lngLoop1 As Long
Set db = CurrentDb
Set tdf1 = db.TableDefs(strTable1)
Set tdf2 = db.TableDefs(strTable2)
If tdf1.Fields.Count = tdf2.Fields.Count Then
For lngLoop1 = 0 To tdf1.Fields.Count - 1
If tdf1.Fields(lngLoop1).Type = tdf2.Fields(lngLoop1).Type Then
Debug.Print "Match: " & tdf1.Fields(lngLoop1).name & vbTab & tdf2.Fields(lngLoop1).name & vbTab & fDatatype(tdf1.Fields(lngLoop1).Type)
Else
Debug.Print "No Match: " & tdf1.Fields(lngLoop1).name & vbTab & tdf2.Fields(lngLoop1).name & vbTab & fDatatype(tdf1.Fields(lngLoop1).Type) & "|" & fDatatype(tdf2.Fields(lngLoop1).Type)
End If
Next lngLoop1
Else
Debug.Print "Field counts do not match"
End If
sExit:
On Error Resume Next
Set tdf1 = Nothing
Set tdf2 = Nothing
Set db = Nothing
Exit Sub
E_Handle:
MsgBox Err.Description & vbCrLf & vbCrLf & "sCompareTables", vbOKOnly + vbCritical, "Error: " & Err.Number
Resume sExit
End Sub
Function fDatatype(lngDatatype As Long) As String
On Error GoTo E_Handle
Select Case lngDatatype
Case 4
fDatatype = "Long"
Case 8
fDatatype = "Date"
Case 10
fDatatype = "Text"
Case 12
fDatatype = "Memo"
Case Else
fDatatype = "Unknown"
End Select
fExit:
On Error Resume Next
Exit Function
E_Handle:
MsgBox Err.Description & vbCrLf & vbCrLf & "fDatatype", vbOKOnly + vbCritical, "Error: " & Err.Number
Resume fExit
End Function
The function fDatatype that I've created does not list all of the available datatypes that are available - you can see a full list by pressing F2 to bring up the Object Browser, and searching for something like dbText to see all members of the DAO.DataTypeEnum class.
I have an access database that links to 6 tables. These tables are updated weekly and kept in a folder with the date. I would like for my access program to ask the user to select the location of the tables with out specifically using the Linked Table Manager.
The following code will prompt a user for the full path and file name of the database to be linked to. I decided to do this rather than just prompt for a folder. I strongly suggest you look at the connect string for one of your linked tables and make sure no other parameters are specified other than something like ';DATABASE=C:\Foldera\YYMMDD\MyAccessDB.mdb"
Private Function ReLinkTables()
Dim dbs As DAO.Database
Dim tdf As DAO.TableDef
Dim tdf2 As DAO.TableDef
Dim strConn As String
Dim strNewPath As String
Dim strTableName As String
On Error GoTo ERROR_HANDLER
' Prompt user for new path...
strNewPath = GetFolder
' Exit if none
If strNewPath = "" Then
Exit Function
End If
Set dbs = CurrentDb
dbs.TableDefs.Refresh
' Find all the linked tables...
For Each tdf In dbs.TableDefs
'Debug.Print tdf.Name & vbTab & tdf.Connect
If Len(tdf.Connect) > 0 Then
strTableName = tdf.Name
Debug.Print "Linked Table: " & tdf.Name & vbTab & tdf.Connect
dbs.TableDefs.Delete strTableName ' Delete the linked table
strConn = ";DATABASE=" & strNewPath
Set tdf2 = CurrentDb.CreateTableDef(strTableName, dbAttachSavePWD, strTableName, strConn)
CurrentDb.TableDefs.Append tdf2
Else ' Not a linked table
'Debug.Print "Keep: " & tdf.Name & vbTab & tdf.Connect
End If
Next tdf
Set tdf = Nothing
Set tdf2 = Nothing
dbs.TableDefs.Refresh
dbs.Close
Set dbs = Nothing
MsgBox "Finished Relinking Tables"
Proc_Exit:
Exit Function
ERROR_HANDLER:
Debug.Print Err.Number & vbTab & Err.Description
Err.Source = "Module_Load_SQLSERVER_DATABASE: ReLinkTables at Line: " & Erl
If Err.Number = 9999 Then
Resume Next
End If
MsgBox Err.Number & vbCrLf & Err.Description
Resume Proc_Exit
Resume Next
End Function
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFilePicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
'.InitialFileName = "Z:\xxxxxxxx" ' You can change to valid start path
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
Debug.Print "User selected path: >" & sItem & "<"
If sItem = "" Then MsgBox "User did not select a path.", vbOKOnly, "No Path"
GetFolder = sItem
Set fldr = Nothing
End Function
I have a massive set of linked databases that have the potential to move. Luckily they are all in ONE working directory of nested folders.
I have effectively created a module that has the path of this working folder defined.
As strWorkingFolder
Now the VBA of the main control center remains intact for multiple calls running and executing queries (append, delete, insert) etc. EXCEPT each of the databases that are still linked to the old folder.
I figured that whenever the error 3044 (Not sure of the exact verbiage "The path to this table does not exist), I could just relink to the correct path - because it is known: It would be strWorkingFolder (concatenated to whatever nested folder the database is in)
I thought I could get away with just linked tables, but apparently, I will need to re-link all kinds of files: csv, Excel, as well as ACCDB.
How can I get it to work?
This is currently what I have setup
Sub RemoveLinks()
Dim tdf As TableDef
For Each tdf In CurrentDb.TableDefs
If Left(tdf.Name, 4) <> "MSys" And (tdf.Attributes And dbAttachedTable) = dbAttachedTable Then
CurrentDb.TableDefs.Delete tdf.Name
End If
Next tdf
Set tdf = Nothing
End Sub
Sub LinkDatabase(StrDBPath As String)
Dim dbs As Database
Dim tdf As TableDef
Set dbs = OpenDatabase(StrDBPath)
For Each tdf In dbs.TableDefs
If Left(tdf.Name, 4) <> "MSys" Then
DoCmd.TransferDatabase acLink, "Microsoft Access", Trim(StrDBPath), acTable, tdf.Name, tdf.Name
SysCmd acSysCmdSetStatus, "Processing table [" & tdf.Name & "]..."
End If
Next tdf
SysCmd acSysCmdClearStatus
Set dbs = Nothing
Set tdf = Nothing
End Sub
Sub RefreshLinks(StrDBPath As String)
Dim tdf As TableDef
For Each tdf In CurrentDb.TableDefs
If (tdf.Attributes And dbAttachedTable) = dbAttachedTable Then
tdf.Connect = "; Database = " & StrDBPath
SysCmd acSysCmdSetStatus, "Processing table [" & tdf.Name & "]..."
tdf.RefreshLink
End If
Next tdf
Set tdf = Nothing
SysCmd acSysCmdClearStatus
End Sub
And finally, in the error_handler, I will trap 3044 and call
Public Sub Relink(strEnginePath)
Dim dbs As Database
Set dbs = CurrentDb
RemoveLinks
LinkDatabase (strEnginePath)
RefreshLinks (strEnginePath)
End Sub
Is there a better way to go about this?
I have altered your code so it will handle text and Excel in addition to Access tables. If you have other types attached, you need to modify the code.
NOTE: With this code, you should NOT delete the links because that will remove all of the attributes you need!
Also, if you have any parameters following the path/file names in the connect strings, you need to add code to retain that information. I hope you have some standards in place that would allow some logical actions to be taken.
Sub RefreshLinks(StrDBPath As String)
Dim iLen As Integer
Dim iStart As Integer
Dim iEnd As Integer
Dim iPos As Integer
Dim strOldConn As String
Dim strNewConn As String
Dim strFile As String
Dim tdf As TableDef
On Error GoTo Error_Trap
For Each tdf In CurrentDb.TableDefs
If (tdf.Attributes And dbAttachedTable) = dbAttachedTable Then
Debug.Print "Table Name: " & tdf.Name
strOldConn = tdf.Connect ' Save the connect string
iLen = Len(strOldConn)
iStart = InStr(1, strOldConn, "DATABASE=") ' Find start of path
iEnd = InStr(iStart + 1, strOldConn, ";") ' Is there more after path?
Debug.Print tdf.Name & ": " & tdf.Connect
If LCase(left(strOldConn, 4)) = "text" Then ' Text file attached
strNewConn = left(strOldConn, iStart + 8) & StrDBPath
ElseIf LCase(left(strOldConn, 5)) = "excel" Then ' Excel file attached
strFile = ""
For iPos = iLen To 1 Step -1 ' Get the file name from the path
If Mid(strOldConn, iPos, 1) = "\" Then Exit For
strFile = Mid(strOldConn, iPos, 1) & strFile
Next
If iPos = 0 Then
MsgBox "Did not find path delimiter '\'" & vbCrLf & vbCrLf & "for TDF '" & tdf.Name & "'", vbOKOnly + vbCritical, "Path Delimiter Unknown"
End If
strNewConn = left(strOldConn, iStart + 8) & StrDBPath & "\" & strFile
Else
' Assume it is Access table. If other types, add code to handle.
strFile = ""
For iPos = iLen To 1 Step -1 ' Get the file name from the path
If Mid(strOldConn, iPos, 1) = "\" Then Exit For
strFile = Mid(strOldConn, iPos, 1) & strFile
Next
If iPos = 0 Then
MsgBox "Did not find path delimiter '\' in connect string '" & strOldConn & "'", vbOKOnly + vbCritical, "Wrong delimiter?"
End If
strNewConn = left(strOldConn, iStart + 8) & StrDBPath & "\" & strFile
End If
Debug.Print " (new): " & strNewConn
tdf.Connect = strNewConn
SysCmd acSysCmdSetStatus, "Processing table [" & tdf.Name & "]..."
tdf.RefreshLink
Else
' Ignore this table since it is not linked.
End If
Next tdf
Set tdf = Nothing
SysCmd acSysCmdClearStatus
Exit Sub
Error_Trap:
MsgBox "Error: " & Err.Number & vbTab & Err.Description & vbCrLf & vbCrLf & _
"While processing table: " & tdf.Name & vbCrLf & _
"Old: " & strOldConn & vbCrLf & _
"New: " & strNewConn, vbOKOnly, "Relink Error"
Exit Sub
End Sub
I am setting up a Audit Tracking system for the forms in my database. I am following the example from Susan Harkins Here
My code works for my form customers which is based off the customers table. Here is my code:
Const cDQ As String = """"
Sub AuditTrail(frm As Form, recordid As Control)
'Track changes to data.
'recordid identifies the pk field's corresponding
'control in frm, in order to id record.
Dim ctl As Control
Dim varBefore As Variant
Dim varAfter As Variant
Dim strControlName As String
Dim strSQL As String
On Error GoTo ErrHandler
'Get changed values.
For Each ctl In frm.Controls
With ctl
'Avoid labels and other controls with Value property.
If .ControlType = acTextBox Then
If .Value <> .OldValue Then
MsgBox "Step 1"
varBefore = .OldValue
varAfter = .Value
strControlName = .Name
'Build INSERT INTO statement.
strSQL = "INSERT INTO " _
& "Audit (EditDate, User, RecordID, SourceTable, " _
& " SourceField, BeforeValue, AfterValue) " _
& "VALUES (Now()," _
& cDQ & Environ("username") & cDQ & ", " _
& cDQ & recordid.Value & cDQ & ", " _
& cDQ & frm.RecordSource & cDQ & ", " _
& cDQ & .Name & cDQ & ", " _
& cDQ & varBefore & cDQ & ", " _
& cDQ & varAfter & cDQ & ")"
'View evaluated statement in Immediate window.
Debug.Print strSQL
DoCmd.SetWarnings False
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
End If
End If
End With
Next
Set ctl = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description & vbNewLine _
& Err.Number, vbOKOnly, "Error"
End Sub
However, when I try to change data in my subform within the form I get an error "Operation is not supported for this type of object". I can see the error is occuring here:
If .Value <> .OldValue Then
My subform is based off of a query which is based off of three tables
I'm trying to change a customer price under Customer Products and keep a log of those changes. Is there something I'm missing or a work around.
Thank you for the help!
Temporarily disable your error handler like this:
'On Error GoTo ErrHandler
When you get the error notice about "operation not supported", choose Debug from the error dialog. That will allow you to find out more information about the current text box control which is triggering the error. Try the following statements in the Immediate window:
? ctl.Name
? ctl.ControlSource
? ctl.Enabled
? ctl.Locked
? ctl.Value
At least ctl.Name will identify which text box is triggering the error.
After examining the db, I'll suggest a function (IsOldValueAvailable) to indicate whether .OldValue is available for the current control. With that function, the AuditTrail procedure works after this change:
'If .ControlType = acTextBox Then
If IsOldValueAvailable(ctl) = True Then
And the function. It may still need more work, but I didn't spot any problems in my testing.
Public Function IsOldValueAvailable(ByRef ctl As Control) As Boolean
Dim blnReturn As Boolean
Dim strPrompt As String
Dim varOldValue As Variant
On Error GoTo ErrorHandler
Select Case ctl.ControlType
Case acTextBox
varOldValue = ctl.OldValue
blnReturn = True
Case Else
' ignore other control types; return False
blnReturn = False
End Select
ExitHere:
On Error GoTo 0
IsOldValueAvailable = blnReturn
Exit Function
ErrorHandler:
Select Case Err.Number
Case 3251 ' Operation is not supported for this type of object.
' pass
Case Else
strPrompt = "Error " & Err.Number & " (" & Err.Description _
& ") in procedure IsOldValueAvailable"
MsgBox strPrompt, vbCritical, "IsOldValueAvailable Function Error"
End Select
blnReturn = False
Resume ExitHere
End Function
I've been looking a while now for a solution to export a query with open parameters. I need to export a Query as a Formatted Excel Spreadsheet and can't create additional Tables, Queries, Forms, or Reports to the Database being used. I use DoCmd.OutputTo as it exports a formatted query unlike DoCmd.TransferSpreadsheet however I can't seem to export the query with defined parameters. I need to include the parameters or else the user will be forced to input the start and end date three times a piece as the database for some reason asks for the startDate and endDate twice and in order to keep the excel spreadsheet and the subsequent outlook section consistant i would have to ask the user to input their previous parameters again
Sub Main()
On Error GoTo Main_Err
'Visually Display Process
DoCmd.Hourglass True
Dim fpath As String
Dim tname As String
Dim cname As String
Dim tType As AcOutputObjectType
Dim tempB As Boolean
fpath = CurrentProject.path & "\"
'tType = acOutputTable
'tname = "APPROVED SWPS FOR LOOK AHEAD & BAR CHART"
tType = acOutputQuery
tname = "ASFLA&BC Query"
cname = "Temp BPC Calendar"
Dim qdfQry As DAO.QueryDef
Dim strStart As String
Dim strEnd As String
Set qdfQry = CurrentDb().QueryDefs(tname)
'strStart = InputBox("Please enter Start date (mm/dd/yyyy)")
'strEnd = InputBox("Please enter Start date (mm/dd/yyyy)")
qdfQry.Parameters("ENTER START DATE") = FormatDateTime("6/30/12", vbShortDate) 'strEnd
qdfQry.Parameters("ENTER END DATE") = FormatDateTime("7/1/12", vbShortDate) 'strStart
tempB = Backup(fpath, qdfQry, tType)
If (Not tempB) Then
MsgBox "Excel Conversion Ended Prematurely..."
Exit Sub
End If
' tempB = sendToOutlook(qdfQry, cname)
' If (Not tempB) Then
' MsgBox "Access Conversion Ended Prematurely..."
' Exit Sub
' End If
MsgBox "Procedure Completed Successfully"
Main_Exit:
DoCmd.Hourglass False
Exit Sub
Main_Err:
DoCmd.Beep
MsgBox Error$
Resume Main_Exit
End Sub
'************************************************************************************
'*
'* Excel PORTION
'*
'************************************************************************************
Public Function Backup(path As String, db As DAO.QueryDef, Optional outputType As AcOutputObjectType) As Boolean
On Error GoTo Error_Handler
Backup = False
Dim outputFileName As String
Dim name As String
Dim tempB As Boolean
'Set Up All Name Variablesand
name = Format(Date, "MM-dd-yy") & ".xls"
'Cleans Directory of Any older files and places them in an archive
SearchDirectory path, "??-??-??.xls", name
'See If File Can Now Be Exported. If Already Exists ask to overwrite
outputFileName = path & name
tempB = OverWriteRequest(outputFileName)
If tempB Then
'Formats The Table And Exports Into A Formatted SpreadSheet
'Checks if an output type was added to the parameter if not defualt to table
If Not IsMissing(outputType) Then
DoCmd.OutputTo outputType, db.name, acFormatXLS, outputFileName, False
Else
DoCmd.OutputTo acOutputTable, db.name, acFormatXLS, outputFileName, False
End If
Else
Exit Function
End If
Backup = True
Error_Handler_Exit:
Exit Function
Error_Handler:
MsgBox "MS Access has generated the following error" & vbCrLf & vbCrLf & "Error Number: " & _
Err.number & vbCrLf & "Error Source: Main Excel Backup" & vbCrLf & "Error Description: " & _
Err.Description, vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Function
The SQL currently given looks like similar to below with omitted fields for for clarity
PARAMETERS [ENTER START DATE] DateTime, [ENTER END DATE] DateTime;
SELECT [SWPS].STATION,
[SWPS].START_DATE,
[SWPS].END_DATE,
FROM [SWPS]
WHERE ((([SWPS].STATION)
Like ("*"))
AND (([SWPS].START_DATE)<=[ENTER END DATE])
AND (([SWPS].END_DATE)>=[ENTER START DATE])
AND (([SWPS].SWP_STATUS) In ("A","P","W","T","R")));
I suggest you change the sql of the query.
Dim qdfQry As DAO.QueryDef
Dim strStart As String
Dim strEnd As String
''You could use a query specifically for this
Set qdfQry = CurrentDb.QueryDefs(tname)
sSQL=qdfQry.SQL
NewSQL = "SELECT [SWPS].STATION, [SWPS].START_DATE, [SWPS].END_DATE, " _
& "FROM [SWPS] WHERE [SWPS].STATION Like '*' " _
& "AND [SWPS].SWP_STATUS In ('A','P','W','T','R') " _
& "AND [SWPS].START_DATE)<=#" & Format(DateStart, "yyyy/mm/dd") & "# " _
& "AND [SWPS].END_DATE)>=#" & Format(DateEnd, "yyyy/mm/dd") & "#"
qdfQry.SQL = NewSQL
''Do the excel stuff
''Reset the query
qdfQry.SQL = sSQL