簡體   English   中英

在access vba中調用excel函數

[英]Call excel function in access vba

我有一個需要從訪問中調用的 excel 子程序。 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

您可能希望從 Excel 的對象模型中使用 Application.Run。 您向它傳遞一個字符串,例如“QuickRDA.JavaCallBacks.GetQuickTab”作為宏名稱,其中 QuickRDA 是 Excel VBA 項目的名稱,JavaCallBacks 是該 VBA 項目中的 VBA 模塊的名稱,GetQuickTab 是該 VBA 模塊中的函數。

訪問中

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。

那么,您想從 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

在此處輸入圖片說明

要從 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM