How to Programmatically Add an Index To a Table
More Tutorials Articles
How
to Programmatically Add an Index To a Table
Author: Allen Beechick
Date Added: Monday Aug 29th, 2005 Category: Tutorials
How to Programmatically Add an Index To a Table
If your Microsoft Access database is split into front end and back end, how can you easily add an index to a table?
One solution is to use VBA code on the front end to modify table structure on the back end.
The function AddIndexToTable works both if the table is linked or local, because the code checks what kind of table it is.
The subroutine CallAddIndex has sample code to call the function.
Function AddIndexToTable(ByVal TblName As String, IndexName As String, IsPrimary As Boolean, _
IsUnique As Boolean, ParamArray FldNames()) As Boolean
Dim Idx As Index
Dim Td As TableDef
Dim DbPath As Variant
Dim Db As Database
Dim FldNum As Integer
On Error Resume Next
DbPath = DLookup("Database", "MSysObjects", "Name='" & TblName & "' And Type=6")
If IsNull(DbPath) Then
Set Db = CurrentDb
Else
Set Db = OpenDatabase(DbPath)
If Err <> 0 Then
Exit Function
End If
TblName = DLookup("ForeignName", "MSysObjects", "Name='" & TblName & "' And Type=6")
End If
Set Td = Db.TableDefs(TblName)
If Err <> 0 Then
GoTo Done
End If
With Td
On Error Resume Next
Set Idx = .Indexes(IndexName)
If Err = 0 Then GoTo Done
If Err > 0 Then
On Error Resume Next
Set Idx = .CreateIndex(IndexName)
With Idx
For FldNum = 0 To UBound(FldNames)
.Fields.Append .CreateField(FldNames(FldNum))
.IgnoreNulls = True
.Primary = IsPrimary
.Unique = IsUnique
Next
End With
.Indexes.Append Idx
End If
End With
If Err = 0 Then AddIndexToTable = True
Done:
End Function
Sub CallAddIndex()
Dim Result As Boolean
Result = AddIndexToTable("Table1", "MyIndex", False, True, "Field1", "Field2")
Debug.Print Result
End Sub
Download this code and other back end functions as a .bas file ready to import into your database.
|
|