Question

How to create the use of multiple worksheets using Excel VBA ?

Asked by: zimmer9

I am developing an Access application with Excel VBA using Access 2003 as the front end and SQL Server as the back end database.

I use the following Attached Code Snippet containing 2 functions:
a) UDLIntToExcel()
b) ExportToExcels(filename As String)
to write out to an Excel file using Multiple Worksheets from an Access table.

Do you know how I could modify the following 2 functions
a) BranchDetailAll()
b) Calc_subtotals(filename)
using logic similar to the above function ExportToExcels(filename As String)
to write out to an Excel file using Mutiple Worksheets from an Access table

The problem with the following 2 functions is that they cannot handle > 65,535 records where Multiple Worksheets need to be used.

Private Sub BranchDetailAll()
    Dim cnn As ADODB.Connection
    Dim ExportedFile As String
    Dim strNextFile As String
    Dim rstQueryFS As ADODB.Recordset
    Dim objXL As Excel.Application
    Dim objWS As Excel.Worksheet
    Dim fld As ADODB.Field
    Dim intCol As Integer
    Dim intRow As Integer
    Dim strSQL As String
    Dim intBonds As Integer
    Dim com As ADODB.Command
    Dim P1 As New Parameter
    Dim intReport As Integer
    Const strTable = "tblDtlBranchAll"
    Set cnn = CurrentProject.Connection
    Dim cn As ADODB.Recordset
   
    Set cn = New ADODB.Recordset
   
    cn.ActiveConnection = CurrentProject.Connection
    cn.CursorType = adOpenStatic
    cn.CursorLocation = adUseServer
    cn.LockType = adLockReadOnly

    strSQL = "If  Exists(SELECT * FROM dbo.SYSOBJECTS WHERE NAME = 'tblDtlBranchAll' AND TYPE = 'U') DROP TABLE tblDtlBranchAll"
   
    cn.Open strSQL
   
    strSQL = "If  Exists(SELECT * FROM dbo.SYSOBJECTS WHERE NAME = 'tblDtlBrOrder' AND TYPE = 'U') DROP TABLE tblDtlBrOrder"
   
    cn.Open strSQL
       
    DoCmd.Hourglass True
       
    Set com = New ADODB.Command
    With com
       .CommandType = adCmdStoredProc
       .CommandText = "dbo.procNumberOfAccounts"
        Set .ActiveConnection = CurrentProject.Connection
       .Execute
    End With
   
    Set com = New ADODB.Command
    With com
       .CommandType = adCmdStoredProc
       .CommandText = "dbo.procDeleteBrAllRpt"
        Set .ActiveConnection = CurrentProject.Connection
       .Execute
    End With
   
    Set com = New ADODB.Command
    With com
       .CommandType = adCmdStoredProc
       .CommandText = "dbo.procDetailBranchAll"
       .Parameters.Append .CreateParameter("@Branch", adVarChar, adParamInput, 4, strBranch)
       Set .ActiveConnection = CurrentProject.Connection
       .Execute
    End With
   
    strSQL = "select OfficeNumber, CustomerNumber,DateRange,[Property Type],MarketValue into dbo.tblDtlBrOrder From dbo.tblDtlBranchAll order by DateRange Asc, CustomerNumber Asc, MarketValue Desc "
    cn.Open strSQL
   
    ExportedFile = "\\nydfs1\root\lib\CONTROLLERS\IIG\CASH_CONTROL\ccshared\AbandonedProperty\UDL\Access\Reconcile\DTLBRANCHALL" & "_" & intYearSP & "_" & Format(Now, "mmddhhnnss") & ".XLS"
    DoCmd.TransferSpreadsheet acExport, 8, "tblDtlBrOrder", ExportedFile, True, ""
   
    If isFileExist(ExportedFile) Then Calc_subtotals ExportedFile
   
    DoCmd.Hourglass False
End Sub

Private Sub Calc_subtotals(filename)
Dim str As String
Dim lastrow As Long
Dim i As Long
Dim rng As Range
Dim celle As Range
Dim str1 As String
Dim str2 As String
Dim rowe As Long
Dim temp As Double
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim xlWS As Excel.Worksheet
Set xlApp = New Excel.Application
xlApp.Visible = True
Set xlWB = xlApp.Workbooks.Open(filename)
Set xlWS = xlWB.Sheets(1)
xlApp.ScreenUpdating = False
rowe = 2
str1 = "A"
str2 = "E"
With xlWS
    Set rng = .Range(.Cells(rowe, str1), .Cells(.Cells.Rows.count, str2).End(xlUp))
