2010-02-02 65 views

回答

2

我上週剛寫代碼,這對於一個應用程序:

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變量命名約定(例如,應該是LastName的txtLastName),我需要刪除所有這些。該代碼被稱爲是這樣的:

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 

所有這一切說,我d真的,非常強烈地建議你用而不是用空格替換下劃線,因爲這使得它更加難以使用SQL和代碼中的字段名稱。我會用CAMEL情況下,沒有下劃線或空格或破折號,以便將替換代碼()線以上將成爲:

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

這將轉換「姓氏」或「姓氏」,以「姓氏」。只要我在Access中進行編程(自1996年以來),字段名稱可讀性的駝峯案例就成爲Access開發人員的標準,並且避免了由特殊字符或空格造成的問題(即必須用方括號包圍字段名稱)。

相關問題