|
Sub Query()
Dim Conn As Object, Rst As Object
Dim strConn As String, strSQL As String
Dim i As Integer, PathStr As String
Set Conn = CreateObject("ADODB.Connection")
Set Rst = CreateObject("ADODB.Recordset")
PathStr = ThisWorkbook.FullName '设置工作簿的完整路径和名称
strConn = "Provider=Microsoft.ACE.OLEDB.12.0; Extended Properties='Excel 12.0;HDR=YES;'; Data Source=" & ThisWorkbook.FullName
'设置SQL查询语句
strSQL = "SELECT [项目名称-3-1] as [项目名称],[问题类型-3-2] as [问题类型] FROM [tempsheet$]"
Conn.Open strConn '打开数据库链接
Set Rst = Conn.Execute(strSQL) '执行查询,并将结果输出到记录集对象,这里在极个别人的电脑上返回的是nothing,不知道是不是系统中少了某个文件,还是哪里没有设置好,望高人指点,不胜感激!!
With Sheet1
.Cells.Clear
For i = 0 To Rst.Fields.Count - 1 '填写标题
.Cells(1, i + 1) = Rst.Fields(i).Name
Next i
.Range("A2").CopyFromRecordset Rst
.Cells.EntireColumn.AutoFit '自动调整列宽
End With
Rst.Close '关闭数据库连接
Conn.Close
Set Conn = Nothing
Set Rst = Nothing
End Sub
|
|