473,382 Members | 1,365 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

VBA Create Delete relationships

PhilOfWalton
1,430 Expert 1GB
I need to delete relationships using VBA so that I can delete the linked tables, then link different tables and re-create the relationship.

This is the code I use to create the relationship
Expand|Select|Wrap|Line Numbers
  1. Sub CreateRelation(RelName As String, TabPrime As String, TabForeign As String, FldPrime As String, FldForeign As String)
  2.  
  3.     Dim MyDb As DAO.Database
  4.     Dim Rel As DAO.Relation
  5.     Dim Fld As DAO.Field
  6.  
  7.     On Error GoTo CreateRelationDAO_Err
  8.  
  9.     'Initialize
  10.     Set MyDb = CurrentDb()
  11.  
  12.     ' Check if relationship already there
  13.     For Each Rel In MyDb.Relations
  14.         If Rel.Name = RelName Then
  15.             Exit Sub
  16.         End If
  17.     Next Rel
  18.  
  19.     'Create a new relation.
  20.     Set Rel = MyDb.CreateRelation(RelName)
  21.  
  22.     'Define its properties.
  23.     With Rel
  24.         'Specify the primary table.
  25.         .Table = TabPrime
  26.         'Specify the related table.
  27.         .ForeignTable = TabForeign
  28.         'Specify attributes for cascading updates and deletes.
  29.         .Attributes = 3
  30.  
  31.         'Add the fields to the relation.
  32.         'Field name in primary table.
  33.         Set Fld = .CreateField(FldPrime)
  34.         'Field name in related table.
  35.         Fld.ForeignName = FldForeign
  36.         'Append the field
  37.         .Fields.Append Fld
  38.  
  39.         'Repeat for other fields if a multi-field relation.
  40.     End With
  41.  
  42.     'Save the newly defined relation to the Relations collection.
  43.     MyDb.Relations.Append Rel
  44.  
  45. CreateRelationDAO_Exit:
  46.     'Clean up
  47.     Set Fld = Nothing
  48.     Set Rel = Nothing
  49.     Set MyDb = Nothing
  50.     'Debug.Print "Relation created."
  51.  
  52.     Exit Sub
  53.  
  54. CreateRelationDAO_Err:
  55.     el = Erl
  56.     en = Err.Number
  57.     ed = Err.Description
  58.     ctrlfnctnm = "GetDescription"
  59.     Call Form_Err(en, ed, ctrlfnctnm, el, errMsgStr)
  60.     Resume CreateRelationDAO_Exit
  61.  
  62. End Sub
  63.  



Here is the relationship window, and there are 2 copies of TblJoinComputerBranchTblComputers


It would appear that if the tables are local, I get line 4 as expected. using the code
Expand|Select|Wrap|Line Numbers
  1.     CreateRelation "TblJoinComputerBranchTblComputers", "TblJoinComputerBranch", _
  2.     "TblComputers", "ComputerID", "ComputerID"
  3.  
Assuming my FE is on Computer 1, TblComputers on Computer2 and TblJoinComputerBranch on Computer3 ... Don't ask
it would appear Access creates it's own name for the relationship as on line 1 (Difficult to see) but it is
{C40F1BCB-C7D2-4ED0-8DFF-EADBF5B7E583}

This code works to delete the relationship created with my name

Expand|Select|Wrap|Line Numbers
  1. Function DeleteRelationship(RelName As String)
  2. '   DeleteRelationship ("TblJoinComputerBranchTblComputers")
  3.     On Error GoTo DeleteRelationship_Err
  4.  
  5.     Dim MyDb As DAO.Database
  6.     Set MyDb = CurrentDb
  7.     MyDb.Relations.Delete RelName
  8.     Set MyDb = Nothing
  9.  
  10. DeleteRelationship_Exit:
  11.     Exit Function
  12.  
  13. DeleteRelationship_Err:
  14.     If Err = 3265 Then                  ' Relationship doesn't exist
  15.         Resume DeleteRelationship_Exit
  16.     Else
  17.         el = Erl
  18.         en = Err.Number
  19.         ed = Err.Description
  20.         ctrlfnctnm = "RElationship"
  21.         Call Form_Err(en, ed, ctrlfnctnm, el, errMsgStr)
  22.         Resume DeleteRelationship_Exit
  23.     End If
  24.  
  25. End Function
  26.  
