VBA Brush Up 11:Creating and Accessing Tables and Fields with ADO

Technorati 标签: , , , error handler

来自:Julitta Korol,“Access.2003.Programming.by.Example.with.VBA.XML.and.ASP”,by Wordware Publishing, Inc. 2005, p194-p211

In this chapter you will use the ADOX library to programmatically create tables and add new fields.

(1)

adox object model

(2)The Catalog object is extremely important as it represents an entire database and contains database tables, columns, indexes, groups, users, procedures, and views.

(3)The following steps outline the process of creating a new Microsoft Access table:

1. Declare the variables representing the Connection, Catalog, and Table objects:

  1. Dim conn As ADODB.Connection 
  2. Dim cat As ADOX.Catalog 
  3. Dim tbl As ADOX.Table 

2. Open the connection to your database:

  1. set conn = New ADODB.Connection 
  2. conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ 
  3.     "Data Source=C:/NewAccessDb.mdb" 

3. Supply the open connection to the ActiveConnection property of the ADOX Catalog object:

  1. Set cat = New ADOX.Catalog 
  2. set cat.ActiveConnection = conn 

4. Create a new Table object:

  1. Set tbl = New ADOX.Table 

5. Provide the name for your table:

  1. tbl.Name = "tblAssets" 

The Table object is a member of the Tables collection, which in turn is a member of the Catalog object. Each Table object has a Name property and a Type property. The Type property specifies whether a Table object is a standard Microsoft Access table, a linked table, a system table, or a view.

6. Append the Table object to the Catalog object’s Tables collection:

  1. cat.Tables.Append tbl 

At this point your table is empty.

7. Add new fields (columns) to your new table:

  1. With tbl.Columns 
  2.     .Append "SiteId", adVarWChar, 10 
  3.     .Append "Category", adSmallInt 
  4.     .Append "InstallDate", adDate 
  5. End With

You can create new fields in a table by passing the Column object Name, Type, and DefinedSize properties as arguments of the Columns collection’s Append method.

The Table object contains the Columns collection that contains Column objects. To add a new field to a table you could create a Column object and write the following code:

  1. Dim col As ADOX.Column 
  2. set col = New ADOX.Column 
  3. With col 
  4.     .Name = "SiteId" 
  5.     .DefinedSize = 10 
  6. End With 
  7. tbl.Columns.Append col

Creating fields in this manner takes longer and is less efficient than using the method demonstrated earlier.

(4)Notice that ADOX uses different data types than those used in the Access user interface

adox data types

(5)

  1.     On Error GoTo ErrorHandler
  2.     ……
  3.     cat.Tables.Append myTbl
  4.     ……
  5.     Exit Sub
  6. ErrorHandler: 
  7.     If Err.Number = -2147217857 Then 
  8.         cat.Tables.Delete "tblFilters" 
  9.         Resume 
  10.     End If 
  11.     MsgBox Err.Number & ": " & Err.Description

(6)SQL SELECT…INTO statement: select all records from one table into a new table. This statement creates a new table and inserts data from other tables. To copy a table, the SQL statement is passed as the first argument of the Execute method of the Connection object. Note that the copied table will not have the indexes that may exist in the original table.

  1. Sub Copy_Table()
  2.     Dim conn As ADODB.Connection 
  3.     Dim strTable As String 
  4.     Dim strSQL As String
  5.     On Error GoTo ErrorHandler
  6.     strTable = "Customers"
  7.     strSQL = "SELECT " & strTable & ".* INTO " 
  8.     strSQL = strSQL & strTable & "Copy " 
  9.     strSQL = strSQL & "FROM " & strTable 
  10.     Debug.Print strSQL
  11.     Set conn = New ADODB.Connection 
  12.     conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ 
  13.         "Data Source=" & CurrentProject.Path & _ 
  14.         "/Northwind.mdb" 
  15.     conn.Execute strSQL 
  16.     conn.Close 
  17.     Set conn = Nothing 
  18.     MsgBox "The " & strTable & " table was copied." 
  19.     Exit Sub
  20. ErrorHandler: 
  21.     If Err.Number = -2147217900 Then 
  22.         conn.Execute "DROP Table " & strTable 
  23.         Resume 
  24.     Else 
  25.         MsgBox Err.Number & ": " & Err.Description 
  26.     End If
  27. End Sub

