I pull a query off SQL Server using an access front-end. I then export the recordset to a new Excel workbook. I want to then use excel to run code that I have in Access. It
I've put this code in the "ThisWorkbook" object in Excel:
Public Sub TestScript()
Debug.Print "Hello"
End Sub
And then successfully called it from Access using a button on a form:
Private Sub cmdRunExcel_Click()
Dim xl As Excel.Application
Set xl = CreateObject("Excel.Application")
xl.Visible = True
xl.Workbooks.Open "C:/Your/FolderPath/And/FileName.xlsx", True, False
xl.Run "ThisWorkbook.TestScript"
Set xl = Nothing
End Sub
Admittedly I've not given it a lot of code to run, but here the code is at least running on Excel, from Excel... which must be better than trying to run code on Excel from Access.
Update: See if you can create the module from Access to Excel by testing this (I can't test it properly because I'm using a work computer and it seems to be not letting me run this type of code due to security settings)
Private Sub cmdRunExcel_Click()
Dim xl As Excel.Application
Dim myWrkBk As Excel.Workbook
Dim myModule As VBComponent
Dim strVb As String
Set xl = CreateObject("Excel.Application")
xl.Visible = True
xl.Workbooks.Open "C:/Your/FolderPath/And/FileName.xlsx", True, False
Set myWrkBk = xl.Workbooks.Add
Set myModule = myWrkBk.VBProject.VBComponents.Add(vbext_ct_StdModule)
strVb = "Public Sub TestScript()" & vbCrLf _
& "Debug.Print 'Hello'" _
& "End Sub"
myModule.CodeModule.AddFromString strVb
' xl.Run "ThisWorkbook.TestScript"
Set myModule = Nothing
Set myWrkBk = Nothing
Set xl = Nothing
End Sub