问题
I am creating an C# application that must call subs in an Access mdb database file.
I've created a test sub in the mdb file and I can call it from C# and also pass it parameters. That all works fine, but I want to pass a result back to C#. I know I can't do this with a function, so is it possible to pass the variables by reference, then vba can change the variables and I get my result back? I tried the following, but it doesn't work. Anybody know if this is possible?
Thanks
VBA test sub:
Sub test(Byref p1 As String)
p1="bar"
MsgBox p1
End Sub
Call it from C#:
Access.Application oAccess = new Access.Application();
oAccess.Visible = true;
oAccess.OpenCurrentDatabase("d:\\tmp\\test1.mdb", false, "");
string t;
t = "foo"
oAccess.Run("test", t);
//t still equals "foo" at this point, it should be equal to "bar"
回答1:
For a scalar (a simple number, string, or Boolean) the system makes a copy of the current value and passes this copy to the called procedure. Upon return from the called procedure the system discards the copy. So, even if the called procedure changes the value of a ByVal argument, there is no way for that change to propagate back to the caller.
Take a look at this for explanation on passing scalar values. As explained on the page, callee can modify the property of the object, thereby caller can see the modified value (in case of using an object).
Another alternative, is to use a return value from the function.
EDIT:
Function test(p1 As String) as String
test = "Bar"
End Function
c#
t = "foo"
t = oAccess.Run("test", t);
来源:https://stackoverflow.com/questions/17393305/receiving-values-back-after-calling-a-sub-in-access-through-net