Execute a function in an open instance of Access from a .NET application

元气小坏坏 提交于 2019-12-11 06:57:37

问题


I have an Access database and a C# app. The C# app does some things to some tables in Access and I want to refresh the Access form when the C# code ends. I tried to do this:

void refresh()
    {
Access.Application acApp = new Access.ApplicationClass();//create msaccess application

object oMissing = System.Reflection.Missing.Value;
//Run the Test macro in the module
acApp.Run("Function_refresh",ref oMissing,ref oMissing,ref oMissing,ref oMissing,
ref oMissing,ref oMissing,ref oMissing,ref oMissing,
ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing
,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing
,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing
,ref oMissing,ref oMissing,ref oMissing,ref oMissing,ref oMissing
,ref oMissing,ref oMissing);
acApp.Quit();//exit application
        }

My code works if the DB is closed. How can I use the function if the database is already open?

edit: The C# does some inserts in an Access table, so when it ends I want to refresh the form when it is open.


回答1:


My code works, if the DB is closed. How can I use the function if the database is already open?

I just tried the following code for a button on a C# Winforms application and it worked for me. If I have my database open in Access and the form "LogForm" is open in the database then when I click the button on my C# form the Access form is updated.

private void button1_Click(object sender, EventArgs e)
{
    Microsoft.Office.Interop.Access.Application acApp;
    this.Activate();
    acApp = (Microsoft.Office.Interop.Access.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Access.Application");
    Microsoft.Office.Interop.Access.Dao.Database cdb = acApp.CurrentDb();
    cdb.Execute("INSERT INTO LogTable (LogEntry) VALUES ('Entry added ' & Now())");
    acApp.Forms["LogForm"].Requery();
}

The code is adapted from the Microsoft Support article

How to use Visual C# to automate a running instance of an Office program



来源:https://stackoverflow.com/questions/28364168/execute-a-function-in-an-open-instance-of-access-from-a-net-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!