C#Excelマクロの呼び出し
8118 ワード
using System;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication1
{
/// <summary>
/// Excel VBA
/// </summary>
public class ExcelMacroHelper
{
/// <summary>
/// Excel
/// </summary>
/// <param name="excelFilePath">Excel </param>
/// <param name="macroName"> </param>
/// <param name="parameters"> </param>
/// <param name="rtnValue"> </param>
public void RunExcelMacro(Excel.Application app, string macroName, object[] parameters, out object rtnValue)
{
// ,
object[] paraObjects;
if (parameters == null)
paraObjects = new object[] { macroName };
else
{
int paraLength = parameters.Length;
paraObjects = new object[paraLength + 1];
paraObjects[0] = macroName;
for (int i = 0; i < paraLength; i++)
paraObjects[i + 1] = parameters[i];
}
rtnValue = this.RunMacro(app, paraObjects);
}
/// <summary>
///
/// </summary>
/// <param name="oApp">Excel </param>
/// <param name="oRunArgs"> ( , )</param>
/// <returns> </returns>
private object RunMacro(object app, object[] oRunArgs)
{
object objRtn; //
//
objRtn = app.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, app, oRunArgs);
return objRtn;
}
}
}
使用方法
app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = true;
string filePath = @"F:\test.xlsm";
Workbook wb = app.Workbooks.Open(filePath);
object objRtn = new object();
// Excel , Excel
ExcelMacroHelper excelMacroHelper = new ExcelMacroHelper();
excelMacroHelper.RunExcelMacro(app,"hong",new Object[] { " " },out objRtn);
MessageBox.Show(objRtn.ToString());
Excelに「モジュール」を追加
Function hong(title As String)
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
ws.Cells(1, 1).Value = title & ",123"
hong = title & ",123"
End Function