I appreciate the picture of the table is not very clear but the only difference between line 1 and line 4 is in the last column where on line 1 it is:
Expand|Select|Wrap|Line Numbers
  1. {C40F1BCB-C7D2-4ED0-8DFF-EADBF5B7E583}
and on Line 4 it is:
Expand|Select|Wrap|Line Numbers
  1. TblJoinComputerBranchTblComputers
My problem is deleting the
{C40F1BCB-C7D2-4ED0-8DFF-EADBF5B7E583} relationship.

How do I find the name or do I have to trawl through the MSysRelationships table to match the names of the 4 fields that I do know and delete them.

Sorry this post is so long winded.

Phil
Aug 17 '16 #1

✓ answered by ADezii

  1. Tom, while deal with confusing Relationship Names at all? Why not simply pass the 2 Table Names involved in a Relationship to a Public Function, in any order, that will do the dirty work for you? The Function will return a Boolean Value indicating Success or Failure. As an example, I created a Code Segment that will DELETE the Relationship between the Orders and Shippers Tables in the Northwind Sample DB without knowing the Name of the Relationship.
  2. Function Definition:
    Expand|Select|Wrap|Line Numbers
    1. Public Function fDELETERelationship(strTable1 As String, strTable2 As String) As Boolean
    2. On Error GoTo Err_fDELETERelationship
    3. Dim rel As DAO.Relation
    4.  
    5. For Each rel In CurrentDb.Relations
    6.   If (rel.Table = strTable1 And rel.ForeignTable = strTable2) Or _
    7.      (rel.Table = strTable2 And rel.ForeignTable = strTable1) Then
    8.        CurrentDb.Relations.Delete rel.Name
    9.   End If
    10. Next
    11.  
    12. fDELETERelationship = True
    13.  
    14. Exit_fDELETERelationship:
    15.   Exit Function
    16.  
    17. Err_fDELETERelationship:
    18.   fDELETERelationship = False
    19.     MsgBox Err.Description, vbExclamation, "Error in fDELETERelationship()"
    20.       Resume Exit_fDELETERelationship
    21. End Function
    22.  
  3. Sample Function Call:
    Expand|Select|Wrap|Line Numbers
    1. If fDELETERelationship("Orders", "Shippers") Then
    2.   MsgBox "Relationship has been DELETED!"
    3. Else
    4.   MsgBox "Relationship has NOT been DELETED!"
    5. End If
    6.  
  4. OR
    Expand|Select|Wrap|Line Numbers
    1. If fDELETERelationship("Shippers", "Orders") Then
    2.   MsgBox "Relationship has been DELETED!"
    3. Else
    4.   MsgBox "Relationship has NOT been DELETED!"
    5. End If
    6.  

