-
When you've got some queries defined in Access. Maybe try this one. Don't promise a thing but you could try.[VBA]Sub GetQueryDef()
'This sub will get data from an Existing QueryDef in
'database and place the data on sheet2.
Dim Db As Database
Dim Qd As QueryDef
Dim Rs As Recordset
Dim Ws As Worksheet
Dim i As Long
Dim Path As String
'Set the Path to the database
Path = "C:\yourfiledirectory\Sales and whatever.mdb"
'Set Ws
Set Ws = Sheets("Sheet2")
Ws.Activate
Range("A1").Activate
Selection.CurrentRegion.Select
Selection.ClearContents
Range("A1").Select
'Set the Database and QueryDef. This QueryDef exists in the
'database.
Set Db = Workspaces(0).OpenDatabase(Path, ReadOnly:=True, _
Exclusive:=False)
'replace the name of your query with the real name
Set Qd = Db.QueryDefs("The name of your query")
'Create a new Recordset from the Query based on the stored
'QueryDef.
Set Rs = Qd.OpenRecordset()
'This loop will collect the field names and place them in the first
'row starting at "A1."
For i = 0 To Rs.Fields.Count - 1
Ws.Cells(1, i + 1).Value = Rs.Fields(i).Name
Next i
'This line simply sets the font to bold for the headers.
Ws.Range(Ws.Cells(1, 1), Ws.Cells(1, Rs.Fields.Count)).Font.Bold = True
'The next line will get the data from the recordset and copy it
'into the Worksheet (Sheet2).
Ws.Range("A2").CopyFromRecordset Rs
'This next code set will just select the data region and auto-fit
'the columns
Ws.Select
Range("A1").Select
Selection.CurrentRegion.Select
Selection.Columns.AutoFit
Range("A1").Select
Qd.Close
Rs.Close
Db.Close
End Sub[/VBA]
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules