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