473,396 Members | 2,023 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,396 software developers and data experts.

change Indexed field to "No"

Hi. Can somebody please help me out here. I have 3 things that i want to do via VBA but cant find what im looking for in the net.

1. I want to be able to change any indexed fields in a table to not indexed. for example. the fields are set as Indexed = Yes (No Duplicates) and i want them to be set as Indexed = No.

2. I want to change all fields in a table that are AutoNumber to Number(long)

3. I want to remove all primary keys from a table.

If anyone can help me with this i would be supa greatful.

thanks

trevor
Jul 4 '10 #1
1 4284
Jim Doherty
897 Expert 512MB
@TrevoriousD
I Have knocked together a module for you to look at and attached it as a textfile as well.

Import it into a spare copy of Microsofts example database 'Northwind' and test it out by typing the function name BanishIndexes at the immediate window or assign the function to a button or whatever else is your flavour in a copy of your own database, whatever that is, to satisfy yourself that it performs as expected.

The VBA routines therein should be sufficient to fit your needs or give you some ideas as to which code segments might be relevant to you.

Basically what the module does is firstly count any relationships defined in your database. If there are relationships it will ask you if you wish to drop them (given you are rather limited as to what you can accomplish if relationships between primary keys exist) A new table is created named tblIndexes and populated with all table names and indexes except Access system tables (tables names prefixed with 'MSys').

tblIndexes is traversed in a code loop dropping indexes for all table names contained in tblIndexes accordingly. This table (tblIndexes) is ultimately left in your database as a reference point for you to examine post processing. Delete at your leisure.

The autonumber columns are dealt with by firstly asking you if you wish to deal with that element at the same time. If so it continues examining autonumber fields and 'dropping' them, but not without first placing any data contents into a 'holding' field and then recreating the original autonumber field as a long integer field and repopulating it.

The downside of this field creation 'as is' of course is that it places the newly created and populated long integer field (hitherto autonumber) at the 'end' of the field stack (you will see it as the last field listed in table design view) but with development you could rearrange this if needs be

Regards :)

