我正在建立一份薪酬工作表。这些表格和关键信息位于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/