.net 调用Excel 中 VBA宏 返回值-2146826273

private void button1_Click(object sender, EventArgs e)
{
try
{

            object oMissing = System.Reflection.Missing.Value;

            Excel.Application oExcel = new Excel.Application();
            oExcel.Visible = true;
            Excel.Workbooks oBooks = oExcel.Workbooks;
            Excel._Workbook oBook = null;
            oBook = oBooks.Open(Application.StartupPath.ToString()+"\\ts.xlsm", oMissing, oMissing,
                oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);


           // RunMacro(oExcel, new Object[] { "Sheet1.DoKbTest" });
           // RunMacro(oExcel, new Object[] { "Sheet1.DoKbTestWithParameter", "传个参数给你" });
            RunMacro(oExcel, new Object[] { "Sheet1.aa()" });

            oBook.Close(false, oMissing, oMissing);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook);
            oBook = null;
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks);
            oBooks = null;
            oExcel.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);
            oExcel = null;




        }
        catch (Exception ex)
        {

            Debug.Print(ex.ToString());
        }



    }


    /// <summary>
    /// 调用excel中VBA  
    /// </summary>
    /// <param name="oApp"></param>
    /// <param name="oRunArgs"></param>
    private void RunMacro(object oApp, object[] oRunArgs)
    {


        try
        {
            object o = null;             
           o= oApp.GetType().InvokeMember("Run",
            System.Reflection.BindingFlags.Default |
            System.Reflection.BindingFlags.InvokeMethod,
            null, oApp, oRunArgs);


        }
        catch (Exception ex)
        {

            Debug.Print(ex.ToString());
        }


    }

    这个是EXCEL中代码

Public Function aa()
aa = "1123"
End Function

程序返回的O 一直是 -2146826273 。。无论VBA中返回什么值都是 -2146826273

1个回答

电脑里安装完整版的excel了没有,注意勾选“.net编程性”选项。
还不行,重新引用下excel

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问