简体   繁体   English

使用VBA / SQL查询大型Excel文件

[英]Query Large Excel File using VBA/SQL

I am trying to write some SQL code within VBA to execute a query on a relatively large excel file(500,000 lines), where I would like to find the total sales for these given subcategories: 我正在尝试在VBA中编写一些SQL代码以在相对较大的excel文件(500,000行)上执行查询,在这里我想找到这些给定子类别的总销售额:

My data looks like this: 我的数据如下所示:

Order ID|Sales|ProductSubCategory|Region
234324   3400  BookCases          South 
234345   2700  Tables             North

This is the main criteria for the SQL Query: 这是SQL查询的主要标准:

  • Bookcases Chairs 书柜椅
  • Chairmats 椅子垫
  • Office Furnishings 办公家具
  • Tables 桌子

I am relatively new to using VBA, and especially SQL within VBA, so any help would be greatly appreciated. 对于使用VBA(尤其是VBA中的SQL),我是一个相对较新的人,因此对您的帮助将不胜感激。 Thanks for your time. 谢谢你的时间。

您可以使用Power查询仅将相关数据(使用过滤条件)从excel文件/ Sql数据库导入到新excel文件中的数据模型中,然后可以轻松地对该数据模型进行分析。

strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
               & "Data Source='C:\Path\To\Workbook.xlsm';" _
               & "Extended Properties=""Excel 8.0;HDR=YES;"";"

strSQL = "SELECT * FROM [Sheet1$]" 

You can treat excel files like data sources like you would an access file, and query it that way :) 您可以像对待访问文件一样将excel文件视为数据源,然后以这种方式查询它:)

RunQuery(SourceFile As String, Targetrange As Range, strsql As String, ColName As Boolean) RunQuery(SourceFile作为字符串,Targetrange作为范围,strsql作为字符串,ColName作为布尔值)

Dim dbConnection As ADODB.Connection, rs As ADODB.Recordset
Dim dbConnectionString As String
Dim TargetCell As Range, i As Integer

dbConnectionString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)}; DBQ=" & SourceFile & ";"

Set dbConnection = New ADODB.Connection
'On Error GoTo InvalidInput
dbConnection.Open dbConnectionString

Set rs = dbConnection.Execute(strsql)
If ColName Then
    Set TargetCell = Targetrange.Cells(1, 1)
    For i = 0 To rs.Fields.count - 1
        TargetCell.Offset(0, i).Formula = rs.Fields(i).Name
        Debug.Print rs.Fields(i).Name
    Next i
    Set TargetCell = Targetrange.Offset(1, 0)
Else
    Set TargetCell = Targetrange.Offset(0, 0)
End If
TargetCell.CopyFromRecordset rs
rs.Close
dbConnection.Close
Set TargetCell = Nothing
Set rs = Nothing
Set dbConnection = Nothing

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

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