access數據庫中field對象的caption屬性(也就是標題)是用來設置數據字段的標題,在正常的數據庫設計中為了保持維護的便利性,許多開發者都將字段名與標題做了分別設置,標題往往比字段名更友好,更能說明字段的用途。本篇從另一個角度來說明如何用vba讀寫該屬性。
field對象的caption屬性并不是ado原生對象,而是“可由ado訪問的access屬性”,在幫助文檔中介紹了兩種訪問這個屬性的方法,一種利用ado,一種利用dao,由于在access2003及以前的版本中field對象并不是accessobject對象,因而也就沒有accessobjectproperties 屬性,所以我們也就不能在ado中去解決這個問題,現在用另一種方式來解決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對象 dim i as integer dim tmpprop as dao.property //強制使用dao類型 dim fld as dao.field //強制使用dao類型 dim tmptxt as string 'on error resume next dim msg as string dim cdb as dao.database //*****強制使用dao類型 set cdb = currentdb //****關鍵,確定對當前數據庫的靜態引用 set dset = cdb.tabledefs(tbname)//*****必須使用tabledef對象 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 |
在以上部分的代碼中有兩個sub,一個是setproperty ,用來判斷一個字段是否有指定的屬性,如果沒有設置,就將相應的數值賦給該屬性。另一個是displayclumcaption,這是對指定表中的字段按字段名設置其caption屬性的演示代碼。如果有需要,大家可以對setproperty進行修改,使他變成一個只讀的函數,用來枚舉指定表中每個字段的caption屬性。displayclumcaption代碼中,打“星號”的地方是要重點注意的,不然可能會在msdn中多走彎路。
新聞熱點
疑難解答