作者:乔山办公网日期:
返回目录:excel表格制作
ALT+F11,打开VBE,插入一个模块,7a686964616fe58685e5aeb9333把以下代码复制进去:
Sub dosql(sql, a As Range)
Dim Conn As Object
Set Conn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")
PathStr = ThisWorkbook.FullName
Select Case Application.Version * 1
Case Is <= 11
strConn = "Provider=Microsoft.Jet.Oledb.4.0;Extended Properties=excel 8.0;Data source=" & PathStr
Case Is >= 12
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathStr & ";Extended Properties=""Excel 12.0;HDR=YES"";"""
End Select
Conn.Open strConn
Set rst = Conn.Execute(sql)
If VBA.InStr(sql, "select") > 0 or VBA.InStr(sql, "Select") > 0 Then
With a.Parent
For i = 0 To rst.fields.Count - 1
.Cells(1, a.Column + i).EntireColumn.ClearContents
.Cells(1, a.Column + i) = rst.fields(i).Name
Next
End With
a.Offset(1).CopyFromRecordset rst
For i = 0 To rst.fields.Count - 1
a.Parent.Cells(1, a.Column + i).EntireColumn.AutoFit
Next
End If
Conn.Close
End Sub
Public Sub t()
'sql = "这里写你的查询语句"
dosql sql, [E1]
End Sub
1、记得运行代码前要保存工作簿
2、查询语句中,表名是[工作表名$]这样的格式
3、dosql sql, [E1]中的E1,就是要放查询结果的区域左上角那个单元格。
http://jingyan.baidu.com/article/c35dbcb0f18f448916fcbcfd.html
1、需要导入的数据百如图。
2、在excel中添加列,并写入拼装脚本。
3、鼠标往度下拖拽第一条数据单元格右下问角的点,完成所有的拖动。
4、选择带有答所需数据的单元格,并复制。
5、打开记事本专,粘贴,并一个个替换。
6、完成替换后,完整的sql语句就出来了属。
例如简单zd的从sheet1表中的数据取专到表二:
Sub 简单属查询()
Set cn = CreateObject("adodb.connection")
Set rs = CreateObject("adodb.recordset")
cn.Open "provider=microsoft.jet.oledb.4.0;Extended Properties='Excel 8.0';data source=" & ThisWorkbook.FullName
Sql = "select * from [sheet1$]"
Sheets(2).[A2].CopyFromRecordset cn.Execute(Sql)
MsgBox "取数据成功"
Sheets("sheet2").Select
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub