与Microsoft Access互操作不与用户会话交互 [英] Interop with Microsoft Access does not interact with User's session

查看:47
本文介绍了与Microsoft Access互操作不与用户会话交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从.Net向Microsoft Access数据库中注入一段VBA代码.

I am injecting a piece of VBA code into a Microsoft Access database from .Net.

这只是一行代码,它运行一个Macro.宏所做的全部工作就是在模块内部运行VBA代码块.

It is just a single line of code, which runs a Macro. All the Macro does is run a block of VBA code inside a module.

我遇到的问题是,所有这些都发生在我什至看不到的新MSAccess会话中,而不是用户当前已打开的会话中.

The issue I am having is that this all happens in a new MSAccess session, which I can't even see, instead of the session the user currently has open.

是否有可能与用户当前的MSAccess会话进行交互?这样做的全部目的是在每次发生.Net事件时,在MSAccess会话中打开一个特定的表单.我的C#代码如下:

Is it possible to, instead, have this interact with the users current MSAccess session? The whole point of this is to open a particular form inside the MSAccess session on every occurence of a .Net event. My C# code is below:

using Microsoft.Office.Interop.Access;

var msAccess = new Application();

msAccess.OpenCurrentDatabase(@"x:\foo\bar.accdb", false);
msAccess.DoCmd.RunMacro("macCTI");
msAccess.CloseCurrentDatabase();

谢谢

推荐答案

如果您有一个正在运行的Access实例,则可以使用

If you have a single instance of Access running you could use Marshal.GetActiveObject:

using Microsoft.Office.Interop.Access;
using System.Runtime.InteropServices
...
try
{
    var msAccess = (Application)Marshal.GetActiveObject("Access.Application");
    msAccess.DoCmd.RunMacro("macCTI");
}
catch (COMException ex)
{
    // handle error
}

或者,如果有多个正在运行,并且没有两个实例打开相同的数据库,则可以使用

Alternatively, if more than one are running, and no two instances have the same database open, you could use Marshal.BindToMoniker:

var msAccess = (Application) Marshal.BindToMoniker(@"x:\foo\bar.accdb"); 


注意::此 Microsoft知识库文章具有这样说:

Note: This Microsoft knowledge base article has this to say:

COM服务器是一次性使用(多个实例)还是多次使用(单实例)可能会影响您使用的决定GetActiveObject以获取对该服务器的引用.因为可能可以有多个Word,Excel或Microsoft Access实例运行中,特定服务器上的GetActiveObject可能会返回一个实例你没想到的.首先在ROT通常是GetActiveObject返回的实例.如果您想要获取对特定正在运行的实例的自动化参考Word,Excel或Microsoft Access的名称使用BindToMoniker在该实例中打开的文件.对于多用途(单个实例)服务器(例如PowerPoint),这没关系,因为自动化参考指向相同的运行实例.

这篇关于与Microsoft Access互操作不与用户会话交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