MS Access:以编程方式重命名列

时间:2010-02-02 16:38:30

标签: database ms-access database-design

我需要更新8个表的Access数据库中的所有列名。简而言之,列名中的每个下划线应替换为空格。你能推荐一种快速的方法吗?

2 个答案:

答案 0 :(得分:4)

您是否尝试使用TableDefs

DatabaseName.TableDefs("TableName").Fields("FieldName").Name = "NewName"

http://msdn.microsoft.com/en-us/library/bb220949.aspx

答案 1 :(得分:4)

上周我为一个应用程序编写了代码:

  Public Sub RenameFields(ByRef tdf As DAO.TableDef)
    Dim fld As DAO.Field
    Dim strFieldName As String
    Dim strNewName As String

    Debug.Print "==============================================" & vbCrLf & UCase(tdf.Name)
    For Each fld In tdf.Fields
      strFieldName = fld.Name
      strNewName = Mid(strFieldName, 4)
      Select Case Left(strFieldName, 3)
        Case "boo", "byt", "cur", "dat", "hyp", "int", "mem", "obj", "txt"
          fld.Name = strNewName
          Debug.Print tdf.Name & "." & strFieldName & "=>" & strNewName
      End Select
    Next fld
    Set fld = Nothing
  End Sub

在这种情况下,前一个开发人员愚蠢地使用字段名称的VBA变量命名约定(例如,txtLastName应该是LastName),我需要删除所有这些。代码的调用方式如下:

  Dim tdf As DAO.TableDef

  For Each tdf in CurrentDB.TableDefs
    If Left(tdf.Name,3) = "tbl" Then ' <= this line may differ for you
       Call RenameFields(tdf)
    End If
  Next tdf
  Set tdf = Nothing

您可以轻松调整RenameFields()子项以使用Replace()作为新名称,如下所示:

  Public Sub RenameFields(ByRef tdf As DAO.TableDef)
    Dim fld As DAO.Field
    Dim strFieldName As String
    Dim strNewName As String

    Debug.Print "==============================================" & vbCrLf & UCase(tdf.Name)
    For Each fld In tdf.Fields
      strFieldName = fld.Name
      strNewName = Replace(strFieldName, "_"," ")
      If strFieldName <> strNewName Then
         fld.Name = strNewName
         Debug.Print tdf.Name & "." & strFieldName & "=>" & strNewName
      End If
    Next fld
    Set fld = Nothing
  End Sub

所有这一切,我真的,非常强烈地建议您用空格替换下划线,因为这使得使用SQL中的字段名称变得更加困难。码。我会使用没有下划线或空格或破折号的CAMEL案例,以便上面代码中的Replace()行变为:

  strNewName = Replace(StrConv(Replace(strFieldName, "_"," "), vbProper)," ", vbNullString)

这会将“Last_Name”或“last_name”转换为“LastName”。用于字段名称可读性的Camel案例已经成为Access开发人员的标准,只要我在Access中编程(自1996年以来),并避免由特殊字符或空格引起的问题(即,必须用方括号括起字段名称) )。