I am trying to open a pre-saved excel file then put data in to it from an SQL query.
what's actually happening with the code below is that it opens the pre-saved excel as intended, but the it opens a new workbook and pastes the data in to it.
How can I paste the data only in to the pre-saved excel?
what's actually happening with the code below is that it opens the pre-saved excel as intended, but the it opens a new workbook and pastes the data in to it.
How can I paste the data only in to the pre-saved excel?
Code:
Public Sub ExportQuery(ByVal Query As String, ByVal ShowToUser As Boolean, ByVal TabName As String, ByVal TabCount As Integer, ByRef xlApp As Excel.Application, ByRef xlWB As Object)
'This will export a query to Excel and display it, or save it to a path if requested.
Dim rst As DAO.Recordset
Dim rstA As DAO.Recordset
Dim xlSh As Excel.Worksheet
Dim i As Long
Dim ID As String
Dim sql As String: sql = ""
Set rst = CurrentDb.OpenRecordset(Query, dbOpenDynaset, dbSeeChanges)
Set rstA = CurrentDb.OpenRecordset("SELECT DISTINCT [Extension Reference] FROM CFR")
xlApp.Workbooks.Open "FILE PATH HERE", True, False
With xlApp
.Visible = ShowToUser
If TabCount < 1 Then
Set xlWB = .Workbooks.Add
Set xlSh = xlWB.Worksheets(xlWB.Worksheets.Count)
With xlSh
.Name = "ID"
.Select
.Range("A2") = "FullFITID"
.Range("A3").CopyFromRecordset rstA
Set xlSh = xlWB.Worksheets(xlWB.Worksheets.Count)
xlWB.Worksheets.Add After:=xlSh
.Select
End With
Else
Set xlSh = xlWB.Worksheets(xlWB.Worksheets.Count)
xlWB.Worksheets.Add After:=xlSh
End If
End With
Set xlSh = xlWB.Worksheets(xlWB.Worksheets.Count)
With xlSh
.Name = TabName
.Select
.Range("A2").CopyFromRecordset rst
For i = 1 To rst.Fields.Count
.Cells(1, i).Value = rst.Fields(i - 1).Name
Next i
xlApp.Cells.EntireColumn.AutoFit
End With
'Set xlSh = xlWB.Worksheets(xlWB.Worksheets("ID").Select)
'With xlSh
' Add formula to excel
' .Range("B2").Select
' ActiveCell.FormulaR1C1 = "='Tariff code'!R[-1]C"
' Range("B2").Select
' Selection.AutoFill Destination:=Range("B2:D2"), Type:=xlFillDefault
' Range("B2:D2").Select
' Range("B3").Select
' ActiveCell.FormulaR1C1 = _
' "=INDEX('Tariff code'!C,MATCH(ID!RC1,'Tariff code'!C1,0))"
' Range("B3").Select
' Selection.AutoFill Destination:=Range("B3:D3"), Type:=xlFillDefault
' Range("B3:D3").Select
' Selection.AutoFill Destination:=Range("B3:D89395")
' Range("B3:D150000").Select
' Cells.Select
' Cells.EntireColumn.AutoFit
'End With
End Sub