Create Excel Workbooks Using Access

foxhound

Board Regular
Joined
Mar 21, 2003
Messages
182
I am desperately seeking assistance on this one and will attempt to explain my situation. I need to create multiple Excel workbooks through code in Access 2000. My info is similar to that below.

I am trying to pull hierarchial information from table1, go to the top hierarchial name, find all rows (records) in that hierarchy tree and create separate worksheets within the same workbook for records in each "branch" of the tree. Hopefully, the "X's" below demonstrate what I am trying to accomplish. I need to loop through and create separate workbooks for each "branch" of the tree. So, "World.xls" would have a worksheet so named for every "hierarchy" and "Canada.xls" would only have one worksheet named "Canada."
Hierarchy.xls
ABCDEFGHIJ
1NumLocNumNumDescriptionWorld.xlsNorthAmerica.xlsUnitedStates.xlsWashington.xlsCanada.xlsEurope.xlsFrance.xls
217011701Worldx      
317021701NorthAmericaxx     
417031702UnitedStatesxxx    
517041703Washingtonxxxx   
617051704Redmondxxxx   
717061703NewYorkxxx    
817071706NewYorkCityxxx    
917081702Canadax   x  
1017091701Europex    x 
1117101709Francex    xx
1217111710Parisx    xx
table2
 

Excel Facts

Return population for a City
If you have a list of cities in A2:A100, use Data, Geography. Then =A2.Population and copy down.
Hello,

