excel - 从 Excel 调用 Access VBA 函数

标签 excel ms-access vba

我正在建立一份薪酬工作表。这些表格和关键信息位于access数据库Compensation.accdb中,该数据库具有根据代理契约(Contract)计算补偿的功能。如果代理是“REP”,则 Access VBA 函数执行一项计算,如果代理是 SRP,则执行另一项计算。几个不同的用户想要从 Excel 调用此函数(顺便说一句,MS Office 2013)。这个想法是用户在电子表格中更改或输入数量,电子表格调用 Compensation.accdb VBA 函数。 Compensation.accdb 进行计算,并将值传递回原始电子表格。

这是Compensation.accdb VBA 代码:

Option Compare Database

Function AutoComp(WritingRepContract As String) As Integer 'Auto insurance
    'Debug.Print WritingRepContract
    If WritingRepContract = "REP" Then
        AutoComp = 1 'Compensation formula for Rep will go here
    End If

    If WritingRepContract = "SRP" Then
        AutoComp = 2 'Compensation formula for Senior Rep will go here, etc.
    End If

End Function

这是 Excel VBA 代码:

Public Sub Worksheet_Change(ByVal Target As Range) 
    'Is there a better way than this???
    Dim WritingLevel As String
    If Target.Address = "$B$8" Then 
    'This is the cell where one would enter Auto value.
        If Target.Value = 1 Then 'just a test to see if working
            WritingLevel = "REP"
        Else
            WritingLevel = "SRP"
        End If
        CallAutoComp (WritingLevel)
    End If

End Sub

Sub CallAutoComp(WritingLevel)
    Dim appAccess As Access.Application
    Dim test As Integer

    Set appAccess = New Access.Application
    Debug.Print appAccess.Eval("AutoComp(WritingLevel)") 
    'A test to see what is happening
    With appAccess
        .OpenCurrentDatabase "C:\Mypath\Compensation.ACCDB"
        .Visible = False ' Useful for debugging when true
        .Eval ("AutoComp(WritingLevel)")
    End With
    test = appAccess.Eval("AutoComp(WritingLevel)")
    With appAccess
        .CloseCurrentDatabase
        .Quit
    End With

End Sub

当我更改 B8 中的值时,我得到:

Run-time error 2425: The expression you entered has a function name that Microsoft Access can't find.

它不喜欢以下语句(所有三个语句均出现相同的 2425 错误):

Debug.Print statement
.Eval ("AutoComp(WritingLevel))") statement
test = appAccess.Eval("AutoComp(WritingLevel)")

我尝试了多个版本的单引号和双引号以及围绕 WritingLevel"&" 但没有成功。

我不确定这是否是最好的方法。这是我第一次尝试这样的跨平台,但如果我能得到这个问题的答案,那将对很多人有很大的帮助。如果我能以一种更简单的方式调用该函数,就像调用内部 Excel 函数那样,那就太好了。我已经用不同版本的搜索字符串搜索了几天,但没有成功。

当我用 AutoComp(SRP)AutoComp(REP) 替换 AutoComp(WritingLevel) 时,它工作正常。

最佳答案

尝试改用Application.Run。像这样的东西:

Application.Run ("AutoComp", WritingLevel)

我做过类似的事情,但不完全像你正在做的事情。就我而言,函数名称是一个变量,传递给它的值是一个常量,但理论上我的代码应该可以工作。

关于excel - 从 Excel 调用 Access VBA 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24622348/

相关文章:

c# - 在 C# 中使用 Access 2010 数据库

ms-access - Access 报告不显示数据或失败并显示 "Multi-level GROUP BY cause not allowed in subquery."

vba - Excel-VBA。移动公式而不复制它们

excel - 工作表中的 Active X 组合框

excel - 显示警报 VBA

vba - 如何检测单元格是否由 "=IF()"公式而不是用户更改

excel - 如果单元格范围包含 "active",则增加 excel 值

winforms - VBA 窗体可以有流式布局吗?

arrays - 将不连续的命名范围放入数组中,然后放入不同工作表中的行中

vba - 选择 - ShapeRange 和图表问题