Reputation: 1686
I've a sub in excel that needs to be called from access. Excel vba
Public Function testme(value As String) As String
Dim xlpath As String
Dim concate As String
xlpath=ActiveWorkbook.Path
value = ActiveWorkbook.Name
concate = xlpath & "\" & value
Let testme = concate
End Function
i need to call above method in one of the access method.How do i call it.
Sub Connect1()
Dim xlApp As Variant
'Set xlApp = CreateObject("Excel.Application")
'this will launch a blank copy of excel; you'll have to load workbooks
'xlApp.Visible = True
Set xlApp = GetObject(, "Excel.Application")
Let ans = xlApp.Application.Run("MyXLVBAProject.MyXLVBAModule.testme", 400)
'here ans has the string "500"
End Sub
Upvotes: 2
Views: 9485
Reputation: 20302
So, you want to trigger an Excel function from Access, or run an Excel subroutine from Access?
To run a function, you can do something like this.
Public Function FV(dblRate As Double, intNper As Integer, _
dblPmt As Double, dblPv As Double, _
intType As Integer) As Double
Dim xl As Object
Set xl = CreateObject("Excel.Application")
FV = xl.WorksheetFunction.FV(dblRate, intNper, dblPmt, dblPv, intType)
Set xl = Nothing
End Function
To run an Excel subroutine from Access, you can do the following.
Sub RunExcelMacro()
Dim xl As Object
'Step 1: Start Excel, then open the target workbook.
Set xl = CreateObject("Excel.Application")
xl.Workbooks.Open ("C:\Book1.xlsm")
'Step 2: Make Excel visible
xl.Visible = True
'Step 3: Run the target macro
xl.Run "MyMacro"
'Step 4: Close and save the workbook, then close Excel
xl.ActiveWorkbook.Close (True)
xl.Quit
'Step 5: Memory Clean up.
Set xl = Nothing
End Sub
Upvotes: 1
Reputation: 26646
You'll probably want to use Application.Run from Excel's object model. You pass it a string such as "QuickRDA.JavaCallBacks.GetQuickTab" for the macro name, where QuickRDA is the name of the Excel VBA project, JavaCallBacks is the name of the VBA module in that VBA project, and GetQuickTab is the name of the function in that VBA module.
In Access
Sub Connect()
Dim xlApp As Variant
Set xlApp = GetObject(, "Excel.Application")
'this will connect to an already open copy of excel, a bit easier for quick & dirty testing
Let ans = xlApp.Application.Run("MyXLVBAProject.MyXLVBAModule.testme")
End Sub
In Excel
Public Function testme() As String
Dim xlpath As String
Dim concate As String
Dim value as String
xlpath = ActiveWorkbook.Path
value = ActiveWorkbook.Name
concate = xlpath & "\" & value
Let testme = concate
End Function
-or simply-
Public Function testme() As String
Let testme = ActiveWorkbook.FullName
End Function
Remember that in Excel the function testme should be put in a module whose name is MyXLVBAModule, and that the project containing the module should be called MyXLVBAProject.
Upvotes: 2