【发布时间】:2014-01-05 00:36:32
【问题描述】:
当我尝试在 C# 应用程序的 excel 文件中运行 vba 脚本时遇到问题。 我的代码是:
public void RunMacro(string path, string macro)
{
Excel.Application app = null;
Excel.Workbooks workbooks = null;
Excel.Workbook workbook = null;
app = new Excel.Application();
if (app == null)
return;
app.Visible = false;
ChangeCulture();
workbooks = app.Workbooks;
workbook = workbooks.Open(path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
LogWrapper.Debug("Run Macro start");
app.Run(macro, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing
, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing
, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing
, Type.Missing, Type.Missing, Type.Missing);
LogWrapper.Debug("Run macro finish");
workbook.Close(false, Type.Missing, Type.Missing);
app.Quit();
ReleaseObject(app);
ReleaseObject(workbook);
}
我在我的网络浏览器中单击按钮后运行此方法,并且浏览器一直工作(“等待本地主机...”)。我在 Firebug 中看不到任何请求。 我的 LogWrapper 只记录第一个信息(“运行宏开始”)。 在事件查看器中没有关于此执行的任何信息。 在任务管理器进程中,EXCEL.EXE 使用 100% 的处理器。 而且我等了半个小时结果还是什么都没有。
当我将 vba 脚本名称更改为运行时,我收到错误消息,指出在 excel 文件中找不到 vba 脚本。 我的vba脚本很简单:
Sub start()
Range("A3").Select
ActiveCell.Value = "def"
Range("A4").Select
End Sub
有人知道我应该在哪里搜索有关此问题的信息吗?
【问题讨论】:
-
试试
app.Run(macro); -
好的。问题在于宏内容。无法编辑单元格值,有人知道为什么吗?
-
您收到什么异常?
-
我看不出宏代码有什么问题。如果工作表受到保护,它将不会写入单元格。顺便说一句,您可以将这一行更改为
Range("A3").Value = "def"INTERESTING READ 此外,如果您没有完全限定您的范围对象,您将承担很大的风险。你在写哪张表?最后一点。你真的需要这个单行宏吗?你也可以从 C# 中做到这一点。 -
@SiddharthRout 感谢 Range 的建议。此宏仅作为示例。将来会运行更复杂的宏。我没有收到任何异常。