dot NET DLL for use with VBA - Reference the vba created class within the C# class?

henry appliancedude.com 21 Reputation points
2022-01-11T15:49:01.143+00:00

Have a class that I can call from vba, so far so good. I need to refer to the new instance of the class that was created in vba and not make a new class.
I'll try to illustrate (I did not include the Com statements as this is just an simplified example)

Given the following code:

VBA CODE

Private WithEvents MyClass

Private Sub MyCommand_Click()
Set c = New MyClass
MsgBox c.i
Set c = Nothing
End Sub

C# CODE

public class MyClass
{
public int i;

public static void Main()
{
    var mc = new MyClass();   <<<<< This is the crux of the question- see below
    mc.i = 10;
}

}

In the main() function, I need to refer to the class that was already created by the VBA call.
I don't want to create yet another instance.

In pseudo-code, it might look something like this: Set mc = "the class created in VBA"

How to deal with this? Sorry, I know this seems very basic, but I am an old man who last played with vb.6. Feel free to tell me I'm doing it all wrong.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,251 questions
{count} votes

Accepted answer
  1. Viorel 112.1K Reputation points
    2022-01-11T16:18:13.267+00:00

    If you declare it like this:

    public class MyClass
    {
       public int i;
    
       public void Main()
       {
          . . .
       }
    }
    

    then you can call it using c.Main( ) from VBA. Inside the Main and other members, use this to refer to the current object (created in VBA), for example: this.i = 10.


0 additional answers

Sort by: Most helpful