End With
 
rng.Sort Key1:=xlWS.Range("C2"), Order1:=xlAscending, Key2:=xlWS.Range("B2") _
        , Order2:=xlAscending, Key3:=xlWS.Range("E2"), Order3:=xlAscending, Header:= _
        xlNo, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
        DataOption1:=xlSortNormal, DataOption2:=xlSortNormal, DataOption3:= _
        xlSortNormal
str = "B"
With xlWS
    lastrow = .Cells(.Cells.Rows.count, str).End(xlUp).Offset(1, 0).Row
 
For i = lastrow To 3 Step -1
    If .Cells(i, "B") <> .Cells(i - 1, "B") Then
        .Rows(i).Insert Shift:=xlDown
    End If
Next i
 
str = "B"
lastrow = .Cells(.Cells.Rows.count, str).End(xlUp).Offset(1, 0).Row
 
temp = 0
For i = 2 To lastrow
    temp = temp + Cells(i, 5)
    If Cells(i, 5) = "" Then
        Cells(i, 6) = temp
        temp = 0
        Cells(i, 1) = "Sub-total"
    End If
Next i
 
End With
 
xlWS.Columns("F:F").NumberFormat = "#,##0.00"
 
xlApp.ScreenUpdating = True
 
End Sub

Private Sub UDLIntToExcel()
    Dim cn As ADODB.Recordset
    Dim ExportedFile As String
    Dim ImportedFile As String
    Dim strNextFile As String
    Dim rstQueryFS As ADODB.Recordset
    Dim objXL As Excel.Application
    Dim objWS As Excel.Worksheet
    Dim fld As ADODB.Field
    Dim intCol As Integer
    Dim intRow As Integer
    Dim strSQL As String
    Dim intBonds As Integer
    Dim com As ADODB.Command
    Dim P1 As New Parameter
    Dim str_sql As String
    Dim filename As String
    Dim strAccessPath2 As String
              
    str_sql = "If  Exists(SELECT * FROM dbo.SYSOBJECTS WHERE NAME = 'tblRemedInternal' AND TYPE = 'U') DROP TABLE tblRemedInternal"
    DoCmd.RunSQL (str_sql)
    
    Set cn = New ADODB.Recordset
    
    cn.ActiveConnection = CurrentProject.Connection
    cn.CursorType = adOpenStatic
    cn.CursorLocation = adUseServer
    cn.LockType = adLockReadOnly
               
    DoCmd.Hourglass True
    Set com = New ADODB.Command
    With com
       .CommandTimeout = 95
       .CommandType = adCmdStoredProc
       .CommandText = "dbo.procRemedInternal2"
       .ActiveConnection = CurrentProject.Connection
       Set rstQueryFS = .Execute
    End With
              
    ExportedFile = strAccessPath0 & strAccessPath7 & "INTERNAL" & "_" & intYearSP & "_" & Format(Now, "mmddhhnnss") & ".XLS"
    
    ExportToExcels ExportedFile
    
    Beep
    MsgBox "Internal has been exported to Excel", vbOKOnly, ""
      
    If isFileExist(ExportedFile) Then StartDocInternalXLS ExportedFile
    DoCmd.Hourglass False
End Sub
 
Private Sub ExportToExcels(filename As String)
Dim str_sql As String
Dim cn As ADODB.Connection
Dim xl As Excel.Application
Dim xlWB As Excel.Workbook
Dim sht As Excel.Worksheet, rng As Excel.Range
Dim db As DAO.Database, rs As ADODB.Recordset
Dim recordtotal As Long
Dim SheetNum As Long
Dim dest As Range
Dim Counter As Long
Dim Source As Workbook
 
 
Set cn = CurrentProject.Connection
Set rs = New ADODB.Recordset
 
Set db = CurrentDb
 
recordtotal = DCount("ProdID", "tblRemedInternal")
Set xl = CreateObject("Excel.Application")
 
Set xlWB = xl.Workbooks.Add ' Add a new workbook
xlWB.SaveAs filename ' Save the new workbook as "filename"
Set xlWB = xl.Workbooks.Open(filename)  '<--Your Excel File Here
 
 
xl.Visible = True
SheetNum = 1
Do While recordtotal > 0
    rs.Open "Select top 60000 * from tblRemedInternal", cn, 2, 2
    If rs.EOF Then Exit Sub
    rs.MoveFirst
        Set sht = Nothing
        On Error Resume Next
        Set sht = xlWB.Worksheets("Sheet" & SheetNum)
        On Error GoTo 0
        
        If sht Is Nothing Then
        xlWB.Worksheets.Add After:=Worksheets(Worksheets.count)
            Set sht = ActiveSheet
            sht.Name = "Sheet" & SheetNum
        End If
        sht.Range("A1").CopyFromRecordset rs
        SheetNum = SheetNum + 1
        str_sql = "delete from tblRemedInternal where ProdID in(Select top 60000 ProdID from tblRemedInternal)"
        DoCmd.RunSQL (str_sql)
    rs.Close
    recordtotal = DCount("ProdID", "tblRemedInternal")
Loop
 
xlWB.Close (True)
xl.Quit
Set xl = Nothing
 
End Sub
                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-05-18 at 22:02:16ID23412781
Topics

Microsoft ADP

,

Microsoft Excel Spreadsheet Software

,

Access Coding/Macros

Participating Experts
1
Points
500
Comments
11

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. VBA Worksheet_Change
    I am trying to write a code that will log all the changed cells on a worksheet. My problem is that if I have a formula, say a sum formula on A10 for A1:A9 when I change one of the numbers in the range(A1:A9) worksheet_change doesn't pick up the address of the sum formula cell...
  2. refer to a worksheet by reference in VBA
    I need to refer to an Excel worksheet by a double reference, not by name, in my VBA code. I have a user-defined function in VBA that references a sheet to return the correct value. I would like this reference to the sheet to be variable, coming from a cell on the main workshe...
  3. Excel VBA: Cut from Worksheet 1 and Paste into Worksh…
    How do I programatically - 1. Cut a range of cells by shifting cells up 2. Append the range of cells into the end of another worksheet
  4. Combine Worksheets
    Hello: I am not fimilar with VBA coding .. I got following code from the website http://www.geopakistani.com/pics/files/combine1.xls It combines the worksheets... I want to modify it so that it only combines first two worksheets instead of all and when it combines the works...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: bigjokeyPosted on 2008-05-18 at 23:21:56ID: 21595516

So, are you saying that the following line will not allow more than 65,535 records?  And you want to export the data into multiple sheets, and then calculate the totals of the columns from the data across the multiple sheets?

DoCmd.TransferSpreadsheet acExport, 8, "tblDtlBrOrder", ExportedFile, True, ""


 

by: zimmer9Posted on 2008-05-19 at 04:47:51ID: 21596843

Using DoCmd.TransferSpreadsheet acExport, 8, "tblDtlBrOrder", ExportedFile, True, ""
creates the following records in an Excel file WITHOUT SUBTOTALS:

Branch             Customer Number   Date Range           Property Type       Value
004                   998111                   0 To 6 Months       Stocks                  18.00
004                   998111                   0 To 6 Months       Bonds                   12.25
004                   998111                   0 To 6 Months       Mutual Funds          8.00
004                   998111                   0 To 6 Months       Cash                       2.25
004                   999555                   6 To 12 Months     Bonds                   11.00
004                   999555                   6 To 12 Months     Stocks                    5.00

Using the function Calc_subtotals(filename), creates the following layout in the Excel file, with
SUBTOTALS. The problem is that it doesn't handle more than 65,535 records.

I showed the function ExportToExcels in the Attached Code Snippet because I thought why not leverage off of this function to handle creating multiple worksheets.
------------------------------------------------------------------------------------------------------------------

Branch      Customer Number   Date Range                                      Property Type       Value
004            998111                   0 To 6 Months                                  Stocks                18.00
004            998111                   0 To 6 Months                                  Bonds                 12.25
004            998111                   0 To 6 Months                                  Mutal Funds          8.00
004            998111                   0 To 6 Months                                  Cash                     2.25
Subtotal:                                                                                                                       40.50
004            999555                   6 To 12 Months                                Bonds                 11.00
004            999555                   6 To 12 Months                                Stocks                  5.00
Sub Total:                                                                                                                      16.00
Total:                                                                                                                             56.50

 

