Full disclosure I posted this code on another forum, but it was for a different questions that was resolved.
I have a piece of MS Access code that opens an excel instance. Once open Access appends new records to a table. Think most recent monthly detail. This works great. My problem is that after the data is appended, I want to sort the table in descending order. Below is my code.
I should mention the one line of code works as expected if I just paste it into the regular excel file, (not the instance opened by MS Access)
'Change True to False if you do not want the workbook to be
'Visible when the code is running
excelApp.Visible = False
'Open the target workbook
Set targetWorkbook = excelApp.Workbooks.Open(sFilePath & sDepartment & sSubFolder & sDepartment & "_YTD_DETAIL" & ".xlsm")
Debug.Print targetWorkbook.Name
' Debug.Print "Excel File " & sDepartment & " Opened"
' Debug.Print sFilePath & sDepartment & sSubFolder & sDepartment & "_YTD_DETAIL" & ".xlsm"
'Dim tbl As ListObject
Dim sTable As String
Dim LastRow As Long
For Each oSheet In targetWorkbook.Worksheets
If oSheet.Name = "EXHIBIT_2_DETAIL_2020" Then
Debug.Print oSheet.Name
With oSheet.ListObjects("DETAIL_2020")
LastRow = oSheet.Range("DETAIL_2020").Rows.Count + FirstRow
Debug.Print LastRow
.Range("A" & LastRow).CopyFromRecordset rsQuery_expense
' THE FOLLOWING LINE OF CODE!!
' Sort table descending newest date first )WIP
.Range("A1", Range("D" & Rows.Count).End(xlUp)).Sort [E2], xlDescending, Header:=xlYes
End With
'Debug.Print "Completed the export of Expense Detail For " & sDepartment
ElseIf oSheet.Name = "HEAD_TEMP_COUNT" Then
oSheet.Range("D3").CopyFromRecordset rsQuery_head
oSheet.Range("D9").CopyFromRecordset rsQuery_temp_head
Debug.Print "Completed the export of Head Count and Temp Head Count For " & sDepartment
ElseIf oSheet.Name = "PIVOTS" Then
oSheet.Range("A1").Value = "EXPENSES REPORT UPDATED: " & Now
Debug.Print "Report Updated to reflect " & Now & " Timestamp"
ElseIf oSheet.Name = "ACTUALS_VS_PLAN" Then
oSheet.Range("A1").Value = Month(Date) - 1
End If 'There will be other sheets in workbook, but the 2 above are the only ones i need to interact with.
Next oSheet
When I run it as pasted above I get a compiler error saying "Sub or Function not defined" With the word "Range highlighted.
I'm sure I am making this harder than it needs to be. Any help or guideline at this point would be greatly appreciated.
Bookmarks