How do I handle a string array returned from a C# Method in VBA

房东的猫 提交于 2019-12-06 03:44:55

Updated Answer: Instead of returning string[], try returning object instead:

[ComVisible(true)]
public class PostcodeFinder
{
    public object SearchPostcodes(string postCode)
    {
        //Unchanged code

        return (object)resultsToReturn;
    }
}

You will still get the type mismatch error in the immediate window when performing ?results (you need to specify an index such as ?results(0)), however you are able to iterate through the array as:

results = c.SearchPostcodes(postcodeToSearch)
Dim result As Variant
For Each result In results
    MsgBox result
Next result

Original Answer: You need to instantiate the PostcodeFinder class. In your btnSearch_Click subroutine, try:

Dim c As New PostcodeFinder
Dim results

results = c.SearchPostcodes(postcodeToSearch)

Alternatively, you could separate the declaration from the instantiation as:

Dim c As PostcodeFinder
Dim results
Set c = New PostcodeFinder

results = c.SearchPostcodes(postcodeToSearch)

In VBA, the element in a For Each loop must be a Variant when looping thru an array.

Dim v As Variant
For Each v In Array("value 1", "value 2", "value 3")
    ' do something with v
Next v

Typing ?results in the Immediate Window is giving an error because VBA can't auto-convert an array into a string. You have to either tell it which part of the array you want, ?results(2), or use Join(sourcearray, delimiter) to tell it how to convert the array, ?Join(results, ",").

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!