访问VBA以运行多个选择查询并导出到不同工作表上的excel

时间:2019-06-26 17:05:54

标签: access-vba

我正在尝试将多个查询导出到同一excel工作表并命名为excel工作表。我可以将其导出到同一电子表格中的多个工作表,但不能导出到同一工作表。

选项比较数据库

Sub validate()

Dim db As Database
Set db = CurrentDb
Dim strFolder As String
Dim rst1 As DAO.Recordset
Dim rst2 As DAO.Recordset
Dim qry1 As String
Dim qry2 As String

qry1 = "SELECT DISTINCT IIf(IsDate([models].[startdate])=False,'No' + '  ' + [models.Startdate],'Yes') AS StartDate, IIf(IsDate([models].[Enddate])=False," & _
            "'No' + '  ' + [models.Enddate],'Yes') AS EndDate FROM [Models]"
 db.CreateQueryDef "temp1", qry1



qry2 = "SELECT DISTINCT Left([pages.imagefile],InStr([pages.imagefile],'_')-1) AS Pages_Series, " & _
       "Left([parts.imagefile],InStr([parts.imagefile],'_')-1) AS Parts_ImgSeries, IIf([Pages_Series]=[Parts_ImgSeries],'Yes','No') AS Expr1 FROM [Pages], [Parts]"

 db.CreateQueryDef "temp2", qry2



strFolder = CurrentProject.Path & "\"

    DoCmd.TransferSpreadsheet acExport, , "temp1", strFolder & "Validated.xlsx", True
    DoCmd.TransferSpreadsheet acExport, , "temp2", strFolder & "Validated.xlsx", True

  CurrentDb.QueryDefs.Delete "temp1"
  CurrentDb.QueryDefs.Delete "temp2"

End Sub

这会将两个查询放入2个不同的工作表中,但我需要在同一工作表中将它们都放入。还有如何命名工作表。

2 个答案:

答案 0 :(得分:0)

在文件中创建工作表,并在其中创建两个命名范围

将其命名为 NamedRangeName1 NamedRangeName2

然后运行:

DoCmd.TransferSpreadsheet acExport, , "temp1", strFolder & "Validated.xlsx", True, "NamedRangeName1"
DoCmd.TransferSpreadsheet acExport, , "temp2", strFolder & "Validated.xlsx", True, "NamedRangeName2"

答案 1 :(得分:0)

由于您要查找的查询结果要比工作表中的另一个查询结果输出 ,因此我建议您修改SQL,以使用{{1 }},然后将此单个查询的结果输出到电子表格:

MLBatchProvider

我还建议使用&运算符union)进行串联,因为这将始终将参数视为字符串,而加法运算符(select distinct IIf(IsDate([models].[startdate])=False,'No ' & [models.Startdate],'Yes') as StartDate, IIf(IsDate([models].[Enddate])=False,'No ' & [models.Enddate],'Yes') as EndDate, null as Expr1 from [Models] union all select distinct Left([pages.imagefile],InStr([pages.imagefile],'_')-1) as Pages_Series, Left([parts.imagefile],InStr([parts.imagefile],'_')-1) as Parts_ImgSeries, IIf([Pages_Series]=[Parts_ImgSeries],'Yes','No') as Expr1 from [Pages], [Parts] )将如果数据不是数字,则在连接之前首先尝试解释数据的数字内容。