Importing Data from Access using Excel VBA in data

2019-08-24 10:09发布

I have a macro that pulls a sample of data from Access. The Access data first column [ID] is sorted numerically from 1 to the end of data. The macro below takes user's input (start point and end point) to get a sample.

It sometimes returns the data not sorted as in the database. For example, if I enter start point 3,500 and end point 3,999. The first row of data in excel is 3533 to 3,627. Then the next row is 3,500 to 3,532. Then 3,628 to 3,999.

The problem is consistent at the same start/end points.

I went through the database and there are no issues.

Sub GetAccessData(StartofData As Long, EndofData As Long, WS As Worksheet, WB_Path As String)
Dim DBFullName As String
Dim Connect As String, Source As String
Dim Connection As ADODB.Connection
Dim Recordset As ADODB.Recordset
Dim Col As Long
Dim x As Long
Application.ScreenUpdating = False

'DataBase Path
DBFullName = WB_Path & "\RawData - Template.accdb"

'Open the Connection
Set Connection = New ADODB.Connection
Connect = "Provider=Microsoft.ACE.OLEDB.12.0;"
Connect = Connect & "Data Source=" & DBFullName & ";"
Connection.Open ConnectionString:=Connect

'Create a RecordSet
Set Recordset = New ADODB.Recordset
' Client-side cursor
Recordset.CursorLocation = adUseClient

With Recordset
    Source = "SELECT * FROM  CT_RawData WHERE [ID] BETWEEN " & StartofData & " AND " & EndofData
    .Open Source:=Source, ActiveConnection:=Connection
    'WS.Activate
    On Error Resume Next
    WS.Range("A3").CopyFromRecordset Recordset
    'Sheets("Chart1").Activate
End With
End Sub

0条回答
登录 后发表回答