I have VBA code to create an Access database from three Excel spreadsheets. This has worked successfully for a good while. One of the Spreadsheets, obtained from an external source, contains a header row above the column headings and two comments rows at the end. The user sometimes forgets to remove these rows before running the VBA code to create the database. As a result I have tried to incorporate this with the Access code. Without success!
I can delete the first row with a problem, but cannot get the single line to find the last used row to work. I use:
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
I just get 'sub or function' error. Searching for help produces a number of example that use:
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
but neither work.
If i remove this, the firts
The attached code is the relevant section - ignore the 'exit sub', it's there for testing.
I can delete the first row with a problem, but cannot get the single line to find the last used row to work. I use:
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
I just get 'sub or function' error. Searching for help produces a number of example that use:
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
but neither work.
If i remove this, the firts
The attached code is the relevant section - ignore the 'exit sub', it's there for testing.
Code:
If fDialog.Show = True Then
filename = fDialog.SelectedItems(1)
MsgBox filename
'Sub UpdateExcelFromAccess()
' Set a reference to the Excel Application
Dim xlApp As Object
Dim LastRow As Long
Set xlApp = CreateObject("Excel.Application")
' Specify the Excel workbook and worksheet
Dim xlWorkbook As Object
Dim xlWorksheet As Object
'Set xlWorkbook = xlApp.Workbooks.Open("C:\Path\To\Your\Workbook.xlsx") ' Replace with the actual path
Set xlWorkbook = xlApp.Workbooks.Open(filename) ' Replace with the actual path
Set xlWorksheet = xlWorkbook.Sheets("Sheet1") ' Replace with the actual sheet name
xlWorksheet.Activate
' Find the last row
With ActiveSheet
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
End With
' Delete the last two rows
xlWorksheet.Rows(LastRow - 1 & ":" & LastRow).Delete
' Delete first row
xlWorksheet.Rows(1).EntireRow.Delete
' Save and close the Excel workbook
MsgBox xlWorkbook.Sheets("Sheet1").Cells(1, 1)
xlWorkbook.Save
xlWorkbook.Close
' Quit Excel
xlApp.Quit
' Release the objects
Set xlWorksheet = Nothing
Set xlWorkbook = Nothing
Set xlApp = Nothing
Exit Sub
DoCmd.TransferSpreadsheet acImport, 9, "Groups", filename, True
End If