u011364766
best丨Zp
采纳率30%
2017-06-06 04:08

.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条回答

  • caozhy 从今以后生命中的每一秒都属于我爱的人 4年前

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

    点赞 1 评论 复制链接分享

相关推荐