Okay, I revisited this one and have gotten this far. The details are different but it is the same concept. Can anyone else offer assistance? I apologize for this not being indented (I don't know how to post that way.)

Sub CreateTheExcelWorkbooks()

Dim db As DAO.Database
Dim List1 As DAO.Recordset
Dim List2 As DAO.Recordset
Dim List3 As DAO.Recordset
Dim List4 As DAO.Recordset
Dim List5 As DAO.Recordset
Dim List6 As DAO.Recordset

Set db = CurrentDb()

Set List1 = CurrentDb.OpenRecordset("Select DISTINCT [super] from [Employee Snapshot]")
List1.MoveFirst
Do Until List1.EOF
'Need code to open Excel Workbook named "Supervisor.xls"
ActiveWorkbook.SaveAs "C:\Temp\" & List1.Fields("EmpName") & ".xls" 'If last character is "." remove
'Need code to copy "sheet1" and name = Left(List1.fields ("EmpName"), InStr(1, List1.fields ("EmpName"), ",", 1) - 1)
'Need code to select all records in List1 and paste into this new sheet starting at row4
Set List2 = CurrentDb.OpenRecordset("SELECT * FROM [Employee Snapshot] WHERE [super] =" & List1![EmpNo])
List2.MoveFirst
Do Until List2.EOF
'Need code to copy "sheet1" and name = Left(List2.fields ("EmpName"), InStr(1, List2.fields ("EmpName"), ",", 1) - 1)
'if worksheet name already exists, name = Left(List2.fields ("EmpName"), InStr(1, List2.fields ("EmpName"), ",", 1) - 1) & "(1)" (increment this as needed)
'Need code to select all records in List2 and paste into this new sheet starting at row4
Set List3 = CurrentDb.OpenRecordset("SELECT * FROM [Employee Snapshot] WHERE [super] =" & List2![EmpNo])
List3.MoveFirst
Do Until List3.EOF
'Need code to copy "sheet1" and name = Left(List3.fields ("EmpName"), InStr(1, List3.fields ("EmpName"), ",", 1) - 1)
'if worksheet name already exists, name = Left(List3.fields ("EmpName"), InStr(1, List3.fields ("EmpName"), ",", 1) - 1) & "(1)" (increment this as needed)
'Need code to select all records in List3 and paste into this new sheet starting at row4
Set List4 = CurrentDb.OpenRecordset("SELECT * FROM [Employee Snapshot] WHERE [super] =" & List3![EmpNo])
List4.MoveFirst
Do Until List4.EOF
'Need code to copy "sheet1" and name = Left(List4.fields ("EmpName"), InStr(1, List4.fields ("EmpName"), ",", 1) - 1)
'if worksheet name already exists, name = Left(List4.fields ("EmpName"), InStr(1, List4.fields ("EmpName"), ",", 1) - 1) & "(1)" (increment this as needed)
'Need code to select all records in List4 and paste into this new sheet starting at row4
Set List5 = CurrentDb.OpenRecordset("SELECT * FROM [Employee Snapshot] WHERE [super] =" & List4![EmpNo])
List5.MoveFirst
Do Until List5.EOF
'Need code to copy "sheet1" and name = Left(List5.fields ("EmpName"), InStr(1, List5.fields ("EmpName"), ",", 1) - 1)
'if worksheet name already exists, name = Left(List5.fields ("EmpName"), InStr(1, List5.fields ("EmpName"), ",", 1) - 1) & "(1)" (increment this as needed)
'Need code to select all records in List5 and paste into this new sheet starting at row4
Set List6 = CurrentDb.OpenRecordset("SELECT * FROM [Employee Snapshot] WHERE [super] =" & List5![EmpNo])
'Need code to copy "sheet1" and name = Left(List6.fields ("EmpName"), InStr(1, List6.fields ("EmpName"), ",", 1) - 1)
'if worksheet name already exists, name = Left(List6.fields ("EmpName"), InStr(1, List6.fields ("EmpName"), ",", 1) - 1) & "(1)" (increment this as needed)
'Need code to select all records in List6 and paste into this new sheet starting at row4
List5.MoveNext
Loop
List4.MoveNext
Loop
List3.MoveNext
Loop
List2.MoveNext
Loop
ActiveWorkbook.Sheets(1).Delete
'need code to sort worksheets in ascending order
ActiveWorkbook.Close
'Activate "Supervisor.xls"
List1.MoveNext
Loop

List1.Close
List2.Close
List3.Close
List4.Close
List5.Close
List6.Close

Set List1 = Nothing
Set List2 = Nothing
Set List3 = Nothing
Set List4 = Nothing
Set List5 = Nothing
Set List6 = Nothing

Set db = Nothing

End Sub
 
Upvote 0
Hi,

First of all, to post formatted code use the BB code tags. Click the Code button which appears above the texbox when you're composing/editing a message, then paste your code and click the Code button again to close the tag.

There's a lot of stuff you're asking for here so I'll take it a few steps at a time...



If you're running this code in Access then you can't just refer to Excel objects (e.g. ActiveWorkbook) without qualifying them. Access does not know what Activeworkbook is. This code will get an instance of Excel.

Code:
Function GetExcel() As Excel.Application
'Returns a reference to the Excel application.
    On Error Resume Next
    Set GetExcel = GetObject(, "Excel.Application")
    If Err.Number <> 0 Then
        Set GetExcel = New Excel.Application
    End If
End Function

And this is how the first part of your code might look (to open the Supervisor.xls file):-

Code:
    Dim xlApp As Excel.Application
    Dim xlWb As Excel.Workbook

    Set xlApp = GetExcel


    Set db = CurrentDb()

    Set List1 = CurrentDb.OpenRecordset("Select DISTINCT [super] from [Employee Snapshot]")
    List1.MoveFirst
    Do Until List1.EOF
        'Need code to open Excel Workbook named "Supervisor.xls"
        
        Set xlWb = xlApp.Workbooks.Open("C:\some folder\Supervisor.xls")
        xlWb.SaveAs "C:\Temp\" & List1.Fields("EmpName") & ".xls"    'If last character is "." remove

To copy a sheet in Excel and rename it use something like this:

Code:
Dim sht As Worksheet

Sheets("Sheet1").Copy before:=Sheets("Sheet1")
Set sht = ActiveSheet
sht.Name = "My sheet"

To copy a recordset into an Excel worksheet use the CopyFromRecordset method e.g.

sht.Range("A4").CopyFromRecordset List2

This code will paste the contents of the List2 recordset into the 'sht' worksheet starting at range A4.

That should get you going. Let me know how you get on fixing up this lot.
 
Upvote 0
Dan,

Thank you very much for looking at this. Here is where I am so far. And, thanks to your instructions, it should look much cleaner :biggrin: The code works fine until list3 then it does not pull records using fields.super from list2.

Code:
Sub CreateTheExcelWorkbooks()
Dim xlApp As Excel.Application
Dim xlWb As Excel.Workbook
Dim xlsht As Worksheet
Dim db As DAO.Database
Dim List1 As DAO.Recordset
Dim List2 As DAO.Recordset
Dim List3 As DAO.Recordset
'Dim List4 As DAO.Recordset
'Dim List5 As DAO.Recordset
'Dim List6 As DAO.Recordset

    Set xlApp = GetExcel
    Set db = CurrentDb()

    Set List1 = CurrentDb.OpenRecordset("Select DISTINCT [super] from [Employee Snapshot]")
    List1.MoveFirst
    Do Until List1.EOF
        Set List2 = CurrentDb.OpenRecordset("Select * from [Employee Snapshot]where [super]=" & List1.Fields("super"))
        'Opens Excel Workbook named "Supervisor.xls"
        Set xlWb = xlApp.Workbooks.Open("C:\Temp\Supervisor.xls")
        xlWb.SaveAs "C:\Temp\" & (DLookup("[NAME]", "Employees", "[EmpNo]=" & List1.Fields("super"))) & ".xls"
        '*** need code If last character is "." then remove***
        Sheets("Sheet1").Copy before:=Sheets("Sheet1")
        Set xlsht = ActiveSheet
        xlsht.NAME = Left(DLookup("[NAME]", "Employees", "[EmpNo]=" & List1.Fields("super")), InStr(1, DLookup("[NAME]", "Employees", "[EmpNo]=" & List1.Fields("super")), ",", 1) - 1)
        xlsht.Range("A4").CopyFromRecordset List2
'''''good above this
        On Error Resume Next
        Set List3 = CurrentDb.OpenRecordset("Select * from [Employee Snapshot]where [super]=" & List2.Fields("super"))
        Do Until List2.EOF
        List2.MoveFirst
        Sheets("Sheet1").Copy before:=Sheets("Sheet1")
        Set xlsht = ActiveSheet
        xlsht.NAME = Left(DLookup("[NAME]", "Employees", "[EmpNo]=" & List2.Fields("super")), InStr(1, DLookup("[NAME]", "Employees", "[EmpNo]=" & List2.Fields("super")), ",", 1) - 1)
        xlsht.Range("A4").CopyFromRecordset List3
        List2.MoveNext
        Loop
'''''good below this
        xlApp.DisplayAlerts = False
        Sheets("Sheet1").Delete
        xlApp.DisplayAlerts = True
        ActiveWorkbook.Save
        ActiveWorkbook.Close
        List1.MoveNext
        Loop
List1.Close
List2.Close
List3.Close
'List4.Close
'List5.Close
'List6.Close

Set List1 = Nothing
Set List2 = Nothing
Set List3 = Nothing
'Set List4 = Nothing
'Set List5 = Nothing
'Set List6 = Nothing

Set db = Nothing
Set xlApp = Nothing

End Sub
 
Upvote 0
Hello again,

You should get rid of the On Error Resume Next just above the Set List3 bit. You should then be able to see if there is an error in your code. With the error trapping there you've got no hope of working out what's going wrong.

Let me know how you get on,
Dan
 
Upvote 0
Hi Dan,

Sometimes there will be no records that exist for the "super" in list2. Is there a better way to exit the list3 loop and fall back into the list2 loop? That is why I put the "on error resume next" there.

:) Foxhound
 
