简体   繁体   中英

using vba to change field name in access 2007

I receive data monthly from an external company and need to change the field name to a sequential number. example contract 11 15 17 to 1 2 3. I am trying to use the following code but get an error that I cannot define the field more than once at "fld.Name = (n) + 1". How can I correct this?

Function ChangeFieldName()

Dim db As DAO.Database
Dim tbl As DAO.TableDef
Dim fld As DAO.Field
Dim n As Integer

Set db = CurrentDb
Set tbl = db.TableDefs("tdf1")

On Error Resume Next

n = 0
For Each fld In tbl.Fields
    fld.Name = (n) + 1
Next fld

Set fld = Nothing
Set tbl = Nothing
Set db = Nothing

End Function

That code attempts to rename each field to n + 1 , but since n is never incremented, it actually attempts to rename every field to 1 . The following change may do what you want.

n = 1
For Each fld In tbl.Fields
    fld.Name = n
    n = n + 1
Next fld

However there are some other issues you should consider with that approach. The For Each loops through the fields based on fld.OrdinalPosition . If your numbered field names were not defined in the order you expect, you will have a problem. For example, these fields in OrdinalPostion order: 11; 15; 2. In that case 11 would be renamed to 1, but the code would throw an error when attempting to rename 15 to 2.

Also that code will attempt to rename every field to a number. If the table only contains numbered field names, that may not be a problem. But if the table also contains other field names you wish to preserve, you've got more work to do.

A minor point is that fld.Name is text type. When you attempt to rename a field to a number, Access actually uses the number's string equivalent. That may be fine, but I would prefer to explicitly cast the number to a string myself.

fld.Name = CStr(n)

Finally please reconsider this ...

On Error Resume Next

That instructs Access to silently ignore all errors. I think you should get rid of that and add a proper error handler code block instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM