0

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
4
  • 1
    Whether your data is sorted by ID in your source object is irrelevant. Add an ORDER BY clause to your SELECT statement and see if that makes a difference. Commented Nov 15, 2018 at 23:31
  • 1
    Yep, that did it. Pretty new to this. Thanks. Source = "SELECT * FROM CT_RawData WHERE [ID] BETWEEN " & StartofData & " AND " & EndofData & " ORDER BY [ID]" Commented Nov 15, 2018 at 23:35
  • Just out of curiosity - what was driving the odd sorting that was being pulled in. Commented Nov 15, 2018 at 23:43
  • I have seen this behavior too, even with just 500 lines of data. Commented Nov 15, 2018 at 23:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.