VBA for adding and renaming fields in tables already in use.

L

Louverril

I need to add some fields to existing data tables (and do one rename).

I believe you can do this using OpenDatabase() and CreateField() and one for
renaming? I have looked at the VBA help for these commands and can't figure
out how I could create a field and its attributes (field size etc.)

Can anyone point me in the right direction to use the above method or
suggest a better way.

I could do the changes manually but I know this will happen again with other
systems and I would like an automated solution. Also the risk of doing it on
site manually is too high.

Thanks
Lou
 
K

Ken Sheridan

Louverril said:
I need to add some fields to existing data tables (and do one rename).

I believe you can do this using OpenDatabase() and CreateField() and one for
renaming? I have looked at the VBA help for these commands and can't figure
out how I could create a field and its attributes (field size etc.)

Can anyone point me in the right direction to use the above method or
suggest a better way.

I could do the changes manually but I know this will happen again with other
systems and I would like an automated solution. Also the risk of doing it on
site manually is too high.

Thanks
Lou
 
K

Ken Sheridan

Sorry about the empty reply!

The following example would create a text field MyNewColumn of 20 characters
size in the table MyTable in the current database:

Dim dbs As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field

Set dbs = CurrentDb
Set tdf = dbs.TableDefs("MyTable")
With tdf
Set fld = .CreateField("MyNewColumn", dbText)
fld.Size = 20
.Fields.Append fld
End With

Note that with number data types you do not set the Size property, unlike in
table design view. Instead use the relevant data type constant as the second
argument of the CreateField method, dbLong.dbInteger, dbDouble etc.

For an external database return a reference to it with the OpenDatabase
method instead of using CurrentDb.

To rename a column use a function like this:

Public Sub RenameColumn(strtable As String, strOldName As String, strNewName
As String)

Dim dbs As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field

Set dbs = CurrentDb
Set tdf = dbs.TableDefs(strtable)
Set fld = tdf.Fields(strOldName)

fld.Name = strNewName

End Sub

Ken Sheridan
Stafford, England
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top