Exporting filtered tables into dif excel worksheets (1 Viewer)

Arleta

Registered User.
Local time
Yesterday, 19:51
Joined
Mar 1, 2011
Messages
24
Hi all! This is another exporting access data into excel worksheets but although I'm searching many days now I cannot find a suitable answer to my issue, so here I am hopefully to get your precious assistance.

What I have till now is a code to export a filtered query into a single workbook. What I want to do is to filter about 7 tables based on a value of field "BRANCH" and export the result of each one of them into a separate shett. The final workbook should look like this: sheet1 includes all data of branch 2214 coming from table "CHANGES_FP", sheet2 all data of branch 2214 from table "CHANGES_NS" etc. Have to mention that all tables have different structure and values.

The code I use is :
Set DBS = CurrentDb
Set qdf = DBS.QueryDefs("q_temp")

strSQL = "SELECT DISTINCT BRANCH, BranchDirector, GrTypo FROM tbl_Mtv_SEND;"
Set rstMgr = DBS.OpenRecordset(strSQL, dbOpenDynaset, dbReadOnly)

Do While rstMgr.EOF = False

strMgr = DLookup("BRANCH", "T_BranchList", _
"BRANCH = " & rstMgr!BRANCH.Value)

strSQL = "SELECT * FROM Mtv_SEND WHERE " & _
"BRANCH = " & rstMgr!BRANCH.Value & ";"


qdf.sql = strSQL
qdf.Close
' Replace C:\FolderName\ with actual path
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
"q_temp", "D:\DAAP\" & strMgr & "-" & Format(Now(), _
"ddMMMyyyy") & ".xls"


ExcelFile = "D:\DAAP\" & strMgr & "-" & Format(Now(), _
"ddMMMyyyy") & ".xls"
ExcelWorksheet = "q_temp"
Ques = "C:\Users\APC\Desktop\AUDIT PROJECT\DAILY AUDIT DB.accdb"
QueryName = "q_temp"

Can you please help resolve this?
Thank you in advance.
 
Can you clarify that you want information on different worksheets in the same workbook for each branch? Or a different workbook for each branch?
 
Can you clarify that you want information on different worksheets in the same workbook for each branch? Or a different workbook for each branch?

Hi. Thanks for your reply. What I need is to have in the same workbook, same brances but in different workheets for each table.
I'm not sure if this is clear enough.

Let's say. I have 3 tables "Mtv_1", "Mtv_2", "Mtv_3". The only common field in all of them is the field "BRANCH". I want the code to look through all tables find a specific branch, and return it's data to different worksheets for each table but in the same workbook. Then for the next branch open a new workbook. Thanks again.
 
up!

I would really appreciate if I could have someones' reply on this. Please respond even if it is something hard or imposible to be done. I just need to know so to find another solution.

Many thanks in advance.
 
I have some code that I modified for you but I need a couple of questions answered first.

Right now you have:
strSQL = "SELECT * FROM Mtv_SEND WHERE " & _
"BRANCH = " & rstMgr!BRANCH.Value & ";"


But are you looking to have a list of tables and then export the contents based on Branch to the worksheets as individual worksheets for the branch? I'm guessing yes.

If so, I would have a table which lists which tables you want to use. So you can modify things quickly without code changes should anything change. You can even use query names in the table like this:

tblExportTables
TableName - Text (PK)

Then you populate it with rows like:

CHANGES_FP
CHANGES_NS

So is that kind of what you're looking for?
 
But are you looking to have a list of tables and then export the contents based on Branch to the worksheets as individual worksheets for the branch? I'm guessing yes.
.............
So is that kind of what you're looking for?
Well, I think that this is pretty close to what I'm looking for. Let me describe you in a few words the design of my tables so not to be any misunderstanding.

In real I have 13 tables.
t_InactiveSEND
t_Overrides_SEND
t_EMRE_SEND

etc
each one of them has various fields but the one and only common field in each of them is the field BRANCH. (Unfortunately to some is named INP_Branch and to othes as BRANCH but I guess that this is something that I can resolve easily).

an example to get the general picture of the tables is as below :

t_InactiveSEND, ......t_Overrides_SEND,.... t_EMRE_SEND
2214, field1, field2.... 2214,field3,field4.... 2214,field6,fiel7
2226,field1,field2.........2226,field3,field4
2233,field1,field2
The idea is to get each branch in a different workbook, named with the name of the branch : 2214.xls, 2226.xls and 2233.xls.
Each workbook should have different sheets for each table populated with row data of each branch.

Now I hope we both describing the same thing :)

Many many thanks in advance !!!!!!
 
Do you have a table with all of the branch numbers listed?

Also, does each of the 13 tables have the word SEND in its name and are there any other tables with SEND in the name which you would NOT want output from?
 
Do you have a table with all of the branch numbers listed?

Also, does each of the 13 tables have the word SEND in its name and are there any other tables with SEND in the name which you would NOT want output from?

I indeed have a table with all the branch numbers and emails.

For your other question I work both ways. I have 13 tables as imported from excel and a field named Action where I change to SEND for those I want to email and when finish I send all rows with "SEND". Then I go from table to table and to the same since they are totally different tables with various data.

For f/u purposes I run 13 queries and create 13 dif tables where I keep only the SEND data.
 
Okay, so you may have to adjust this some but here's what I have for you.

First, put this code into a STANDARD MODULE (not a form, report, or class module) and name it basExport.


Code:
Public Function SendTQ2ExcelSheets(strTQSQL As String, strSheetName As String, strFileName As String)
' strTQName is the name of the table or query you want to send to Excel
' strSheetName is the name of the sheet you want to name it to
' strFileName is the file path and name of the existing workbook to open (including extension)
 
    Dim rst As DAO.Recordset
    Dim xlWBk As Object
    Dim xlWSh As Object
    Dim fld As DAO.Field
    Dim i As Integer
    Dim blnSheetExists As Boolean
    Dim blnFileExists As Boolean
 
    Const xlCenter As Long = -4108
    Const xlBottom As Long = -4107
 
    On Error GoTo err_handler
 
    Set rst = CurrentDb.OpenRecordset(strTQSQL)
 
    If IsNothing(objXL) Then
       Set objXL = CreateObject("Excel.Application")
    End If
 
    If Dir(strFileName) = vbNullString Then
        Set xlWBk = objXL.Workbooks.Add
    Else
        Set xlWBk = objXL.Workbooks.Open(strFileName)
        blnFileExists = True
    End If
 
' this is here for debugging only.  comment it out for production so Excel doesn't show.
    objXL.Visible = True
 
    With xlWBk
        i = 1
        Do Until i = .Worksheets.Count + 1
            If .Worksheets(i).Name = strSheetName Then
                blnSheetExists = True
            End If
            i = i + 1
        Loop
 
        If Len(strSheetName) > 31 Then
            strSheetName = Left(strSheetName, 31)
        End If
 
        If blnSheetExists Then
                    Set xlWSh = .Worksheets(strSheetName)
        Else
            Set xlWSh = .Worksheets.Add
            xlWSh.Name = strSheetName
        End If
 
    End With
 
    xlWSh.Range("A1").Select
 
    For Each fld In rst.Fields
        objXL.ActiveCell = fld.Name
        objXL.ActiveCell.Offset(0, 1).Select
    Next
 
    rst.MoveFirst
 
    xlWSh.Range("A2").CopyFromRecordset rst
    xlWSh.Range("1:1").Select
 
    ' selects all of the cells
    objXL.ActiveSheet.Cells.Select
 
    ' does the "autofit" for all columns
    objXL.ActiveSheet.Cells.EntireColumn.AutoFit
 
    ' selects the first cell to unselect all cells
    xlWSh.Range("A1").Select
 
    If blnFileExists Then
        xlWBk.Save
    Else
        xlWBk.SaveAs strFileName
    End If
 
    xlWBk.Close
    rst.Close
    Set rst = Nothing
 
ExitThis:
    Exit Function
 
err_handler:
    DoCmd.SetWarnings True
    MsgBox Err.Description, vbExclamation, Err.Number
    Resume ExitThis
    Resume
 
End Function

Put this part in the General Declarations section of your new module just below the Option Compare Database (and Option Explicit if you have that one, which you should)

Code:
Private objXL As Object

Next you would use this in your click event from your send button on the form:
Code:
Dim rst As DAO.Recordset
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim strSQL As String
 
Set db = CurrentDb
 
strSQL = "Select * FROM YourTableNameWhichListsBranches " & _
            "ORDER BY Branch"
 
Set rst = db.OpenRecordset(strSQL)
 
Do Until rst.EOF
    For Each tdf In db.TableDefs
       If Instr(1, tdf.Name, "SEND") > 0 Then
          strSQL = "SELECT *  FROM [" & tdf.Name & "] WHERE BRANCH = " & rst!Branch
          SendTQ2ExcelSheets strSQL, Replace(tdf.Name, "_SEND", vbNullstring), "C:\SomeFolder\" & rst!Branch & ".xls"
       End If
    Next
    rst.MoveNext
Loop
 
rst.Close
Set tdf = Nothing
Set rst = Nothing
Set db = Nothing
You will want to make sure the send tables all have _SEND at the end with the underscore. And you will have to replace the C:\SomeFolder with an acutal path to where you want these.