6 6483
ADezii
8,834 Expert 8TB
  1. Tom, while deal with confusing Relationship Names at all? Why not simply pass the 2 Table Names involved in a Relationship to a Public Function, in any order, that will do the dirty work for you? The Function will return a Boolean Value indicating Success or Failure. As an example, I created a Code Segment that will DELETE the Relationship between the Orders and Shippers Tables in the Northwind Sample DB without knowing the Name of the Relationship.
  2. Function Definition:
    Expand|Select|Wrap|Line Numbers
    1. Public Function fDELETERelationship(strTable1 As String, strTable2 As String) As Boolean
    2. On Error GoTo Err_fDELETERelationship
    3. Dim rel As DAO.Relation
    4.  
    5. For Each rel In CurrentDb.Relations
    6.   If (rel.Table = strTable1 And rel.ForeignTable = strTable2) Or _
    7.      (rel.Table = strTable2 And rel.ForeignTable = strTable1) Then
    8.        CurrentDb.Relations.Delete rel.Name
    9.   End If
    10. Next
    11.  
    12. fDELETERelationship = True
    13.  
    14. Exit_fDELETERelationship:
    15.   Exit Function
    16.  
    17. Err_fDELETERelationship:
    18.   fDELETERelationship = False
    19.     MsgBox Err.Description, vbExclamation, "Error in fDELETERelationship()"
    20.       Resume Exit_fDELETERelationship
    21. End Function
    22.  
  3. Sample Function Call:
    Expand|Select|Wrap|Line Numbers
    1. If fDELETERelationship("Orders", "Shippers") Then
    2.   MsgBox "Relationship has been DELETED!"
    3. Else
    4.   MsgBox "Relationship has NOT been DELETED!"
    5. End If
    6.  
  4. OR
    Expand|Select|Wrap|Line Numbers
    1. If fDELETERelationship("Shippers", "Orders") Then
    2.   MsgBox "Relationship has been DELETED!"
    3. Else
    4.   MsgBox "Relationship has NOT been DELETED!"
    5. End If
    6.  
Aug 18 '16 #2
zmbd
5,501 Expert Mod 4TB
ADezii, very nice... I have read thru most if not all of the tabledef and relationship objects for something better and of course the SQL ALTER TABLE doesn't work on linked tables - IMHO, at this point in time, you have the only tool in the shop for the task at hand!
Aug 18 '16 #3
PhilOfWalton
1,430 Expert 1GB
Sweet, thanks a lot

Phil
Aug 18 '16 #4
ADezii
8,834 Expert 8TB
Thanks for the compliment, zmbd - glad it worked out for you, Phil.

P.S. - Not really that critical, but I would probably set the Return Value of the Function = True and exit the For...Next Loop after
Expand|Select|Wrap|Line Numbers
  1. CurrentDb.Relations.Delete rel.Name
Aug 18 '16 #5
NeoPa
32,556 Expert Mod 16PB
Nice one ADezii. Long in the tooth but you've still got it :-)
Aug 19 '16 #6
ADezii
8,834 Expert 8TB
@NeoPa:
Was wondering how you have been, hopefully all is well. Always nice to hear from an old friend (the old not meant literally!).
Aug 19 '16 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Erick Bodine | last post by:
I am trying to get a list of Storage Groups on an Exchange Server (E2K) with an eye towards deleting/creating more. I am going off of the Exchange SDK docs in msdn...
3
by: banon | last post by:
I am trying to write code to create and delete a virtual directory with ASP 3. If it is not possible, then how could I do the same with a physical folder. any help is appreciated. Thanks in...
10
by: Dixie | last post by:
I need to delete some relationships in code. How do I know what the names of those relationships are?
0
by: rsheridan | last post by:
OK - My issue is that I am trying to build an app that will add and delete printers. I know this can be thru WMI on Windows 2003 and XP Operating systems. But Unfortantely I need this to work on...
0
by: Shaul Feldman | last post by:
Hello, I'm trying to find a way to add data (not working with DB) from client-side to server side. Let's say I have a form (page) that a user may add rows (in table) with data. the data is NOT...
3
by: bluez | last post by:
I want to design a webpage where user can search the data from the database and list out the related records. Each of the record got a delete button which allow user to delete the record. ...
3
by: Yas | last post by:
Hi everyone I am trying to create a DELETE Trigger. I have 2 tables. Table1 and Table2. Table 2 has all the same fields and records as Table1 + 1 extra column "date_removed" I would like that...
1
by: Claire | last post by:
Ive written a small string resource building utility that I send out to our translators. I have a setup project for each language we support, which picks out a group of 12 english resx files plus...
3
by: tetsuo2030 | last post by:
Greetings all, (Access 2003) The bosses want me to take an old version of a database designed with a single-user-at-a-time mentality and update it to allow multiple, simultaneous users. The...
8
Ajay Bhalala
by: Ajay Bhalala | last post by:
I have one application in which I used one richtextbox and some buttons. I have 1 button named "Delete". I want to create delete command using the code. When the user clicked the "Delete"...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.