使用MS Access VBA从“范围”创建表

时间:2013-08-22 11:08:30

标签: ms-access access-vba

我是VBA的MSAccess新手。我要做的是从每组名称创建一个新表,例如

Name  Email  Company

Abby  Abby@Time.com  Time    
BeeT  Beet@Share.com Share    
BeeT  Beet@Share.com Share    
BeeT  Beet@Share.com Share    
Carol Carol@Total.com Total    
Carol Carol@Total.com Total

我想要做的是从每个结算名称创建一个新表格,以便在这种情况下会有3个新表格,例如

Name  Email  Company

Abby  Abby@Time.com  Time
    
Name  Email  Company

BeeT  Beet@Share.com Share    
BeeT  Beet@Share.com Share    
BeeT  Beet@Share.com Share
    
Name  Email  Company

Carol Carol@Total.com Total    
Carol Carol@Total.com Total

1 个答案:

答案 0 :(得分:0)

有几种方法可以做到这一点。您实际上可以遍历表,如果表已经存在,那么您可以将数据附加到表中。如果没有,那么您可以创建一个新表。这涉及检查数据库对象的现有名称,并且工作量更大。

最简单的方法是为每个帐单名称创建一个表格,然后过滤原始表格以添加适当的行。

Dim db as Database
dim rec as Recordset
Dim rec2 as Recordset
Dim tbl As TableDef
Dim fld As Field
Dim fld2 as Field

Set db = CurrentDB
set rec = db.OpenRecordSet ("Select DISTINCT Company from YourTableName")

Do While rec.EOF = False
   Set rec2 = db.OpenRecordSet ("Select DISTINCT * from YourTableName WHERE Company = '" & 
   rec("Company") & "")
   Do While rec2.EOF = False
      Set tbl = dbs.CreateTableDef(Rec2("Company"))
      Set fld = tbl.CreateField(Rec2("Name"), dbText)
      Set fld2 = tbl.CreateField(Rec2("Email"), dbText)

      tbl.Fields.Append fld
      tbl.Fields.Append fld2
      db.TableDefs.Append tbl
      db.TableDefs.Refresh
      rec2.MoveNext
   Loop
   rec.MoveNext
Set rec2 = Nothing
Loop

Set db = Nothing
Set rec = Nothing
Set rec2 = Nothing