You can find the previous parts of this message here:
Copying Access Tables / Data using VBA Real World Case – Part 1 | Access JumpStart
Copying Access Tables / Data using VBA Real World Case – Part 2 | Access JumpStart
In Part 3 I discovered that the copied tables using this method had no indexed fields and no primary keys, I suspect the autonumber field was not autonumber any more as well, but I didn’t check that.
So I needed to not just SELECT INTO a table, but actually create a duplicate copy of the table structure including the indexes and field types.
Initially I tried to just create a new TableDef in the target database by using:
TableDefs.Append SourceDB.TabledDefs(SourceTableName)
However, this just tried to put the same object into the source database using the same connection properties that were in the new database. This did not and could not work. I need to replicate the fields and indexes collections in a new table.
Because I knew exactly what I wanted I was able to craft a pretty specific prompt for CoPilot and had a basic function to do what I needed to replicate the fields. I had to tell it to add the indexes for the fields which gave me about what I needed, which I was able to tweak to get to be exactly what I needed.
So here is the main function, updated with the new code:
And unveiling the new function:
So you can see it deletes then creates the new TableDef as a blank one in the target database, then loops over the fields and indexes and uses those to create the same structure from the source TableDef.