场景: 1.包含链接表的Access数据库2.第二个Access数据库根据第一个数据库中链接表的结构接收新表3.代码如下:
Dim db As Database
Dim dbtemp As Database
Dim tblSrc As TableDef
Dim tblNew As TableDef
Dim fldSrc As Field
Dim fldNew As Field
Set db = CurrentDb()
Set dbtemp = OpenDatabase("C:\MSR DWA\CACHE\CacheTemp.mdb")
For Each tblSrc In db.TableDefs
If Not Left(tblSrc.Name, 4) = "MSys" Then
'Debug.Print tblSrc.Name
Set tblNew = dbtemp.CreateTableDef(tblSrc.Name)
For Each fldSrc In tblSrc.Fields
Set fldNew = tblNew.CreateField(fldSrc.Name, fldSrc.Type, fldSrc.Size)
On Error Resume Next
fldNew.Attributes = fldSrc.Attributes
fldNew.AllowZeroLength = fldSrc.AllowZeroLength
fldNew.DefaultValue = fldSrc.DefaultValue
fldNew.Required = fldSrc.Required
fldNew.Size = fldSrc.Size
tblNew.Fields.Append fldNew
On Error GoTo 0
Next
End If
dbtemp.TableDefs.Append tblNew
Next
代码将一直运行,直到在尝试创建上一个表时遇到第一个MSys表。这显然会导致错误:表已经存在..
我不明白为什么它似乎忽略了If语句中的条件并出错。
发布于 2011-06-29 08:18:46
dbtemp.TableDefs.Append tblNew
在If..End If
块之外。因此,您的代码将尝试每次通过外部For
循环执行该行...当前tblSrc.Name是否以"MSys“开头。
当你去掉大部分过程时,它会变得更清晰。
For Each tblSrc In db.TableDefs
If Not Left(tblSrc.name, 4) = "MSys" Then
End If
dbtemp.TableDefs.Append tblNew
Next
发布于 2011-06-28 19:25:40
更改您的代码
If Not Left(tblSrc.Name, 4) = "MSys" Then
至
If Left(tblSrc.Name, 4) <> "MSys" Then
我遇到了同样的问题,通过将其更改为上面的方法,它对我起作用了。
我使用下面的代码将两个Access数据库合并为一个副本。
Public Sub CombineDBs()
Dim appAccess As New Access.Application 'define the copy of the database to transfer to
Dim db As Database 'Database to import
Dim td As TableDef 'Tabledefs in db
Dim strTDef As String 'Name of table or query to import
Dim Const cDir_Database As String = "Location1" 'Access Location
appAccess.Visible = False
'opens the database that needs the tables and data added to it
appAccess.OpenCurrentDatabase "location"
'opens the database to import data from
Set db = OpenDatabase(cDir_Database)
'Import tables from specified Access database.
For Each td In db.TableDefs
strTDef = td.Name
If Left(strTDef, 4) <> "MSys" Then
appAccess.DoCmd.TransferDatabase acImport, "Microsoft Access", cDir_Database, acTable, strTDef, strTDef, False
End If
Next
appAccess.CloseCurrentDatabase
db.Close
End Sub
https://stackoverflow.com/questions/6505366
复制相似问题