c# enumerable class - compatible with VBA

后端 未结 2 1669
余生分开走
余生分开走 2021-01-05 09:29

Can anyone instruct me on how to code a C# enumerable class such that the \"for each\" construct in Excel VBA works properly? I tried this out with a test class called Peop

相关标签:
2条回答
  • 2021-01-05 09:58

    I came across this thread in Feb 2020 whilst experiencing the same problem with a class I wrote as a wrapper for a C# Dictionary.

    The get enumerator method in the class is

        public IEnumerator GetEnumerator()
        {
            foreach (KeyValuePair<dynamic, dynamic> myPair in MyKvp)
            {
                yield return new dynamic[] { myPair.Key, myPair.Value };
            }
        }
    

    I found that the DispId(-4) was successful when I added the attribute to the signature in the Interface.

    Before (in interface)

    IEnumerator GetEnumerator();
    

    Which prodeced an object does not know this methos error in VBA

    After (in interface)

    [DispId(-4)]
    IEnumerator GetEnumerator();
    

    This update allowed me to iterate using a For Each loop in VBA.

    0 讨论(0)
  • 2021-01-05 10:06

    Try adding [DispId(-4)] to your GetEnumerator() method. This flags it to be the DISPID_NEWENUM member. In order for VBA to work with a collection using For Each, it needs to implement _newEnum via COM.

    This can be done by implementing an Enumerator and attributing it with the proper DispId. This is typically done via implementing a custom interface with this specified, though there are other mechanisms available.

    0 讨论(0)
提交回复
热议问题