(7)Deleting a Database Table: You can delete a table programmatically by opening the ADOX Catalog object, accessing its Tables collection, and calling the Delete method to remove the specified table from the Tables collection.

  1. Sub Delete_Table(strTblName As String)
  2.     Dim cat As ADOX.Catalog 
  3.     On Error GoTo ErrorHandler
  4.     Set cat = New ADOX.Catalog 
  5.     cat.ActiveConnection = CurrentProject.Connection 
  6.     cat.Tables.Delete strTblName 
  7.     Set cat = Nothing 
  8.     Exit Sub
  9. ErrorHandler: 
  10.     MsgBox "Table '" & strTblName & _ 
  11.         "' cannot be deleted " & vbCrLf & _ 
  12.     v"because it does not exist." 
  13.     Resume Next
  14. End Sub

(8)Removing a Field from a Table:access the ADOX Columns collection of a Table object and use the Columns collection Delete method to remove a field from a table.

  1. cat.ActiveConnection = CurrentProject.Connection 
  2. cat.Tables("tblFilters").Columns.Delete "Type"

A run-time error will occur if you attempt to delete a field that is part of an index.

(9)Retrieving Table Properties

  1. Dim pr As ADOX.Property
  2. ……
  3. Set tbl = cat.Tables("tblFilters")
  4. ' retrieve table properties 
  5. For Each pr In tbl.Properties 
  6.     Debug.Print tbl.Name & ": " & _ 
  7.         pr.Name & "= "; pr.Value 
  8. Next 
  9. Set cat = Nothing
  10. ……

table properties

(10)Retrieving Field Properties

  1. Dim col As ADOX.Column 
  2. Dim pr As ADOX.Property
  3. ……
  4. Set col = New ADOX.Column 
  5. Set col = cat.Tables("tblFilters").Columns("Id")
  6. ……
  7. For Each pr In col.Properties 
  8. Debug.Print pr.Name & "="; pr.Value 
  9. Next
  10. …… 

Field Properties

(11)Linking a Microsoft Access Table:In Microsoft Office Access 2003, you can create links to tables in Access databases as well as other data formats supported by Microsoft Jet’s installable drivers (for example: Excel, dBASE, Paradox, Exchange/Outlook, Lotus, Text, and HTML) and ODBC drivers.

  1. ……
  2. strDb = CurrentProject.Path & "/Northwind.mdb" 
  3. strTable = "Employees" 
  4. Set cat = New ADOX.Catalog 
  5. cat.ActiveConnection = CurrentProject.Connection
  6. Set lnkTbl = New ADOX.Table 
  7. With lnkTbl
  8.     ' Name the new Table and set its ParentCatalog property to the 
  9.     ' open Catalog to allow access to the Properties collection. 
  10.     .Name = strTable 
  11.     Set .ParentCatalog = cat
  12.     ' Set the properties to create the link 
  13.     .Properties("Jet OLEDB:Create Link") = True 
  14.     .Properties("Jet OLEDB:Link Datasource") = strDb 
  15.     .Properties("Jet OLEDB:Remote Table Name") = strTable 
  16. End With
  17. ' Append the table to the Tables collection 
  18. cat.Tables.Append lnkTbl
  19. Set cat = Nothing

(12)Linking a Microsoft Excel Spreadsheet:You can link an Excel spreadsheet to a Microsoft Access database by using the TransferSpreadsheet method of the DoCmd object. Note, however, that neither the DoCmd object nor its Transfer-Spreadsheet method are members of the ADO Object Model. The DoCmd object is built into the Microsoft Access library.

  1. Sub Link_ExcelSheet()
  2.     Dim rst As ADODB.Recordset 
  3.     DoCmd.TransferSpreadsheet acLink, _ 
  4.         acSpreadsheetTypeExcel8, _ 
  5.         "mySheet", _ 
  6.         CurrentProject.Path & "/Regions.xls", _ 
  7.         -1, _ 
  8.         "Regions!A1:B15"
  9.     Set rst = New ADODB.Recordset 
  10.     With rst 
  11.         .ActiveConnection = CurrentProject.Connection 
  12.         .CursorType = adOpenKeyset 
  13.         .LockType = adLockOptimistic 
  14.         .Open "mySheet", , , , adCmdTable 
  15.         End With 
  16.     Do Until rst.EOF 
  17.         Debug.Print rst.Fields(0).Value, rst.Fields(1).Value 
  18.         rst.MoveNext 
  19.     Loop 
  20.     rst.Close 
  21.     Set rst = Nothing
  22. End Sub 
