open excel worksheet from code

J

James

I have written a small program which cycles through a number of linked tables
in my DB to build a single flat table of all the data. This works fine,
except the DB is quite large in size, as all the linked tables are there
along with the large flat file. Would it be possible to open the excel
worksheets one by one as recordsets and compile the flat file this way,
instead of having to link them all into the DB??? Below is my code: (Access
2003)

Private Sub Command2_Click()

Dim db As Database
Dim rs As Recordset
Dim datars As Recordset
Dim tbl As TableDef
Dim str As String
Dim nmb As Integer
Dim rl As Relation

Set db = CurrentDb
Set rl = Nothing

For Each rl In db.Relations
str = rl.name
If str = "First" Or rl.name = "Second" Then
db.Relations.Delete (str)
End If
Next rl


'Delete Old Stats Table
For Each tbl In db.TableDefs
str = tbl.name
If str = "Stats" Then
db.TableDefs.Delete ("Stats")
End If
Next tbl

'Create Stats Table
Set tdf = db.CreateTableDef("Stats")
Set fld1 = tdf.CreateField("StatID", dbLong)
Set fld2 = tdf.CreateField("ItemName", dbText)
Set fld3 = tdf.CreateField("StatDate", dbDate)
Set fld4 = tdf.CreateField("StatValue", dbDouble)

With fld1
.Attributes = .Attributes Or dbAutoIncrField
End With

tdf.Fields.Append (fld1)
tdf.Fields.Append (fld2)
tdf.Fields.Append (fld3)
tdf.Fields.Append (fld4)

db.TableDefs.Append (tdf)

'Create List of Stats
For Each tbl In db.TableDefs

If tbl.Attributes = 1073741824 And tbl.name <> "LegendTables" Then

str = tbl.name

Set datars = db.OpenRecordset(str)
Set rs = db.OpenRecordset("Stats")

For nmb = 1 To datars.Fields.Count - 1
Do Until datars.EOF = True
With rs
.AddNew
!ItemName = tbl.name & "_" & datars.Fields(nmb).name
!StatDate = datars!Date
!StatValue = datars.Fields(nmb).Value
.Update
End With
datars.MoveNext
Loop
datars.MoveFirst
Next nmb

End If
Next tbl

Set tbl = Nothing
Set rs = Nothing
Set tdf = Nothing

'Create Primary Key
db.TableDefs.Refresh
Set tbl = db.TableDefs("Stats")
Set ind = tbl.CreateIndex("PrimaryKey")
With ind
.Fields.Append .CreateField("StatID")
.Unique = False
.Primary = True
End With
tbl.Indexes.Append ind

MsgBox ("Stats Table Created")
Call Command0_Click
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top