| 
UID525积分3148精华贡献 威望 活跃度 D豆 在线时间 小时注册时间2002-1-14最后登录1970-1-1 
 | 
 
| 
Import data from Access to Excel (ADO)
×
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册 
    With the procedure below you can import data from an Access table to a worksheet.
 
 Sub ADOImportFromAccessTable(DBFullName As String, _
 TableName As String, TargetRange As Range)
 ' Example: ADOImportFromAccessTable "C:\FolderName\DataBaseName.mdb", _
 "TableName", Range("C1")
 Dim cn As ADODB.Connection, rs As ADODB.Recordset, intColIndex As Integer
 Set TargetRange = TargetRange.Cells(1, 1)
 ' open the database
 Set cn = New ADODB.Connection
 cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & _
 DBFullName & ";"
 Set rs = New ADODB.Recordset
 With rs
 ' open the recordset
 .Open TableName, cn, adOpenStatic, adLockOptimistic, adCmdTable
 ' all records
 '.Open "SELECT * FROM " & TableName & _
 " WHERE [FieldName] = 'MyCriteria'", cn, , , adCmdText
 ' filter records
 
 RS2WS rs, TargetRange ' write data from the recordset to the worksheet
 
 '        ' optional approach for Excel 2000 or later (RS2WS is not necessary)
 '        For intColIndex = 0 To rs.Fields.Count - 1 ' the field names
 '            TargetRange.Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
 '        Next
 '        TargetRange.Offset(1, 0).CopyFromRecordset rs ' the recordset data
 
 End With
 rs.Close
 Set rs = Nothing
 cn.Close
 Set cn = Nothing
 End Sub
 
 ' RS2WS rs, Range("A3") ' rs is an ADO recordset variable
 
 Sub RS2WS(rs As ADODB.Recordset, TargetCell As Range)
 Dim f As Integer, r As Long, c As Long
 If rs Is Nothing Then Exit Sub
 If rs.State <> adStateOpen Then Exit Sub
 If TargetCell Is Nothing Then Exit Sub
 
 With Application
 .Calculation = xlCalculationManual
 .ScreenUpdating = False
 .StatusBar = "Writing data from recordset..."
 End With
 
 With TargetCell.Cells(1, 1)
 r = .Row
 c = .Column
 End With
 
 With TargetCell.Parent
 .Range(.Cells(r, c), .Cells(.Rows.Count, c + rs.Fields.Count - 1)).Clear
 ' clear existing contents
 ' write column headers
 For f = 0 To rs.Fields.Count - 1
 On Error Resume Next
 .Cells(r, c + f).Formula = rs.Fields(f).Name
 On Error GoTo 0
 Next f
 ' write records
 On Error Resume Next
 rs.MoveFirst
 On Error GoTo 0
 Do While Not rs.EOF
 r = r + 1
 For f = 0 To rs.Fields.Count - 1
 On Error Resume Next
 .Cells(r, c + f).Formula = rs.Fields(f).Value
 On Error GoTo 0
 Next f
 rs.MoveNext
 Loop
 .Rows(TargetCell.Cells(1, 1).Row).Font.Bold = True
 .Columns("A:IV").AutoFit
 End With
 
 With Application
 .StatusBar = False
 .Calculation = xlCalculationAutomatic
 .ScreenUpdating = True
 End With
 End Sub
 | 
 |