The Link_ExcelSheet procedure begins by creating a linked table named mySheet from the specified range of cells (A1:B15), located in the Regions worksheet in the Regions.xls file. The –1 argument in the DoCmd statement indicates that the first row of the spreadsheet contains column headings. Next, the procedure uses the ADO Recordset object to retrieve the data from the mySheet table into the Immediate window. Notice that prior to opening the Recordset object, several properties of the Recordset object must be set.
    • The ActiveConnection property sets the reference to the current database.
    • The CursorType property specifies how the Recordset object should interact with the data source.
    • The adOpenKeyset setting tells Visual Basic that instead of retrieving all the records from the data source, only the keys are to be retrieved. The data for these keys is retrieved only as you scroll through the recordset. This guarantees better performance than retrieving big chunks of data at once.
    • The LockType property determines how to lock the data while it is being manipulated.
    • The adLockOptimistic setting locks the record only when you attempt to save it.
    • Opening the Recordset object also requires that you specify the data source. The data source in this procedure is the linked table named mySheet. The parameter passed depends on the source type used.
    • The adCmdTable setting indicates that all rows from the source table should be included.

You could also open the Recordset object by passing all the required parameters at once, as follows:

  1. rst.Open "mySheet", _ 
  2.     CurrentProject.Connection, adOpenKeyset, _ 
  3.     adLockOptimistic, adCmdTable

(13)Listing Database Tables: uses the ADOX Catalog object to gain access to the database, then iterates through the Tables collection to retrieve the names of Access tables, system tables, and views. The ADOX Tables collection stores various types of Table objects, as shown in Table 11-2

types of tables

  1. Set cat = New ADOX.Catalog 
  2. cat.ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ 
  3.     "Data Source=" & CurrentProject.Path & _ 
  4.     "/Northwind.mdb" 
  5. For Each tbl In cat.Tables 
  6.     If tbl.Type <> "VIEW" And _ 
  7.         tbl.Type <> "SYSTEM TABLE" And _ 
  8.         tbl.Type <> "ACCESS TABLE" Then Debug.Print tbl.Name 
  9. Next tbl 
  10. Set cat = Nothing

(14)Changing the AutoNumber:The AutoNumber is a unique sequential number (incremented by 1) or a random number assigned by Microsoft Access whenever a new record is added to a table. Microsoft Office Access 2003 allows you to set the start and step value of auto-increment fields programmatically by using Jet 4.0 SQL statements

(15)Listing Tables and Fields:To list tables in your database you can also use the OpenSchema method of the ADO Connection object

  1. Set rst = CurrentProject.Connection.OpenSchema(adSchemaTables)
  2. Do Until rst.EOF 
  3.     Debug.Print rst.Fields("TABLE_TYPE") & " ->" _ 
  4.         & rst.Fields("TABLE_NAME"
  5.     rst.MoveNext 
  6. Loop

Obtaining the names of fields requires that you use adSchemaColumns as the parameter for the OpenSchema method.

  1. Set rst = conn.OpenSchema(adSchemaColumns)
  2. Do Until rst.EOF 
  3.     curTable = rst!table_Name 
  4.     If (curTable <> newTable) Then 
  5.         newTable = rst!table_Name 
  6.         Debug.Print "Table: " & rst!table_Name 
  7.             counter = 1 
  8.     End If 
  9.     Debug.Print "Field" & counter & ": " & rst!Column_Name 
  10.     counter = counter + 1 
  11.     rst.MoveNext 
  12. Loop 
  13. rst.Close 
  14. conn.Close 
  15. Set rst = Nothing 
  16. Set conn = Nothing

(16)Listing Data Types:uses the adSchemaProvider-Types parameter of the ADO Connection object’s OpenSchema method to list the data types supported by the Microsoft Jet OLE DB 4.0 provider.

  1. Set conn=New ADODB.Connection 
  2. conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" _ 
  3.     & "Data Source=" & CurrentProject.Path & _ 
  4.     "/Northwind.mdb" 
  5. Set rst=conn.OpenSchema(adSchemaProviderTypes) 
  6. Do Until rst.EOF 
  7.     Debug.Print rst!Type_Name & vbTab _ 
  8.         & "Size: " & rst!Column_Size 
  9.     rst.MoveNext 
  10. Loop

(17)This chapter has shown you how to programmatically create Microsoft Access tables by using ActiveX Data Objects. You learned how to add fields to your tables and define field data types. You found out how to list both tables and fields, and investigate their properties. In addition to creating new tables from scratch, you discovered how to work with linked tables. You also learned how to copy tables and transfer data from a Microsoft Excel spreadsheet to an Access table.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值