ACCESS中Field對(duì)象的標(biāo)題屬性

字號(hào):

ACCESS數(shù)據(jù)庫中Field對(duì)象的caption屬性(也就是標(biāo)題)是用來設(shè)置數(shù)據(jù)字段的標(biāo)題,在正常的數(shù)據(jù)庫設(shè)計(jì)中為了保持維護(hù)的便利性,許多開發(fā)者都將字段名與標(biāo)題做了分別設(shè)置,標(biāo)題往往比字段名更友好,更能說明字段的用途。本篇從另一個(gè)角度來說明如何用VBA讀寫該屬性。
    Field對(duì)象的CAPTION屬性并不是ADO原生對(duì)象,而是“可由ADO訪問的ACCESS屬性”,在幫助文檔中介紹了兩種訪問這個(gè)屬性的方法,一種利用ADO,一種利用DAO,由于在ACCESS2003及以前的版本中Field對(duì)象并不是ACCESSObject對(duì)象,因而也就沒有AccessObjectProperties 屬性,所以我們也就不能在ADO中去解決這個(gè)問題,現(xiàn)在用另一種方式來解決DAO的代碼。
    Sub SetProperty(dbsTemp As DAO.Field, strName As String, _
     booTemp As String)
     Dim prpNew As DAO.Property
     Dim errLoop As Error
     ' Attempt to set the specified property.
     On Error GoTo Err_Property
     dbsTemp.Properties(strName) = booTemp
     On Error GoTo 0
     Exit Sub
    Err_Property:
     ' Error 3270 means that the property was not found.
     If DBEngine.Errors(0).Number = 3270 Then
    ' Create property, set its value, and append it to the
    ' Properties collection.
    Set prpNew = dbsTemp.CreateProperty(strName, _
      dbText, booTemp)
    dbsTemp.Properties.Append prpNew
    Resume Next
     Else
    ' If different error has occurred, display message.
    For Each errLoop In DBEngine.Errors
      MsgBox "Error number: " & errLoop.Number & vbCr & _
     errLoop.Description
    Next errLoop
    End
     End If
    End Sub
    Sub DisplayClumCaption(ByVal tbname As String,
    ByVal fldIndex As Integer)
    Dim dset As DAO.TableDef) //*****必須使用TableDef對(duì)象
    Dim i As Integer
    Dim tmpProp As DAO.Property  //強(qiáng)制使用DAO類型
    Dim fld As DAO.Field  //強(qiáng)制使用DAO類型
    Dim tmpTxt As String
    'On Error Resume Next
    Dim msg As String
    Dim cdb As DAO.Database //*****強(qiáng)制使用DAO類型
    Set cdb = CurrentDb //****關(guān)鍵,確定對(duì)當(dāng)前數(shù)據(jù)庫的靜態(tài)引用
    Set dset = cdb.TableDefs(tbname)//*****必須使用TableDef對(duì)象
    For Each fld In dset.Fields
    tmpTxt = fld.Name
    SetProperty fld, "Caption", tmpTxt
    msg = msg + fld.Properties("Caption")
    msg = msg + Chr(10) + Chr(13)
    Next fld
    MsgBox msg
    End Sub
    在以上部分的代碼中有兩個(gè)SUB,一個(gè)是SetProperty ,用來判斷一個(gè)字段是否有指定的屬性,如果沒有設(shè)置,就將相應(yīng)的數(shù)值賦給該屬性。另一個(gè)是DisplayClumCaption,這是對(duì)指定表中的字段按字段名設(shè)置其CAPTION屬性的演示代碼。如果有需要,大家可以對(duì)SetProperty進(jìn)行修改,使他變成一個(gè)只讀的函數(shù),用來枚舉指定表中每個(gè)字段的CAPTION屬性。DisplayClumCaption代碼中,打“星號(hào)”的地方是要重點(diǎn)注意的,不然可能會(huì)在MSDN中多走彎路。