如何使用 C# 在 microsoft excel 中运行回归函数(或任何工具/内置宏)

问题描述 投票:0回答:2

我想知道如何使用 C# 在 microsoft excel 中运行回归函数。目前我正在按照本教程在 Excel 中自动回归:

http://www.michaelcodes.net/2018/09/using-c-to-automate-linear-regression.html

一切正常,但我正在使用的函数(教程中的 x1 作为变量):

myExcelInteropApplication.Run(@"Regress", sheet.Range($"$A$1:$A${rowCount}"),
                sheet.Range($"$B$1:$B${rowCount}"), false, true, Type.Missing, sheet.Range("$D$1"),
                true, false, false, false, Type.Missing, false);

抛出以下错误:

Exception thrown: 'System.Runtime.InteropServices.COMException' in System.Dynamic.dll
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in System.Dynamic.dll
Cannot run the macro 'Regress'. The macro may not be available in this workbook or all macros may be disabled.

我已经检查过数据分析选项卡在Excel中可用,并且我可以在Excel本身中成功手动执行回归函数。程序的其余部分还可以打开 Excel,插入单元格并关闭它。

我的假设是我尝试调用的宏拼写错误,或者 excel 中的某些内容阻止我调用该工具/宏。

我无法找到参考表或记录宏/工具名称的东西,因此任何示例将不胜感激。

提前致谢!

c# excel vba interop excel-addins
2个回答
0
投票

您需要引用包含您尝试运行的宏的 .xlam 文件的名称。对于你想做的事情,我认为应该是这样的:

myExcelInteropApplication.Run("ATPVBAEN.XLAM!Regress", sheet.Range($"$A$1:$A${rowCount}"),
                sheet.Range($"$B$1:$B${rowCount}"), false, true, Type.Missing, sheet.Range("$D$1"),
                true, false, false, false, Type.Missing, false);

0
投票
//Instantiate a new class for the Interop Excel App
Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
//If you want to see the Excel Application Open Up
oXL.Visible = true;
//Enter the Path that stores your Excel App -> Analysis Lib
oXL.RegisterXLL("C:\\Program Files\\Microsoft Office\\root\\Office16\\Library\\Analysis\\ANALYS32.xll");
//Example : If Cell B5 to B9 contains your y-values:
Microsoft.Office.Interop.Excel.Range yValues = Linearity_Sheet.Range[Linearity_Sheet.Cells[5, 2], Linearity_Sheet.Cells[9, 2]];
//Example : If Cell A5 to A9 contains your x-values:
Microsoft.Office.Interop.Excel.Range xValues = Linearity_Sheet.Range[Linearity_Sheet.Cells[5, 1], Linearity_Sheet.Cells[9, 1]];
//Run Data Analysis:
oXL.Run("REGRESS", yValues, xValues);

希望这有帮助。谢谢你。

© www.soinside.com 2019 - 2024. All rights reserved.