excel vba - 在电子表格上查询

too*_*oop 6 sql excel vba excel-vba

如果我有这两个表:

资源

目标

SQL

结果

是否有某种excel vba代码(使用ADO)可以实现这些期望的结果,可以利用我在SQL表中放置的任何查询? 进展

Nig*_*nan 8

Here's some VBA code that allows you to read an Excel range using the text SQL driver. It's quite a complex example, but I'm guessing that you came here because you're a fairly advanced user with a more complex problem than the examples we see on other sites.

Before I post the code in full, here's the original 'sample usage' comment in the core function, FetchXLRecordSet:

__PRE__

It's clunky, forcing you to name the tables (or list the range addresses in full) when you run the query, but it simplifies the code.

__PRE__

And finally, Writing a Recordset to a Range - the code would be trivial if it wasn't for all the errors you have to handle:

__PRE__

Let me know how you get on. As always, watch out for formatting glitches: I've never got the <code> tags to work on this site, and <PRE> isn't always respected by textboxes when the preformatted text contains quotes and HTML entities.

Postscript: Running SQL on Excel 'Table' Objects

For completeness, here's the code for a barebones 'read Excel Table objects with SQL' function that handles all the text-file hacking in the background.

I'm posting it now, a while after my original answer went up, because everyone's using the rich 'table' object for tabulated data in Excel:

__PRE__
...And the full listing (give or take a couple of functions in the previous code dump) is:
__PRE__

Share and enjoy: this is all a horrible hack, but it gives you a stable SQL platform.

And we still don't have a stable 'native' platform for SQL on Excel: the Microsoft.ACE.OLEDB.14.0 Excel data provider still has the same memory leak as Microsoft.Jet.OLEDB.4.0 and the Excel ODBC driver that preceded it, twenty years ago.


Fio*_*ala 1

一些注意事项:

sFullName = ActiveWorkbook.FullName
sSheet = ActiveSheet.Name

Set cn = CreateObject("adodb.connection")
scn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
& sFullName _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"

cn.Open scn

Set rs = CreateObject("adodb.recordset")

For Each c In Sheet4.UsedRange
    sSQL = sSQL & c.Value & " "
Next

rs.Open sSQL, cn

Sheet5.Range("a10").CopyFromRecordset rs
Run Code Online (Sandbox Code Playgroud)