patriciaxxx
Programmer
I have the following code which copies the recordset from an Access query to a linked Excel workbook, and it works.
I need to modify it so it first deletes any/all rows which have data in them from the worksheet (but not the first row which is the header).
Any help will be much appreciated.
I need to modify it so it first deletes any/all rows which have data in them from the worksheet (but not the first row which is the header).
Any help will be much appreciated.
Code:
Private Sub CopyRecordsetToExcel(SQL As String, con As ADODB.Connection)
Dim rs As New ADODB.Recordset
Dim x
Dim i As Integer, y As Integer
Dim xlApp As Excel.Application
Dim xlwbBook As Excel.Workbook, xlwbAddin As Excel.Workbook
Dim xlwsSheet As Excel.Worksheet
Dim rnData As Excel.Range
Dim stFile As String, stAddin As String
Dim rng As Range
stFile = CurrentProject.Path & "\LinkedTables.xls"
'Instantiate a new session with the COM-Object Excel.exe.
Set xlApp = New Excel.Application
Set xlwbBook = xlApp.Workbooks.Open(stFile)
Set xlwsSheet = xlwbBook.Worksheets("Sheet2")
xlwsSheet.Activate
'Getting the first cell to input the data.
xlwsSheet.Cells.Select '.SpecialCells(xlCellTypeLastCell).Select
y = xlApp.ActiveCell.Column - 1
xlApp.ActiveCell.Offset(1, -y).Select
x = xlwsSheet.Application.ActiveCell.Cells(2, 1).Address '.Cells.Address
'Opening the recordset based on the SQL query and saving the data in the Excel worksheet.
rs.CursorLocation = adUseClient
If rs.State = adStateOpen Then
rs.Close
End If
rs.Open SQL, con
If rs.RecordCount > 0 Then
rs.MoveFirst
x = "A2" 'Replace(x, "$", "")
y = Mid(x, 2)
Set rng = xlwsSheet.Range(x)
xlwsSheet.Range(x).CopyFromRecordset rs
End If
xlwbBook.Close True
xlApp.Quit
Set xlwsSheet = Nothing
Set xlwbBook = Nothing
Set xlApp = Nothing
End Sub