control what spreadsheet a query is exported to in msaccess

左心房为你撑大大i 提交于 2019-12-24 18:51:27

问题


I have a query which changes based on the criteria I set. The query's result will be changed after exporting the query to a excel spreadsheet.

This is an example of how the query works

CATEGORY = A,B,C

FILTER = D,E,F

The outcome would be something like the following:

AxF

After exporting it to a spreadsheet, I will run the same query again, but with a different set of parameters, such as:

CxD

(Instead of sending the results to different queries, I rewrite the output query's sql in vba, and there is a reason for doing that), but when it comes to exporting the query that is returned, for some reason, it will do one of the following:

  1. override the data that is already in excel

  2. combine with the data that is already in excel

  3. erase all data in spreadsheet

Is there any way to control what spreadsheet a query is out put to?

i would like it to work like the following:

  • sheet# = outquery(CATEGORYxFILTER)
  • sheet1 = outquery(AxF)
  • sheet2 = outquery(CxD)
  • sheet3 = outquery(BxE)

Because the conditions for the query change every time it is called, posting my query code would be pointless.

but I shall give a better example:

let x represent first parameter let y represent second parameter let A represent first category Let B represent second category

select * from * Where A=x and B=y

say i have a table of the following (this is just an example)

let the table be called EXTABLE

NAME-------BDAY-------AGE-------GENDER-------COUNTRY

AMANDA-----07/04------21--------FEMALE-------USA

MAX--------09/17------30--------MALE---------USA

SARA-------05/03------18--------FEMALE-------ENGLAND

MAX--------09/17------21--------MALE---------ENGLAND

ALEXIS-----10/25------37--------FEMALE-------FRANCE

PIERRE-----07/04------30--------MALE---------FRANCE

MY QUERY MAY SOMETIMES BE SOMETHING LIKE:

SELECT * FROM EXTABLE WHERE AGE = 21 AND GENDER = "MALE"

BUT THE NEXT TIME I CALL THE QUERY IT COULD BE:

SELECT * FROM EXTABLE WHERE COUNTRY = "ENGLAND" AND BDAY = "05/17"

the reason for changing the sql through vba is because not only are the parameters of the conditions changing, but so are the categories to which the parameters are applied


回答1:


I'm still sure you can do it with parameter queries, although I'll have to have a think about it.

To get something you can work with I've come up with this (sorry, there's multiple queries at the moment):

First I created the two queries as stored queries:

AgeGender

PARAMETERS Person_Age Long, Person_Gender Text ( 255 );
SELECT *
FROM EXTABLE
WHERE Age = Person_Age AND Gender = Person_Gender;

CountryBday

PARAMETERS Person_Country Text(255), Person_Bday DateTime;
SELECT      *
FROM        EXTABLE
WHERE       Country = Person_Country AND Bday = Person_Bday    

This is the main procedure to export the two queries:

Public Sub ProcessQuery()

    Dim oXL As Object
    Dim oWrkBk As Object
    Dim oWrkSht As Object

    Set oXL = CreateXL
    Set oWrkBk = oXL.Workbooks.Add(-4167) 'xlWBATWorksheet - creates a workbook with 1 sheet.
    Set oWrkSht = oWrkBk.Worksheets(1)

    Export_To_XL "AgeGender", oWrkSht.Range("A1"), "Person_Age", 47, "Person_Gender", "Female"

    Set oWrkSht = oWrkBk.Worksheets.Add 'This will now have a reference of your new sheet.
    Export_To_XL "CountryBday", oWrkSht.Range("A1"), "Person_Country", "England", "Person_Bday", #5/3/1971#

End Sub

Code to process your queries and export them to Excel. The ParamArray must takes sets of two parameters - the parameter name and its value.

Public Sub Export_To_XL(sQueryName As String, PasteRange As Object, ParamArray Params())

    Dim db As DAO.Database
    Dim qdf As DAO.QueryDef
    Dim rst As DAO.Recordset
    Dim fld As DAO.Field
    Dim pElement As Long

    On Error GoTo ERR_HANDLE

    Set db = CurrentDb
    Set qdf = db.QueryDefs(sQueryName)
    With qdf
        For pElement = LBound(Params) To UBound(Params) Step 2
            .Parameters(Params(pElement)) = Params(pElement + 1)
        Next
    End With
    Set rst = qdf.OpenRecordset

    With rst
        If Not (.BOF And .EOF) Then

            For Each fld In rst.Fields
                PasteRange.offset(, fld.OrdinalPosition) = fld.Name
            Next fld
            PasteRange.Resize(, rst.Fields.Count).Font.Bold = True
            PasteRange.offset(1).CopyFromRecordset rst
            PasteRange.Parent.Columns.Autofit

        End If
    End With

EXIT_PROC:

    Set rst = Nothing

        On Error GoTo 0
        Exit Sub

ERR_HANDLE:
    Select Case Err.Number

        Case Else
            MsgBox "Error " & Err.Number & vbCr & _
                " (" & Err.Description & ") in procedure Export_To_XL."
            Resume EXIT_PROC
    End Select

End Sub  

You'll need code to create an instance of Excel:

Public Function CreateXL(Optional bVisible As Boolean = True) As Object

    Dim oTmpXL As Object

    '''''''''''''''''''''''''''''''''''''''''''''''''''''
    'Defer error trapping in case Excel is not running. '
    '''''''''''''''''''''''''''''''''''''''''''''''''''''
    On Error Resume Next
    Set oTmpXL = GetObject(, "Excel.Application")

    '''''''''''''''''''''''''''''''''''''''''''''''''''''''
    'If an error occurs then create an instance of Excel. '
    'Reinstate error handling.                            '
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''
    If Err.Number <> 0 Then
        Err.Clear
        On Error GoTo ERROR_HANDLER
        Set oTmpXL = CreateObject("Excel.Application")
    End If

    oTmpXL.Visible = bVisible
    Set CreateXL = oTmpXL

    On Error GoTo 0
    Exit Function

ERROR_HANDLER:
    Select Case Err.Number

        Case Else
            MsgBox "Error " & Err.Number & vbCr & _
                " (" & Err.Description & ") in procedure CreateXL."
            Err.Clear
    End Select

End Function  

Right, just need to figure out how to combine 100 queries into 1 now....

Edit:
This SQL isn't tested, but I'm thinking something along these lines -

PARAMETERS  Person_Name Text(255), Person_Bday DateTime, Person_Age Long, 
            Person_Gender Text(255), Person_Country Text(255);
SELECT      *
FROM        EXTABLE
WHERE       IIF(ISNULL(Person_Name),TRUE,sName = Person_Name) AND
            IIF(ISNULL(Person_Bday),TRUE,Bday = Person_Bday) AND
            IIF(ISNULL(Person_Age),TRUE,Age = Person_Age) AND
            IIF(ISNULL(Person_Gender),TRUE,Gender = Person_Gender) AND
            IIF(ISNULL(Person_Country),TRUE,Country = Person_Country)


来源:https://stackoverflow.com/questions/50858307/control-what-spreadsheet-a-query-is-exported-to-in-msaccess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!