把excel当数据库来查询
Posted lcxsummer
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了把excel当数据库来查询相关的知识,希望对你有一定的参考价值。
Sub excel连接数据库() Dim Con As New ADODB.Connection Dim strCon, strsql As String Dim rs As ADODB.Recordset ‘设置记录集 Dim i, t, path_ path_ = ThisWorkbook.path & "" t = Timer
连接字符串 strCon = "Provider=Microsoft.Ace.OLEDB.12.0;Extended Properties=‘Excel 12.0;imex=0‘;Data Source=F: ewv511.xlsx"
关联多个文件查询 ‘ strsql = "select a.id,a.firstname,b.lastname from [a1$] a left join [Excel 8.0;hdr=1;imex=1;Database=C:UsersAdministratorDesktopa2.xlsx].[a2$] b on a.id=b.id"
表名的表示方式 [] 中括号包起来,里面是sheet名称+$符号 ‘ strsql = "select a.id,a.firstname,b.lastname from [EDM-10$] a left join [a2$] b on a.id=b.id" 有些数字查出来后会变成 1900-01-10 12:00:00,看起来是个日期,处理方式就是*1,让它重新变回数字 strsql = "select a.内部订单号,a.R * 1 from [CNC-11$] a where a.内部订单号 <> ‘内部订单‘ "
各种函数的使用,还可以嵌套,但是要注意嵌套的先后顺序,比如这个distinct,要达到真正的效果,就得在最外层
‘ strsql = " select distinct(UCASE(trim(a.D))) as id from [G-10$] a where a.D <> ‘内部订单‘ "
结果集合并,就是一个累加行的过程 ‘ strsql = "" ‘ strsql = strsql + " select distinct(UCASE(trim(a.D))) as id from [EDM-10$] a where a.D <> ‘内部订单‘ " ‘ strsql = strsql + " union " ‘ strsql = strsql + " select distinct(UCASE(trim(a.D))) as id from [G-10$] a where a.D <> ‘内部订单‘ " Con.Open strCon Set rs = Con.Execute(strsql)
这个是查询所有sheet的名字 ‘ Set rs = Con.OpenSchema(20) ‘adSchemaTables=20 ‘ Columns("A:A").NumberFormatLocal = "m""月""d""日"";@" For i = 0 To rs.Fields.Count - 1 Sheets("lcx").Cells(1, i + 1) = rs.Fields(i).Name Next i Sheets("lcx").Cells(2, 9).CopyFromRecordset rs rs.Close Con.Close Set rs = Nothing Set Con = Nothing Debug.Print "提取完毕" & "耗时" & Round(Timer - t, 4) & "秒" End Sub
需要引用的project有3个:
补充
Sub lcxreaddata() Dim fname As String, path As String, cnn As Object, rst As ADODB.Recordset, sql As String
使用createobject的方式,不需要引入相应的project,可以直接使用 Set cnn = CreateObject("ADODB.Connection") fname = "11.xlsx" path = "F: ewv5" & fname cnn.Open "Provider=Microsoft.Ace.OLEDB.12.0;Extended Properties=‘Excel 12.0;imex=0‘;Data Source=" & path
$符号后面可以加查询的范围 ‘ sql = "SELECT [Actual],[Upper Tol] FROM [Report$a13:f100] where Characteristic=‘" & cname & "‘"
有特殊符号的字段,用中括号括起来就可以使用了,否则需要打开表替换字段名称,关闭的时候还要还原,是不是好傻的操作,都怪以前没有get到这个技能 ‘ sql = " SELECT [新模/修模],[实际产出(H)] FROM [CNC-11$a:r] where [实际产出(H)] <> 0 "
where后面的条件匹配要注意类型,字符串类型的字段用字符串匹配,数字类型的列用数字匹配,否则会报类型不匹配的错误,还有就是,如果两个表关联查询的时候,两个关联的字段的类型必须一致,否则也会报类型不匹配的错误 sql = " SELECT [新模/修模],[实际产出(H)] FROM [CNC-11$a:r] where trim([新模/修模]) <> ‘‘ " Set rst = cnn.Execute(sql) Sheets.Add For i = 0 To rst.Fields.Count - 1 Cells(1, i + 1) = rst.Fields(i).Name Next i Cells(2, 1).CopyFromRecordset rst cnn.Close Set rst = Nothing Set cnn = Nothing End Sub
以上是关于把excel当数据库来查询的主要内容,如果未能解决你的问题,请参考以下文章
使用POI把查询到的数据表数据导出到Excel中,一个表一个sheet.[超详细]