简体   繁体   English

使用VBA在Excel中使用SQL样式查询

[英]Use SQL-style query in Excel using VBA

I have a large excel sheet which looks similar to this: 我有一个大的excel表,看起来像这样:

date       |  name  |  age  |  type
10/10/2012 | James  |  12   |  man 
11/10/2012 | Jane   |  50   |  woman 
12/10/2012 | Freddy |  2    |  dog
13/10/2012 | Bob    |  23   |  man
14/10/2012 | Mary   |  34   |  woman 

What I want to do is create a new, dynamically generated table showing all the men. 我想要做的是创建一个新的,动态生成的表格,显示所有人。

In SQL this would be a synch: "SELECT * FROM table WHERE type='men'" . 在SQL中,这将是一个同步: "SELECT * FROM table WHERE type='men'" I've never used VBA in excel before (tho I am an experienced PHP/Javascript programmer and have used VBA in MS Access) so I'm looking for beginners instructions to get me started. 我之前从未在excel中使用过VBA(因为我是一名经验丰富的PHP / Javascript程序员,并且在MS Access中使用了VBA)所以我正在寻找初学者的指示来帮助我入门。 Perhaps someone can recommend a simple tutorial or blog post that does something like what I need to do? 也许有人可以推荐一个简单的教程或博客文章来完成我需要做的事情?

It took me most of the day but I have figured this out. 它花了我一天的大部分时间,但我已经想到了这一点。 Here's the code: 这是代码:

Sub Excel_QueryTable()

Sheet2.Cells.ClearContents

Dim oCn As ADODB.Connection
Dim oRS As ADODB.Recordset
Dim ConnString As String
Dim SQL As String

Dim qt As QueryTable

ConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\t.xlsm;Extended Properties=Excel 8.0;Persist Security Info=False"
Set oCn = New ADODB.Connection
oCn.ConnectionString = ConnString
oCn.Open

SQL = "Select * from [Sheet1$] WHERE type='man'"

Set oRS = New ADODB.Recordset
oRS.Source = SQL
oRS.ActiveConnection = oCn
oRS.Open

Set qt = Worksheets(2).QueryTables.Add(Connection:=oRS, _
Destination:=Range("A1"))

qt.Refresh

If oRS.State <> adStateClosed Then
oRS.Close
End If

If Not oRS Is Nothing Then Set oRS = Nothing
If Not oCn Is Nothing Then Set oCn = Nothing

End Sub

To get this working on your own workbook, you'll need to change the Data Source path to the name of the file youre using. 要使这个工作在您自己的工作簿上,您需要将Data Source路径更改为您正在使用的文件的名称。

[Sheet1$] in the query is the name of the sheet you are selecting from (leave in the $ ). 查询中的[Sheet1$]是您选择的工作表的名称(留在$ )。

Worksheets(2) is the number of the sheet where you are creating the dynamic table. Worksheets(2)是要创建动态表的工作表编号。

Additionally, you'll need to enable one of the the Microsoft Active X Data Objects libraries by going to Tools>References in the VBA editor in excel. 此外,您需要通过转到Excel中VBA编辑器中的Tools>References来启用其中一个Microsoft Active X Data Objects库。

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

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