怎么在excel中正确使用SQL的查询语句
展开全部
ALT+F11,打开VBE,插入一个模块,把以下代码复制进去:
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,就是要放查询结果的区域左上角那个单元格。
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,就是要放查询结果的区域左上角那个单元格。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询