从VSTO代码调用VBA函数时出错

时间:2010-08-05 16:48:18

标签: c# excel-vba vsto excel-2007 vba

我的一个.xlt文件的模块中有以下VBA代码:

Public Sub SetShapeTop(ByVal shapeName As String, ByVal topValue As Single)
  ThisWorkbook.ActiveSheet.Shapes(shapeName).Top = topValue
End Sub

在我的VSTO加载项中,我有以下C#代码尝试调用该VBA函数:

m_worksheet.Application.Run("SetShapeTop", kv.Key, kv.Value, 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);

该行引发异常,如下所示:

(Excerpt from my log4net logs)

[Exception: COMException]
{Target: Cluster Report}
{Invoked Method: Macro execution}
{Target Method: Cluster Report}
{Parameters: }
{Message: Cannot run the macro 'SetShapeTop'. The macro may not be available in this workbook or all macros may be disabled.}
{Stack trace: 
Server stack trace: 


Exception rethrown at [0]: 
  at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
  at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
  at Microsoft.Office.Interop.Excel._Application.Run(Object Macro, Object Arg1, Object Arg2, Object Arg3, Object Arg4, Object Arg5, Object Arg6, Object Arg7, Object Arg8, Object Arg9, Object Arg10, Object Arg11, Object Arg12, Object Arg13, Object Arg14, Object Arg15, Object Arg16, Object Arg17, Object Arg18, Object Arg19, Object Arg20, Object Arg21, Object Arg22, Object Arg23, Object Arg24, Object Arg25, Object Arg26, Object Arg27, Object Arg28, Object Arg29, Object Arg30)
  at MSA.Excel.ClusterPresenter.RenderReport(IReportData reportData, IResponseReportParameters reportParams, Worksheet worksheet) in C:\workspace\MSABasketlink\2.0\MSA.Library.UI\Presentation\ClusterPresenter.cs:line 647} 

我在这里遗漏了什么吗?如果有人能指出我正确的方向,我真的很感激......!

2 个答案:

答案 0 :(得分:1)

这是一项安全限制。

转到Excel中的信任中心,然后检查信任对VBA项目对象模型的访问权限。

答案 1 :(得分:0)

您的呼叫代码是否在VSTO Addin的启动中运行?如果是这样,可能并非所有东西都已加载。解决这个问题的一种(愚蠢的)方法就是运行它直到它工作。抱歉VB.NET,但C#应该是类似的

Dim hasRun As Integer
Do 
    hasRun = Me.Application.Run("SetShapeTop", kv.Key, kv.Value)
Until hasRun > 0

另外,请看一下这篇文章:Extend Your VBA Code With VSTO

  

有一点需要注意的是这段代码   如果适当的访问权限将失败   未授予VBA宏。