[英]Copy Query from Access to Excel
I'm having some problems when I try to import a Query from Access to Excel. 尝试从Access导入Excel时出现问题。
Some days ago I programmed a code (with some help of Google haha) to import a Table from Access to Excel: 几天前,我编写了代码(在Google哈哈的帮助下),以便从Access到Excel导入表:
Sub importQuery(DBFullName As String, data_sht As Worksheet)
Dim cn As Object, rs As Object
Dim i As Integer
Dim TargetRange As Range
Dim rows As Long, cols As Long
Dim dataEmpty As Boolean
Dim lastColString As String
data_sht.Activate
Application.ScreenUpdating = False
Set TargetRange = data_sht.Range("A1")
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=Microsoft.Ace.OLEDB.12.0; Data Source=" & DBFullName & ";" 'the Access file is .accdb
Set rs = CreateObject("ADODB.Recordset")
rs.Open "SELECT * FROM C_Paso2_SM_Cuplas", cn, , , adCmdUnspecified
cols = rs.Fields.Count
rows = data_sht.Range("A" & data_sht.rows.Count).End(xlUp).Row
' Copy titles of the Access Query
For i = 0 To (cols - 1)
TargetRange.Offset(0, i).Value = rs.Fields(i).Name
Next
' Copy data
TargetRange.Offset(1, 0).CopyFromRecordset rs
End Sub
That code works but when I do this: 该代码有效,但是当我这样做时:
rs.Open "SELECT * FROM C_Paso2_SM_Cuplas", cn, , , adCmdUnspecified
I'm importing another Query called C_Paso 1 _SM_Cuplas, from the same file. 我正在从同一文件中导入另一个名为C_Paso 1 _SM_Cuplas的查询。 What can I do? 我能做什么? Why am I importing C_Paso 1 _SM_Cuplas when I say C_Paso 2 _SM_Cuplas? 为什么说C_Paso 2 _SM_Cuplas时要导入C_Paso 1 _SM_Cuplas? Is there other possibility to import an Access Query to Excel? 还有其他将Access Query导入Excel的可能性吗?
Try this DAO solution. 试试这个DAO解决方案。
Sub ImportFromAccessToExcel()
Dim db1 As Database
Dim db2 As Database
Dim recSet As Recordset
Dim strConnect As String
Set db1 = OpenDatabase("C:\Database1.mdb")
strConnect = db1.QueryDefs("Query3").Connect _
& "DSN=myDsn;USERNAME=myID;PWD=myPassword"
Set db2 = OpenDatabase("", False, False, strConnect)
db2.Close
Set db2 = Nothing
Set recSet = db1.OpenRecordset("Query3")
With ActiveSheet.QueryTables.Add(Connection:=recSet, Destination:=Range("$A$4"))
.Name = "Connection"
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.Refresh BackgroundQuery:=False
End With
recSet.Close
db1.Close
Set recSet = Nothing
Set db1 = Nothing
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.