从 VBA 调用 C# 时出现对象类型错误
我有一个用 C# 编写的 Excel 插件,我试图从 Excel 中的 VBA 调用。在 VBA 中,我生成了几个要传递的数组:
Dim Identifiers() As Variant
Dim Variables() As Variant
Dim Times() As Variant
...
Dim QaddIn As COMAddIn
Dim QTool As Object
Dim results As Variant
Set QaddIn = Application.COMAddIns("QTool")
QaddIn.Connect = True
Set QTool = QaddIn.Object
results = QTool.GetQData(datasetName, Identifiers, Variables, Times, timeString)
GetQData
在 C# 中定义为:
string[] GetQData(string DatasetName, object[] Identifiers, object[] Variables, object[] TimeCodes,
string TimeString);
但是当我运行代码时,VBA 抛出错误 object of type 'system.object[*]' can be转换为“system.object[]”类型的对象
。相同的代码可以很好地传递使用静态长度定义的变体数组,如 Dim Identifiers(3) As Variant
中所示。我现在想要通过的有什么区别?
I have a an Excel addin written in C# I am trying to call from VBA in Excel. In VBA I generate several arrays to pass:
Dim Identifiers() As Variant
Dim Variables() As Variant
Dim Times() As Variant
...
Dim QaddIn As COMAddIn
Dim QTool As Object
Dim results As Variant
Set QaddIn = Application.COMAddIns("QTool")
QaddIn.Connect = True
Set QTool = QaddIn.Object
results = QTool.GetQData(datasetName, Identifiers, Variables, Times, timeString)
GetQData
is defined in C# as:
string[] GetQData(string DatasetName, object[] Identifiers, object[] Variables, object[] TimeCodes,
string TimeString);
But when I run the code, VBA throws the error object of type 'system.object[*]' cannot be converted to object of type 'system.object[]'
. This same code worked fine passing variant arrays defined with a static length, as in Dim Identifiers(3) As Variant
. What is the difference between what I am trying to pass now?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是我试图传递给 C# 的数组从 1 开始索引,也就是说,它是一个 Array(1 to 5) 而不是 Array(0 to 4)< /代码>。不幸的是,传递从 1 开始索引的数组失败,因为
Range.Value
和所有WorksheetFunction
方法返回从 1 开始索引的数组。我在 VBA 中编写了以下代码来重新索引在传递它们之前,我的数组从零开始:
The problem was that the array I was attempting to pass to C# was indexed from 1, that is, it was an
Array(1 to 5)
rather than anArray(0 to 4)
. It's unfortunate that passing an array indexed from 1 fails, becauseRange.Value
and all of theWorksheetFunction
methods return arrays indexed from 1.I wrote the following code in VBA to reindex my arrays from zero before passing them:
问题是变长数组和定长数组不一样。一般来说,vba 的宽容度很高,因此您通常可以侥幸逃脱,但 C# 却不然。无法确定您的意思是将数组转换为固定长度数组。您应该在 Identifiers 对象上寻找一种方法,将其转换为固定长度的数组。这可能看起来像:
尽管我不确定该方法的确切命名,所以请使用代码完成来查找它。
The problem is that variable length arrays and fixed length arrays are not the same. vba in general will be pretty forgiving so you generally get away with it, but C# isn't. It can't be sure that you mean to convert the array to a fixed length array. You should look for a method on the Identifiers object to convert it to a fixed length array. This will probably then look something like:
I'm not sure the exact naming of that method though so use the code completion to look for it.