Expand|Select|Wrap|Line Numbers
  1. '---------------------------------------------------------------------------------------
  2. ' Module    : bas_BanishIndexes
  3. ' Author    : Jim Doherty www.Bytes.com
  4. ' Date      : 05/07/2010
  5. ' Reference : http://bytes.com/topic/access/answers/890981-change-indexed-field-no
  6. ' Purpose   : To deal with three issues as requested on the forum
  7. '1. to be able to change any indexed fields in a table to not indexed. for example.
  8. 'the fields are set as Indexed = Yes (No Duplicates) and i want them to be set as Indexed = No.
  9. '2. I want to change all fields in a table that are AutoNumber to Number(long)
  10. '3. I want to remove all primary keys from a table.
  11.  
  12. 'Tested on Northwind database tables  and works ok! but test it out yourself on a spare copy  USE AT YOUR RISK!
  13. '---------------------------------------------------------------------------------------
  14. Option Explicit
  15.  
  16. Sub CreateTable_tblIndexes()
  17.     On Error GoTo CreateTable_tblIndexes_Error
  18.     Dim db As DAO.Database
  19.     Dim tdf As DAO.TableDef
  20.     Dim fld As DAO.Field
  21.     Dim ind As DAO.Index
  22.  
  23.     Set db = CurrentDb()
  24.     For Each tdf In db.TableDefs    'delete any pre-existing tblindex table
  25.         If tdf.Name = "tblIndexes" Then db.TableDefs.Delete "tblIndexes"
  26.     Next
  27.     Set tdf = db.CreateTableDef("tblIndexes")
  28.     With tdf
  29.         Set fld = .CreateField("Row", dbLong)
  30.         fld.Attributes = dbAutoIncrField + dbFixedField
  31.         .Fields.Append fld
  32.         .Fields.Append .CreateField("TableName", dbText, 100)
  33.         .Fields.Append .CreateField("FieldCount", dbLong)
  34.         .Fields.Append .CreateField("IndexName", dbText, 100)
  35.         .Fields.Append .CreateField("Sequence", dbLong)
  36.         .Fields.Append .CreateField("Primary", dbBoolean)
  37.         .Fields.Append .CreateField("Unique", dbBoolean)
  38.     End With
  39.     db.TableDefs.Append tdf
  40.     Set ind = tdf.CreateIndex("PrimaryKey")
  41.     With ind
  42.         .Fields.Append .CreateField("Row")
  43.         .Unique = True
  44.         .Primary = True
  45.     End With
  46.     tdf.Indexes.Append ind
  47.     RefreshDatabaseWindow
  48.     Set fld = Nothing
  49.     Set tdf = Nothing
  50.     Set db = Nothing
  51.  
  52.     On Error GoTo 0
  53.     Exit Sub
  54. CreateTable_tblIndexes_Error:
  55.     MsgBox "Error " & Err.Number & " (" & Err.Description & _
  56.            ") in procedure CreateTable_tblIndexes of Module bas_BanishIndexes"
  57. End Sub
  58.  
  59. Function DoIndexes(tbl, rstIndexes As Object)
  60.     On Error GoTo DoIndexes_Error
  61.     Dim idx As DAO.Index
  62.     Dim Ctr As Integer  'counter (simply for sequencing)
  63.     Ctr = 1
  64.     BeginTrans
  65.     For Ctr = 1 To tbl.Indexes.Count
  66.         Set idx = tbl.Indexes(Ctr - 1)
  67.         rstIndexes.AddNew
  68.         rstIndexes!TableName = tbl.Name
  69.         rstIndexes!FieldCount = tbl.Fields.Count
  70.         rstIndexes!IndexName = idx.Name
  71.         rstIndexes!Sequence = Ctr
  72.         rstIndexes!Primary = idx.Primary
  73.         rstIndexes!Unique = idx.Unique
  74.         rstIndexes.Update
  75.         '  wIdxCtr = wIdxCtr + 1
  76.     Next Ctr
  77.     CommitTrans
  78.     Set idx = Nothing
  79.  
  80.     On Error GoTo 0
  81.     Exit Function
  82.  
  83. DoIndexes_Error:
  84.     MsgBox "Error " & Err.Number & " (" & Err.Description & _
  85.         ") in procedure DoIndexes of Module bas_BanishIndexes"
  86. End Function
  87.  
  88. Function ExamineIndexes()
  89.     On Error GoTo ExamineIndexes_Error
  90.     Dim Mydb As DAO.Database
  91.     Dim MyRS As DAO.Recordset
  92.     Dim tbl As DAO.TableDef
  93.     Dim rstIndexes As DAO.Recordset
  94.     Dim MyFields As DAO.Recordset
  95.     Dim MyField As DAO.Field
  96.     Dim MyIndex As DAO.Index
  97.     Dim MyIndexfields
  98.     Dim strSQL As String
  99.     Dim mystr As String, myndxstr As String
  100.     Dim MyIndexunique
  101.     Dim j As Long, cnt As Long
  102.     Dim x
  103.  
  104.     Set Mydb = CurrentDb
  105.     Set rstIndexes = Mydb.OpenRecordset("SELECT * FROM tblIndexes WHERE 1=2", dbOpenDynaset)
  106.     BeginTrans
  107.     SysCmd acSysCmdInitMeter, "Examining tables: ", CurrentDb.TableDefs.Count
  108.     cnt = 1
  109.     For Each tbl In CurrentDb.TableDefs
  110.         SysCmd acSysCmdUpdateMeter, cnt
  111.         If Left(tbl.Name, 4) <> "MSys" Then
  112.             If tbl.Name <> "tblIndexes" Then
  113.                 x = DoIndexes(tbl, rstIndexes)
  114.             End If
  115.  
  116.         End If
  117.         cnt = cnt + 1
  118.     Next tbl
  119.     CommitTrans
  120.     SysCmd acSysCmdRemoveMeter
  121.     rstIndexes.Close
  122.     Set rstIndexes = Nothing
  123.     Set MyIndex = Nothing
  124.     Set tbl = Nothing
  125.     Set Mydb = Nothing
  126.     strSQL = ""
  127.  
  128.     On Error GoTo 0
  129.     Exit Function
  130. ExamineIndexes_Error:
  131.     MsgBox "Error " & Err.Number & " (" & Err.Description & _
  132.         ") in procedure ExamineIndexes of Module bas_BanishIndexes"
  133. End Function
  134.  
  135. '---------------------------------------------------------------------------------------
  136. ' Procedure : BanishIndexes
  137. ' Author    : Jim Doherty
  138. ' Date      : 05/07/2010
  139. ' Purpose   : Run this from the immediate window simply type the Function name
  140.             '    ?BanishIndexes
  141.             'and hit enter   (You can if you wish assign the function to a button on a form up to you)
  142. '           The procedure will call a routine to create a table inwhich is pumped table indexes
  143.             'the table is ultimately traversed and relevant indexes dropped as outlined by the
  144.             'contents of the table created called tblIndexes. The finale is a call to the function
  145.             ''ed AUTOSTOLONG which looks for existing autonumber fields in all tables
  146.             'if it finds one it creates a holding field and updates the contents from the autonumber
  147.             'field. the original autonumber field is then dropped and recreated (cannot rename) and the
  148.             'holding field then puts all the data back into the created  long integer field
  149. '---------------------------------------------------------------------------------------
  150. '
  151. Function BanishIndexes()
  152.     On Error GoTo BanishIndexes_Error
  153.     Dim db As DAO.Database
  154.     Dim rs As DAO.Recordset
  155.     Dim msg As String
  156.     Set db = CurrentDb
  157.     If CurrentDb.Relations.Count > 0 Then
  158.         msg = "You have relationships defined in this database" & vbNewLine
  159.         msg = msg & "You cannot drop primary keys unless you delete relationships" & vbNewLine & vbNewLine
  160.         msg = msg & "Do you wish to delete them in order to use this procedure?"
  161.         DoCmd.Beep
  162.         If MsgBox(msg, vbQuestion + vbYesNo, "Drop Relationships") = vbYes Then
  163.             DeleteRelationShips
  164.         Else
  165.             Exit Function
  166.         End If
  167.     End If
  168.     CreateTable_tblIndexes    '<< create a table to store indexes so we have an 'after job done' reference
  169.     ExamineIndexes  '<<< pump all table indexes into the created table
  170.     'Now loop this tblIndexes table using it as a reference and delete the primary keys
  171.     Set rs = db.OpenRecordset("tblIndexes", dbOpenSnapshot)
  172.     Do While Not rs.EOF
  173.         DBEngine(0)(0).TableDefs(rs!TableName).Indexes.Delete (rs!IndexName)
  174.         rs.MoveNext
  175.     Loop
  176.     rs.Close
  177.     AutosToLong
  178.     MsgBox "Process Complete", vbInformation, "System Message"
  179.     Set rs = Nothing
  180.     Set db = Nothing
  181.     On Error GoTo 0
  182.     Exit Function
  183. BanishIndexes_Error:
  184.     If Err.Number = 3281 Then Resume Next    '<< 3281 is error for index used in relation
  185.     MsgBox "Error " & Err.Number & " (" & Err.Description & _
  186.            ") in BanishIndexes of Module bas_BanishIndexes", vbExclamation, _
  187.            "System Message"
  188. End Function
  189.  
  190. '---------------------------------------------------------------------------------------
  191. ' Procedure : DeleteRelationShips
  192. ' Purpose   : Delete all relationships in the current database
  193. '---------------------------------------------------------------------------------------
  194. Function DeleteRelationShips()
  195.     On Error Resume Next
  196.     Dim rel As DAO.Relation
  197.     For Each rel In CurrentDb.Relations
  198.         CurrentDb.Relations.Delete rel.Name
  199.     Next
  200. End Function
  201.  
  202. '---------------------------------------------------------------------------------------
  203. ' Procedure : AutosToLong
  204. ' Purpose   : to change all autonumbers to long integer for all tables in the database
  205. '---------------------------------------------------------------------------------------
  206. Function AutosToLong()
  207.     On Error GoTo AutosToLong_Error
  208.     Dim db As DAO.Database
  209.     Dim tdf As DAO.TableDef
  210.     Dim fld As DAO.Field
  211.     Dim MyField As String, msg As String
  212.     Set db = CurrentDb
  213.     msg = "Do you wish to change all 'Autonumber' fields to Number Long Integer?"
  214.     If MsgBox(msg, vbQuestion + vbYesNo, "Change Autonumbers") = vbNo Then
  215.         Exit Function
  216.         For Each tdf In CurrentDb.TableDefs
  217.             If Left(tdf.Name, 4) <> "MSys" And tdf.Name <> "tblIndexes" Then
  218.                 For Each fld In tdf.Fields
  219.                     If CLng(fld.Type) = dbLong Then
  220.                         If (fld.Attributes And dbAutoIncrField) = 0& Then
  221.                             'it is a long integer so leave alone
  222.                         Else
  223.                             'it is an autonumber so convert by creating a field
  224.                             'then updating it and dropping the original and recreating it
  225.                             DoCmd.SetWarnings False
  226.  
  227.                             BeginTrans
  228.                             tdf.Fields.Append tdf.CreateField("HoldingField", dbLong)
  229.                             DoCmd.RunSQL "UPDATE " & tdf.Name & " SET HoldingField=" & fld.Name & ";"
  230.                             MyField = fld.Name
  231.                             tdf.Fields.Delete fld.Name
  232.                             tdf.Fields.Append tdf.CreateField(MyField, dbLong)
  233.                             DoCmd.RunSQL "UPDATE " & tdf.Name & " SET " & MyField & "=HoldingField;"
  234.                             tdf.Fields.Delete "HoldingField"
  235.                             CommitTrans
  236.                             DoCmd.SetWarnings True
  237.                         End If
  238.                     End If
  239.                 Next fld
  240.             End If
  241.         Next tdf
  242.     End If
  243.  
  244.     On Error GoTo 0
  245.     Exit Function
  246. AutosToLong_Error:
  247.     MsgBox "Error " & Err.Number & " (" & Err.Description & _
  248.         ") in procedure AutosToLong of Module bas_BanishIndexes"
  249. End Function
Attached Files
File Type: txt BanishIndexes.txt (10.0 KB, 371 views)
Jul 4 '10 #2

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

Similar topics

2
by: Bengt Richter | last post by:
Why wouldn't quote-stuffing solve the problem, and let you treat \ as an ordinary character? In a raw string, it's no good for preventing end-of-quoting anyway, unless you want the literal \ in...
1
by: Mark Richards | last post by:
The solutions for the following problems seems to be simple but I did not found a (convenient) solution: Assume we have a number of elements of the same type under a common parent e.g. <person...
38
by: Haines Brown | last post by:
I'm having trouble finding the character entity for the French abbreviation for "number" (capital N followed by a small supercript o, period). My references are not listing it. Where would I...
1
by: Grey | last post by:
i use "this.Page.RegisterStartupScript()" to display the client-side script of confirmation box ...but I want to know that how can I know the user was clicked "YES" or "NO" as I need to do different...
0
by: sdb1031 | last post by:
I'm trying to learn about Python and XML. I would like to be able to add standalone="no" to my xml declaration when writing an xml file, but I am unable to figure out how. So far, I have the...
5
by: balakrishnan.dinesh | last post by:
hi Frnds, I need Confirm box with "yes" or "no" buttons, Is that possible in JAVASCRIPT , Can anyone tell me the solution for this or anyother way to create confirm box with "yes" or "no" button?...
0
by: grego9 | last post by:
I am trying to insert a new blank row above any row in my excel spreadsheet that has the text "NO" in column O. The macro I have written (below) works fine - apart from when there are two or three...
6
by: RSbroman | last post by:
I have created an append query that I would like to run when the DB is opened. However I do not want the end user to receive the "yes" "no" confirmation box when the query is being run. Can...
4
by: senthilkumarb | last post by:
Hi every body, i need a snippet in JavaScript to perform close window(browser) when we close window it should give alert with "YES" & "NO" button if yes the window should stay still otherwise...
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: 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...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.