Hello,
I have working code to copy the matching records of an Access table into an Excel worksheet, but now I am trying to modify this code so that I can select a couple of specific fields from the table instead of just copying all of the fields (there are 15 fields in the table, but I only actually need 4 of them for this particular report).
Here is the code I am currently using to copy all of the fields over with the matching records:
Code:
Const myDB = "DSD Errors DB tester.mdb"
Private Sub CommandButton4_Click()
' Test Field Select button
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim sSQL As String
sSQL = "SELECT * FROM DSD_Invoice_Requests WHERE `Paid?` IS NULL"
Range("A2:O65536").ClearContents
Application.EnableEvents = False
' Create the database connection
Set cnn = New ADODB.Connection
myFile = ThisWorkbook.Path & "\" & myDB
With cnn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.Open myFile
End With
' Create the recordset
Set rst = New ADODB.Recordset
rst.CursorLocation = adUseServer
rst.Open Source:=sSQL, ActiveConnection:=cnn, _
CursorType:=adOpenForwardOnly, LockType:=adLockOptimistic, Options:=adCmdText
' Transfer data to Excel
Range("A2").CopyFromRecordset rst
' Close the connection and clean up references
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
Application.EnableEvents = True
myRow = Range("A65536").End(xlUp).Row - 1
MsgBox ("Finished loading " & myRow & " record(s)."), vbInformation, "Data Loaded"
End Sub
How can I modify this so that I put specific fields from the table into columns in Excel that will not line up with the layout of the table? For the sake of the example, let's say that I need fields 2, 4, 6, and 8 of the table to go into columns 1, 2, 3, and 4 in Excel.
Thanks in advance for any help with this.