简体   繁体   English

如何使用 VBA 在 MS Access 中创建查询?

[英]How do you create a query in MS Access using VBA?

I am trying to automate a process of exporting data from a database in MS Access to excel using VBA. When I do it regularly (excuse my lack of proper verbiage as I am a complete newb at this), I start by creating a query linking two tables.我正在尝试使用 VBA 将数据从 MS Access 中的数据库导出到 excel 的过程自动化。当我经常这样做时(请原谅我缺乏适当的措辞,因为我是一个完全的新手),我首先创建一个查询链接两张桌子。 I double click the asterisk to show the tables.我双击星号以显示表格。 I add one of the column headers as a field in the query and add the criteria I need.我将其中一个列标题添加为查询中的一个字段,并添加我需要的条件。 Then I run the query and export it to excel.然后我运行查询并将其导出到 excel。

I have tried using Google to solve my issue and I have tried to copy and paste the SQL from the query into VBA. I think the latter could work but it is missing the first step I think but I am not sure what that step is.我尝试使用谷歌解决我的问题,我尝试将查询中的 SQL 复制并粘贴到 VBA 中。我认为后者可以工作,但它缺少我认为的第一步,但我不确定那一步是什么。

Edit: This is one attempt I've made with help from the inte.net.编辑:这是我在 inte.net 的帮助下所做的一次尝试。

Sub createQry()
    Dim db As DAO.Database
    Set db = CurrentDb
    Dim qdf As DAO.QueryDef
    Dim newSQL As String

    newSQL = "Select * From [(MR)Events2025] And [(MR)EventMemo2025]     WHERE [EvtDate]= >=#1/1/2022# And <=#1/31/2022#"


End Sub

I want to make it to where I can click a button in excel and it run the process of creating the query in access and then exporting it to excel. The file changes monthly with updated data and I would like to not have to do the same thing every month and just click a button to get the data I want.我想到达可以单击 excel 中的按钮的位置,它运行在访问中创建查询然后将其导出到 excel 的过程。该文件每月更改一次,更新数据,我不想做同样的事情每个月的事情,只需单击一个按钮即可获取我想要的数据。 If it were all in excel I would be fine because of the record macro feature but it doesn't seem to work outside of excel.如果它全部在 excel 中,我会很好,因为记录宏功能,但它似乎在 excel 之外不起作用。

I guess what I want the code to do is open the access database when I click a button in excel, create the query in access (this includes copying a date range from the cell I have selected and pasting it in the criteria portion of the query, or just having that part of the query equal the selected cell in excel), and export the data from the query to excel. I can figure the other stuff I want to do via the macro recorder.我想我想要代码做的是在我单击 excel 中的按钮时打开访问数据库,在访问中创建查询(这包括从我选择的单元格中复制日期范围并将其粘贴到查询的条件部分,或者只是让查询的那部分等于 excel 中选定的单元格),并将查询中的数据导出到 excel。我可以通过宏记录器计算出我想做的其他事情。

The below creates the query for me, now I have to export it to excel.下面为我创建查询,现在我必须将其导出到 excel。

Sub CreateQueryDefX()
 
   Dim dbsAssetManagement As Database
   Dim qdfTemp As QueryDef
   Dim qdfNew As QueryDef
 
   Set dbsAssetManagement = OpenDatabase("C:(deleted file location for privacy)AssetManagement.accdb")
 
   With dbsAssetManagement
     
      Set qdfNew = .CreateQueryDef("NewQueryDef", _
         "SELECT [(MR)Events2025].*, [(MR)EventMemo2025].* FROM [(MR)Events2025] INNER JOIN [(MR)EventMemo2025] ON [(MR)Events2025].MCN = [(MR)EventMemo2025].MCN_ID WHERE ((([(MR)Events2025].EvtDate) >=#1/1/2022# And ([(MR)Events2025].EvtDate)<=#1/31/2022#))")
     
   End With
 
End Sub