Upvote 0
You can test for an empty recordset by testing its BOF and EOF properties and seeing if they're both true. If a recordset is at the beginning and the end then there must be no records. Here's an example:-

Code:
Sub TestForEmptyRecordset()
    Dim List2 As DAO.Recordset

    Set List2 = CurrentDb.OpenRecordset("SELECT * FROM EMT WHERE LLD Like '272*'")

    If List2.BOF And List2.EOF Then
        MsgBox "The recordset is empty."
    Else
        MsgBox "The recordset is not emtpy."
    End If

    List2.Close
    Set List2 = Nothing

End Sub

You should be able to incorporate this into your code and avoid the error trapping, which is certainly a good thing while you're developing this as you'll be able to pinpoint potential errors in your code.
 
Upvote 0
Okay, I am having a difficult time with list3. I can't make it past selecting the records to test for "If List3.BOF And List3.EOF Then" because I keep getting the error, "no current records." It is true that there are no records in [Employee Snapshot] with some of the [super]'s but I don't think it is even recognizing the [super] field from list2.

So with the posted code, workbooks are being created and saved correctly for all records belonging to each [super] from list2 but it is not pulling records from [Employee Snapshot] in the later loops because they aren't being recognized.

Any suggestion :biggrin:
 
Upvote 0

Forum statistics

Threads
1,221,590
Messages
6,160,668
Members
451,662
Latest member
reelspike

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top