我在C#中编写了一个程序集,它返回一个字符串数组,C#代码如下:
[ComVisible(true)]
public class PostcodeFinder
{
public string[] SearchPostcodes(string postCode)
{
var searchService = new QuickAddress("http://x.x.x.x:xxxx/")
{Engine = QuickAddress.EngineTypes.Singleline, Flatten = true};
var mPicklist = searchService.Search("GBR", postCode, PromptSet.Types.OneLine);
var x = mPicklist.Picklist.Items.Count();
var resultsToReturn = new string[x];
for (var i = 0; i < x; i++)
{
resultsToReturn[i] = mPicklist.Picklist.Items[i].PartialAddress;
}
return resultsToReturn;
}
}
然后我构建了这个程序集,确保勾选属性中的Register for COM interop
框。然后在Microsoft Access中,我将.tlb
文件添加到引用中,并创建了一个包含几个控件的表单(其中一个是名为Listbox
的{{1}}控件。在主按钮控件下,我有以下VBA代码:
lstResults
编辑:这样运行没有错误,但是当我在下面放一些虚拟代码后我用Private Sub btnSearch_Click()
Dim postcodeToSearch As String
postcodeToSearch = Me.txtPostcode
Dim c As New PostcodeFinder
Dim results
results = c.SearchPostcodes(postcodeToSearch)
End Sub
查询立即窗口以允许我放置一个断点时,我收到以下错误:
运行时错误'13' - 类型不匹配
实际上我想在VBA中重写以下C#代码:
?results
提前致谢
答案 0 :(得分:3)
更新后的答案:请尝试返回string[]
,而不是返回object
:
[ComVisible(true)]
public class PostcodeFinder
{
public object SearchPostcodes(string postCode)
{
//Unchanged code
return (object)resultsToReturn;
}
}
执行?results
时,您仍会在即时窗口中出现类型不匹配错误(您需要指定一个索引,例如?results(0)
),但是您可以遍历数组:< / p>
results = c.SearchPostcodes(postcodeToSearch)
Dim result As Variant
For Each result In results
MsgBox result
Next result
原始答案:您需要实例化PostcodeFinder类。在btnSearch_Click子例程中,尝试:
Dim c As New PostcodeFinder
Dim results
results = c.SearchPostcodes(postcodeToSearch)
或者,您可以将声明与实例化分开为:
Dim c As PostcodeFinder
Dim results
Set c = New PostcodeFinder
results = c.SearchPostcodes(postcodeToSearch)
答案 1 :(得分:2)
在VBA中,For Each循环中的元素在循环数组时必须是Variant。
Dim v As Variant
For Each v In Array("value 1", "value 2", "value 3")
' do something with v
Next v
在立即窗口中键入?results
会出错,因为VBA无法将数组自动转换为字符串。您必须告诉它您想要的数组部分?results(2)
,或使用Join(sourcearray, delimiter)
告诉它如何转换数组?Join(results, ",")
。