简体   繁体   English

如何将 SQL 语句结果导出到 Excel 文件

[英]How to export SQL statement results to an Excel File

I have an Access DataBase and a form in Excel VBA.我有一个 Access 数据库和一个 Excel VBA 表单。 All the data I input into the DB is input through the VBA form.我输入到DB的所有数据都是通过VBA形式输入的。

This DB contains all the benefits cards we already received this year in the company.该数据库包含我们今年在公司收到的所有福利卡。 But the same employee can ask for the card twice or more, so we'll have more than one record on the DB for him.但是同一个员工可以要求两次或更多次的卡,因此我们将在数据库中为他保留不止一条记录。

What I need is when the number of records is greater than one, the SQL statement result should appear in a Excel report.我需要的是当记录数大于1时,SQL语句结果应该出现在Excel报表中。

I use the SELECT (*) COUNT statement to know when there is more than one record that is compatible with the search criterion.我使用SELECT (*) COUNT语句来了解何时存在多个与搜索条件兼容的记录。 But I can't make the result appear in an Excel file.但我无法让结果出现在 Excel 文件中。

Here is my code:这是我的代码:

Public Function Relatorio()
    Dim sql As String
    Dim cn  As ADODB.Connection
    Dim rs  As ADODB.Recordset
    Dim rel As String

    Set cn = New ADODB.Connection
    cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & enderecoDB & ";Jet OLEDB:Database"
    cn.Open
    Set rs = New ADODB.Recordset
    sql = "INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=" & enderecoDB & ";', 'SELECT * FROM [Planilha1$]') SELECT * FROM controle WHERE BP = " & controlectform.nmbpbox.Value & ";"
    rs.Open sql, cn
End Function

When I run this code it gives me a message saying something like:当我运行此代码时,它会给我一条消息,内容如下:

Can't locate the OPENROWSET Table exit找不到 OPENROWSET 表出口

I'm not able to install new programs, so I need to do this using only Excel VBA and the Access DB.我无法安装新程序,因此我只需要使用 Excel VBA 和 Access DB 来执行此操作。

How can I make this work?我怎样才能使这项工作?

I don't believe Access supports the OPENROWSET, dynamic table you're working with there.我不相信 Access 支持您在那里使用的 OPENROWSET 动态表。 I have a lot of old projects that do this though, so here's my method我有很多旧项目都这样做,所以这是我的方法

Public Function Relatorio()

    Dim sql As String
    Dim cn  As ADODB.Connection
    Dim rs  As ADODB.Recordset
    Dim rel As String


    Set cn = New ADODB.Connection

    cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & enderecoDB & ";Jet OLEDB:Database"

    cn.Open

    Set rs = New ADODB.Recordset

    dim path_To_XLSX
    dim name_of_sheet
    path_To_XLSX = "c:\temp\output.xlsx"
    name_of_sheet = "Planilha1"
    sql = sql = "SELECT * INTO [Excel 12.0;Database=" & path_To_XLSX & "]." & name_of_sheet & " FROM controle WHERE BP = '" & controlectform.nmbpbox.Value & "';" 

    rs.Open sql, cn

    'If this application is in an unsecure environment, use the following code instead!  This is to prevent a SQL injection, security concern here.
    'As it is an Access Database, this is likely overkill for this project
    'Create Command Object.
    Set Cmd1 = New ADODB.Command
    Cmd1.ActiveConnection = cn
    cmd1.CommandText = "SELECT * FROM controle INTO [Excel 12.0;Database=" & path_To_XLSX & "]." & name_of_sheet & " WHERE BP = ?"
    ' Create Parameter Object.
    Set Param1 = Cmd1.CreateParameter(, adInteger, adParamInput, 5) 'use adVarchar for strings(versus adInteger), https://www.w3schools.com/asp/met_comm_createparameter.asp
    Param1.Value = controlectform.nmbpbox.Value
    Cmd1.Parameters.Append Param1
    Set Param1 = Nothing
    Set Rs = Cmd1.Execute()

End Function

I had this challenge so many years ago that I cant remember but this link ring the bell.多年前我遇到了这个挑战,我不记得了,但是这个链接敲响了警钟。 check if it help.检查它是否有帮助。

https://stackoverflow.com/a/28889774/382588 https://stackoverflow.com/a/28889774/382588

try { connw.Open();尝试 { connw.Open(); OleDbCommand command; OleDbCommand 命令; command = new OleDbCommand( "Update Deliveries " + "SET Deliveries.EmployeeID = ?, Deliveries.FIN = ?, Deliveries.TodaysOrders = ? , connw); command.Parameters.Add(new OleDbParameter("@EMPID", Convert.ToDecimal(empsplitIt[1]))); command.Parameters.Add(new OleDbParameter("@FIN", truckSplit[1].ToString())); command.Parameters.Add(new OleDbParameter("@TodaysOrder", "R")); catchReturnedRows = command.ExecuteNonQuery();//Commit connw.Close(); } catch (OleDbException exception) { MessageBox.Show(exception.Message, "OleDb Exception"); } command = new OleDbCommand( "Update Deliveries " + "SET Deliveries.EmployeeID = ?, Deliveries.FIN = ?, Deliveries.TodaysOrders = ? , connw); command.Parameters.Add(new OleDbParameter("@EMPID", Convert.ToDecimal (empsplitIt[1]))); command.Parameters.Add(new OleDbParameter("@FIN", truckSplit[1].ToString())); command.Parameters.Add(new OleDbParameter("@TodaysOrder", "R ")); catchReturnedRows = command.ExecuteNonQuery();//Commit connw.Close(); } catch (OleDbException exception) { MessageBox.Show(exception.Message, "OleDb Exception"); }

you can use this, to print the actual SQL.您可以使用它来打印实际的 SQL。

Private Sub Command2_Click()

Dim db As Database
Dim qr As QueryDef

Set db = CurrentDb

For Each qr In db.QueryDefs
  TextOut (qr.Name)
  TextOut (qr.SQL)
  TextOut (String(100, "-"))
Next

End Sub

Public Sub TextOut(OutputString As String)

    Dim fh As Long

    fh = FreeFile
    Open "C:\Users\rs17746\Desktop\Text_Files\sample.txt" For Append As fh
    Print #fh, OutputString
    Close fh

End Sub

Here is one more version for you.这是给你的另一个版本。 This will export the results of each query, each to a separate text file.这会将每个查询的结果导出到一个单独的文本文件中。

Private Sub Command0_Click()


Dim qdf As QueryDef
Dim strFileName As String
For Each qdf In CurrentDb.QueryDefs
If Left(qdf.Name, 1) <> "~" Then

'you need to figure out TransferText command. Maybe
'you won't be lazy and expect people to read it to
'you and tutor you on how it works.
strFileName = qdf.Name

'Docmd.TransferText ....
DoCmd.TransferText transferType:=acExportDelim, TableName:=strFileName, FileName:="C:\test\" & strFileName & ".txt", hasfieldnames:=True

End If
Next qdf
MsgBox "Done"


End Sub

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

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