by: bigjokeyPosted on 2008-05-19 at 18:19:19ID: 21602859

Still not entirely clear what you require.  

Is the following line not able to export to muliple sheets if you have more than 65,535 records?

DoCmd.TransferSpreadsheet acExport, 8, "tblDtlBrOrder", ExportedFile, True, ""

Do you need something that will export the "tblDtlBrOrder" data to an excel file onto multiple sheets?

Do you then require the Sub Total and Total fields to be calculated and filled on each sheet, or just the last sheet that has been added?

 

by: zimmer9Posted on 2008-05-19 at 18:48:00ID: 21603003

I am using Access 2003.

Is the following line not able to export to muliple sheets if you have more than 65,535 records?
DoCmd.TransferSpreadsheet acExport, 8, "tblDtlBrOrder", ExportedFile, True, ""

That is true. The DoCmd.TransferSpreadsheet is not able to export to multiple sheets when I have more that 65,535 records.
-----------------------------------------------------------------------------------------------------------------------
Yes I need something that will export the "tblDtlBrOrder" data to an excel file onto multiple sheets?
I require the Sub Total fields to be calculated and filled on each sheet. A total of all records on the last line of the report would be great as well.

Bascially I just want a subtotal for each Customer Number, everytime there is a change in the Customer Number within a Date Range. Thus, if the Customer Number changes, I should have a separate line to show a subtotal for that Customer Number for a given Date Range.

If there is a Customer Number that remains the same but there is a change of the Date Range
as is the case in the last sequence that follows, then I would like a subtotal for that Customer Number.

When the Customer Number remains at 999999 yet the Date Range changes, I should have a sub total
for the:
Date Range  24 To 36 Months and another subtotal for the same customer number 999999 with a
Date Range  36 Months And Greater.
For example, the Excel file would look like the following:

Branch      Customer Number   Date Range                                      Property Type       Value
004            546111                   0 To 6 Months                                  Stocks                18.00
004            546111                   0 To 6 Months                                  Bonds                 12.25
004            546111                   0 To 6 Months                                  Mutal Funds          8.00
004            546111                   0 To 6 Months                                  Cash                     2.25
Subtotal:                                                                                                                       40.50
004            999555                   0 To 6 Months                                  Bonds                 11.00
004            999555                   0 To 6 Months                                  Stocks                  5.00
Sub Total:                                                                                                                     16.00
004            111555                   6 To 12 Months                                Bonds                 11.00
004            111555                   6 To 12 Months                                Stocks                  5.00
Sub Total:                                                                                                                     16.00
004            436555                   6 To 12 Months                                Bonds                 22.00
004            436555                   6 To 12 Months                                Stocks                  5.00
Sub Total:                                                                                                                     27.00
004            757555                  12 To 24 Months                               Bonds                 55.00
004            757555                  12 To 24 Months                               Stocks                  5.00
Sub Total:                                                                                                                     60.00
004            999999                  24 To 36 Months                               Bonds                 88.00
004            999999                  24 To 36 Months                               Stocks                  5.00
Sub Total:                                                                                                                     93.00
004            999999                  36 Months And Greater                    Bonds                 45.00
004            999999                  36 Months And Greater                    Stocks                42.00
Sub Total:                                                                                                                     87.00
Total:                                                                                                                          339.50

 

 

by: bigjokeyPosted on 2008-05-19 at 21:54:51ID: 21603571

Have you considered building a report within access, and then exporting the results to excel?  Because the requirements that you are defining would be well served by the Access reporting capabilities.  And you can easily export the data to excel from a report.  The report could be setup to handle all your Grouping and Totalling needs.

 

by: zimmer9Posted on 2008-05-20 at 04:50:58ID: 21605234

I started out using the Access reporting capabilities because as you stated, it can easily handle grouping and totaling needs. However, I found that it couldn't handle more than 65,535 records.
If I had a table with 50,000 records and after factoring in the subtotal records, the record size exceeded 65,535 records, then I would get an error message regarding max lines exceeded.

 

by: bigjokeyPosted on 2008-05-20 at 18:15:16ID: 21611514

Before I attempt to provide a solution, I just want to confirm that this is what you need. 60,00+ records seems like a lot for a report, especially if this is something that a person is supposed to wade through to try to find the information that they need.
Is this report processed by another application or by people?  And should it be broken down into more readable amounts of data?
Sorry if I am delaying the solution, it just seems to me to be a lot of data for a report, and I don't see how that could be useful to anyone reading it

 