You can save the query/queries you want to export and then in VBA export them to files using the TransferSpreadsheet method您可以保存要导出的查询/查询,然后在 VBA 中使用 TransferSpreadsheet 方法将它们导出到文件

See https://learn.microsoft.com/en-us/office/vba/api/access.docmd.transferspreadsheet参见https://learn.microsoft.com/en-us/office/vba/api/access.docmd.transferspreadsheet

Example:例子:

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, 
"staff_list_with_grouping", "C:\test\test.xlsx", True

Alternatively you can do the following steps in VBA (1) create an Excel object, (2) open a blank workbook, (3) open the query you want to export, (4) copy its data (5) paste the data in the Excel workbook, (6) save the workbook, (7) reclose your query或者,您可以在 VBA 中执行以下步骤(1)创建一个 Excel object,(2)打开一个空白工作簿,(3)打开要导出的查询,(4)复制其数据(5)将数据粘贴到Excel 工作簿,(6) 保存工作簿,(7) 重新关闭查询

Example of code exporting a query to an existing Excel template:将查询导出到现有 Excel 模板的代码示例:

Sub ExportSearchResults()


DoCmd.OpenQuery ("MyQuery")
DoCmd.RunCommand acCmdSelectAllRecords
DoCmd.RunCommand acCmdCopy


Dim xlo As New Excel.Application

xlo.Workbooks.Add (getTemplateFolder & "ExportTemplate.xlsx")

xlo.ActiveSheet.Range("D1").Value = Now()
xlo.ActiveSheet.Range("A4").Select

xlo.ActiveSheet.PasteSpecial Format:="Unicode Text"

xlo.ActiveSheet.Cells.Select
xlo.Selection.ColumnWidth = 30
xlo.Selection.RowHeight = 15
xlo.ActiveSheet.Cells.Select
xlo.ActiveSheet.Cells.EntireColumn.AutoFit
xlo.ActiveSheet.Cells.Select
xlo.ActiveSheet.Cells.EntireRow.AutoFit



xlo.Visible = True
xlo.UserControl = True
xlo.WindowState = -4137 
xlo.Range("A1").Select


End Sub

I was originally trying to do this in Access but I was eventually able to find a video for VBA in excel. It pulls all the data that I want.我最初试图在 Access 中执行此操作,但我最终能够在 excel 中找到 VBA 的视频。它提取了我想要的所有数据。

Sub getDataFromAccess()
' Click on tools, references and select
' the Microsoft ActiveX Data Objects 2.0 Library

Dim DBFullName As String
Dim Connect As String, Source As String
Dim Connection As ADODB.Connection
Dim Recordset As ADODB.Recordset
Dim Col As Integer

Cells.Clear

' Database path info
DBFullName = "C:(deleted file location for privacy)AssetManagement.accdb"

' Open the connection
Set Connection = New ADODB.Connection
Connect = "Provider=Microsoft.ACE.OLEDB.12.0;"
Connect = Connect & "Data Source=" & DBFullName & ";"
Connection.Open ConnectionString:=Connect

'Create RecordSet
Set Recordset = New ADODB.Recordset
With Recordset
'Filter Data
Source = "SELECT [(MR)Events2025].*, [(MR)EventMemo2025].* FROM [(MR)Events2025] INNER JOIN [(MR)EventMemo2025] ON [(MR)Events2025].MCN = [(MR)EventMemo2025].MCN_ID WHERE ((([(MR)Events2025].EvtDate) >=#1/1/2022# And ([(MR)Events2025].EvtDate)<=#1/31/2022#))"

.Open Source:=Source, ActiveConnection:=Connection

'MsgBox "The Query:" & vbNewLine & vbNewLine & Source

'Write field names
For Col = 0 To Recordset.Fields.Count - 1
 Range("A1").Offset(0, Col).Value = Recordset.Fields(Col).Name
Next

'Write Recordset
Range("A1").Offset(1, 0).CopyFromRecordset Recordset
End With
ActiveSheet.Columns.AutoFit
Set Recordset = Nothing
Connection.Close
Set Connection = Nothing


End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM