在access vba中调用excel函数

时间:2014-03-20 20:37:18

标签: vba excel-vba access-vba excel

我需要从访问中调用excel中的sub。 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

我需要在其中一种访问方法中调用上面的方法。我怎么称呼它。

 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

2 个答案:

答案 0 :(得分:2)

您可能希望从Excel的对象模型中使用Application.Run。您为宏名称传递了一个字符串,如“QuickRDA.JavaCallBacks.GetQuickTab”,其中QuickRDA是Excel VBA项目的名称,JavaCallBacks是该VBA项目中VBA模块的名称,GetQuickTab是该名称。在该VBA模块中运行。

在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

在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

- 或简单 -

Public Function testme() As String
    Let testme = ActiveWorkbook.FullName
End Function

请记住,在Excel中,函数testme应该放在名为MyXLVBAModule的模块中,并且包含该模块的项目应该被称为MyXLVBAProject。

答案 1 :(得分:0)

那么,您想要从Access触发Excel功能,还是从Access运行Excel子程序?

要运行某个功能,您可以执行以下操作。

  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

enter image description here

要从Access运行Excel子例程,您可以执行以下操作。

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