I have button on an Access form that opens an existing Excel spreadsheet. All the code is listed below. But the one thing I am having trouble is the following line: "Worksheets("2015").Range("A5").CopyFromRecord set rst". Is there anyway the use variables instead of the "2015" and the "A5" which is the worksheet name and range?
Private Sub btnAddToExcel_Click()
Dim strYear As String
Dim fn As String
Dim ln As String
Dim ph As String
Dim db As Database
Dim rst As Recordset
Set db = DBEngine(0)(0)
Set rst = db.OpenRecordset("Customers", dbOpenDynaset)
Dim objXLApp As Object
Dim objXLBook As Object
Set objXLApp = CreateObject("Excel.Application")
Set objXLBook = objXLApp.Workbooks.Open("C:\Dev\P&L.xls")
strYear = "2014"
With rst
fn = ![FirstName]
ln = ![LastName]
ph = ![Phone]
Worksheets("2015").Range("A5").CopyFromRecordset rst
End With
objXLApp.Application.Visible = True
End Sub