by: zimmer9Posted on 2008-05-20 at 18:27:26ID: 21611564

I am grateful for your time.

I know it seems like a large amount of records. I work for a major financial company with approximately 50,000 employees and we send various assets of our clients to different states within the U.S. when we cannot find the current address of 1 of our clients.

This particular report is based on Branch Number. Unfortunately there are a few branches with over 45,000 records which represent different types of assets for our various clients.

If we cannot find the owner of a property within a prescribed time frame, the assets are escheated to the state within the U.S. where the client was last reported living.  

 

by: bigjokeyPosted on 2008-05-20 at 21:32:41ID: 21612142

Well, I will give you a modified version of your ExportToExcels function.  I have changed it so that you can pass the filename, table name, ID field of the table that you want to export, and the number of records that you want to have on each worksheet.  This function will enable you to export any table to excel using the original logic from your ExportToExcel function that first selects the records, writes them to an excel sheet, and then deletes the records that were selected.
Because of this type of logic, make sure you don't accidentally try to export a non-temporary production table, because this function will just export it and then delete it.

The way to use it is to replace the call to:

DoCmd.TransferSpreadsheet acExport, 8, "tblDtlBrOrder", ExportedFile, True, ""

with the call to this function:

Call ExportToExcels ( ExportedFile, "OfficeNumber", "tblDtlBrOrder", "60000" )

This doesn't yet take into account the sub totals and totals because that requires a lot more work.
So try this for now, and see if it at least exports the way you want it to.

Private Sub ExportToExcels(filename As String, FieldToCount as String, TableToCount as String, NumberOfRecords as Long)
	Dim strSelect as String
	Dim strDelete as String
	Dim cn As ADODB.Connection
	Dim xl As Excel.Application
	Dim xlWB As Excel.Workbook
	Dim sht As Excel.Worksheet, rng As Excel.Range
	Dim db As DAO.Database, rs As ADODB.Recordset
	Dim recordtotal As Long
	Dim SheetNum As Long
	Dim dest As Range
	Dim Counter As Long
	Dim Source As Workbook
 
	strSelect = "Select top " & NumberOfRecords & " * from " & TableToCount
	strDelete = "delete from " & TableToCount & " where " & FieldToCount & " in(Select top " & NumberOfRecords & " " & FieldToCount & " from " & TableToCount & ")"
	
	Set cn = CurrentProject.Connection
	Set rs = New ADODB.Recordset
	 
	Set db = CurrentDb
	 
	recordtotal = DCount(FieldToCount, TableToCount)
	Set xl = CreateObject("Excel.Application")
	 
	Set xlWB = xl.Workbooks.Add ' Add a new workbook
	xlWB.SaveAs filename ' Save the new workbook as "filename"
	Set xlWB = xl.Workbooks.Open(filename)  '<--Your Excel File Here
	 
	 
	xl.Visible = True
	SheetNum = 1
	Do While recordtotal > 0
	    rs.Open strSelect, cn, 2, 2
	    If rs.EOF Then Exit Sub
	    rs.MoveFirst
	        Set sht = Nothing
	        On Error Resume Next
	        Set sht = xlWB.Worksheets("Sheet" & SheetNum)
	        On Error GoTo 0
	        
	        If sht Is Nothing Then
	        xlWB.Worksheets.Add After:=Worksheets(Worksheets.count)
	            Set sht = ActiveSheet
	            sht.Name = "Sheet" & SheetNum
	        End If
	        sht.Range("A1").CopyFromRecordset rs
	        SheetNum = SheetNum + 1
	        DoCmd.RunSQL (strDelete)
	    rs.Close
	    recordtotal = DCount(FieldToCount, TableToCount)
	Loop
	 
	xlWB.Close (True)
	xl.Quit
	Set xl = Nothing
 
End Sub

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:

Select allOpen in new window

 

by: zimmer9Posted on 2008-05-25 at 15:28:53ID: 21643842

Call ExportToExcels ( ExportedFile, "OfficeNumber", "tblDtlBrOrder", "60000" )

This works fine. The tblDtlBrOder table is comprised of the following fields.
The goal is to insert a row with 2 fields on a change in CustomerNumber within DateRange:
Column A)  "Sub Total"  and
Column S)  sum of "MarketValue"