I'm sure there will be some major debugging to do here since I have no real cluse as to your database so I did the best I could with the information received.
 
As u said, here we go with the errors...:confused:

Well, let me tell u what I've done. I moved some tables into a new db and I checked that all their names ending with _SEND.
I created a basExport module that looks as below:
---------------
Option Compare Database

Option Explicit
Private objXL As Object


Public Function SendTQ2ExcelSheets(strTQSQL As String, strSheetName As String, strFileName As String)
' strTQName is the name of the table or query you want to send to Excel
' strSheetName is the name of the sheet you want to name it to
' strFileName is the file path and name of the existing workbook to open (including extension)

etc, etc...
------------------
and rename al fields from INP_BRANCH to BRANCH (I have a big issue here as half tables the branch field is named as BRANCH and in others is names as INP_BRANCH)

Then in a control button I put the suggested code and tried to run but I got the following error : Ambiguous name detected: SendTQ2ExcelSheets. This occurs after the path and highlights the rst!Branch.
 
I figured we'd have to sort a few things out. Also, I forgot to quit the objXL and set it to nothing (needs to be done in the click event after everything is done) so you probably have an extra instance of EXCEL.EXE running in your Task Manager. So, open Windows Task Manager and click on any Excel.EXE listed under the process tab and select TERMINATE. Do that for any that may exist. You can sort the list by process name by clicking on the IMAGE NAME header so you can find all of them.

So let's try this modification to the click event:
Code:
Dim rst As DAO.Recordset
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim strSQL As String
[COLOR=red]Dim strField As String[/COLOR]
[COLOR=red]Dim fld As DAO.Field
[/COLOR] 
Set db = CurrentDb
 
strSQL = "Select * FROM YourTableNameWhichListsBranches " & _
            "ORDER BY Branch"
 
Set rst = db.OpenRecordset(strSQL)
 
Do Until rst.EOF
    For Each tdf In db.TableDefs
[COLOR=red]       For Each fld In tdf.Fields[/COLOR]
[COLOR=red]          If Inst(1, fld.Name, "BRANCH") > 0 Then[/COLOR]
[COLOR=red]             strField = fld.Name[/COLOR]
[COLOR=red]             Exit For[/COLOR]
[COLOR=red]          End If[/COLOR]
[COLOR=red]       Next[/COLOR]
       If Instr(1, tdf.Name, "SEND") > 0 Then
          strSQL = "SELECT *  FROM [" & tdf.Name & "] WHERE [" & strField & "] = " & rst!Branch
          SendTQ2ExcelSheets strSQL, Replace(tdf.Name, "_SEND", vbNullstring), "C:\SomeFolder\" & rst!Branch & ".xls"
       End If
    Next
    rst.MoveNext
Loop
 
rst.Close
Set tdf = Nothing
Set rst = Nothing
Set db = Nothing
So hopefully there are no additional fields in the table which has the word BRANCH in it. If there is, we may have to create another table to be able to just tell it for which table to use which field. If there isn't any other field in any of the tables with the word Branch in it, then this should grab it and use it.
 
There is an error at If Inst

error : sub or function not defined
 
Again the same error as before : Ambiguous name detected: SendTQ2ExcelSheets right after the path and highlights the rst!Branch.
 
First of all, in your table which holds the branch list, what is the actual field name that you used? And second, if your table that holds the branch list has the same branch listed more than once we'll need to change the SQL string so it only pulls it once.
Code:
strSQL = "Select [COLOR=red]DISTINCT BRANCH[/COLOR] FROM YourTableNameWhichListsBranches " & _
            "ORDER BY Branch"
And make sure to change the names to be appropriate and I hope you are referencing the TABLE here and not a query.
 
The actual name of the field of the branchholding table is: BRANCH. no queries here. It's name is t_inputBranchList and code is as :

Set db = CurrentDb
strSQL = "Select BRANCH FROM t_inputBranchList " & _
"ORDER BY BRANCH"

Silly me by mistake I had added a branch twice, so I deleted. When I tried to run the code adding Select DISTINCT BRANCH nothing happend!!!

But when I deleted and run it as it was given at first I got a new error msg this time at the module that says : Sub or function not defined.

This occurs at the line :

If IsNothing(objXL) Then
 
Well, I'm not sure I can describe what happened now. It oppened many many workbooks only wrote the header but in some of them added some row data and at the end I got an error message :

Unable to get the Open property of the Workbooks class.

Seems to get close to a result but still something is missing. I would also like this procedure to take place on behind and not in front of my eyes.

And many many thanks for your time. It's not that easy as I first thought :o
 

Users who are viewing this thread

Back
Top Bottom