strSQL = "select OfficeNumber as Branch, CustomerNumber, DateRange, DateLost, [SSN/Tax ID], FirstName, MiddleInitial, LastName, StreetAddr1, City, ResStateCode, Zip, RedFlag, [Property Type], IRACode, Description, Quantity, [FA #], MarketValue into dbo.tblDtlBrOrder From dbo.tblDtlBranchAll order by DateRange Asc, CustomerNumber Asc, MarketValue Desc "

 

by: bigjokeyPosted on 2008-05-28 at 16:57:54ID: 21665278

In case you are still interested, here is a code snippet that will calculate totals and insert the rows where required.

You need to call it from the Export To Excels function just after the line:

sht.Range("A1").CopyFromRecordset rs
Call GenerateTotals(sht, "B;C", "E")

This will group the rows on columns B and C, and provides totals of column E based on the groups.  You can have more than 1 total column (just seperate the column letters by a semi colon ';'.  And you can also have more grouping columns.

Private Sub GenerateTotals(objWorkSheet, strGroupColumns, strTotalColumns)
    Const FirstRow = 2
    Dim arrGroupColumns, arrTotalColumns, arrGroupColumnValues, arrTotalColumnValues
    Dim lngI, intJ, blnSameGroup
    Dim lngRowCount
    
    ' Store the column letters into arrays for use when referencing the cells of each row
    arrGroupColumns = Split(strGroupColumns, ";")
    arrTotalColumns = Split(strTotalColumns, ";")
    'Resize the Values arrays to store the current group values and Totals
    ReDim arrGroupColumnValues(UBound(arrGroupColumns))
    ReDim arrTotalColumnValues(UBound(arrTotalColumns))
    
    ' Start at 2nd row to ignore row headings
    lngRowCount = objWorkSheet.UsedRange.Rows.Count
    lngI = FirstRow
    While lngI <= lngRowCount
        ' Determine if the Current row grouping values match the previous row grouping values
        'Default the same group variable to be true
        blnSameGroup = True
        For intJ = 0 To UBound(arrGroupColumns)
            blnSameGroup = blnSameGroup And (arrGroupColumnValues(intJ) = objWorkSheet.Range(arrGroupColumns(intJ) & lngI).Value)
            If Not blnSameGroup Then
                Exit For
            End If
        Next
        
        If blnSameGroup Then
            For intJ = 0 To UBound(arrTotalColumns)
                arrTotalColumnValues(intJ) = arrTotalColumnValues(intJ) + objWorkSheet.Range(arrTotalColumns(intJ) & lngI).Value
            Next
        Else
            ' Don't attempt to add a sub totals row if this is the first row
            If lngI > FirstRow Then
                ' Insert a new row above the current row number for inserting the subtotals
                objWorkSheet.Rows(lngI & ":" & lngI).Insert (xlDown)
                
                ' Write out the Sub Totals row, and then reset the grouping values and totals for the new group
                objWorkSheet.Range("A" & lngI).Value = "Sub Total:"
                For intJ = 0 To UBound(arrTotalColumns)
                    objWorkSheet.Range(arrTotalColumns(intJ) & lngI).Value = arrTotalColumnValues(intJ)
                Next
                
                ' increment the row counter so that it is now pointing to the row below the totals
                lngI = lngI + 1
                lngRowCount = lngRowCount + 1
            End If
                        
            ' Assign the new group values to the group values array
            For intJ = 0 To UBound(arrGroupColumns)
                arrGroupColumnValues(intJ) = objWorkSheet.Range(arrGroupColumns(intJ) & lngI).Value
            Next
            ' Assign the new group totals to the group totals array
            For intJ = 0 To UBound(arrTotalColumns)
                arrTotalColumnValues(intJ) = objWorkSheet.Range(arrTotalColumns(intJ) & lngI).Value
            Next
        End If
        lngI = lngI + 1
    Wend
    ' Once we get to the end of the used range, add a row that contains the final sub totals for that page
'    objWorkSheet.Range("A" & lngI).Value = "Sub Total:"
'    For intJ = 0 To UBound(arrTotalColumns)
'        objWorkSheet.Range(arrTotalColumns(intJ) & lngI).Value = arrTotalColumnValues(intJ)
'    Next
End Sub
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:

Select allOpen in new window

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...