question

StuartCoutts avatar image
0 Votes"
StuartCoutts asked StuartCoutts edited

Is it possible to assemble a function address from strings?

I am trying to simplify some code and make it a bit more dynamic.

Currently the code looks like this (simplified to aid in this question)...

 If x = "_One" Then
     Module_One.Main()
 Elseif x = "_Two"
     Module_Two.Main()
 Elseif x = "_Three"
     Module_Three.Main()
 ...
 Elseif x = <"_n">
     Module<_n>.Main()
 End If

...where depending on x as string, a function called "Main" in a module called Module<x> is then called.

Ideally I would like the code to function like this (i'm riffing on this code as I don't actually know if its even possible)...

 Dim ModuleName as Module = "Module" & x
 ModuleName.Main()

The closest example I can think of would be like when one builds a cell address from cell values, using indirect, in excel but instead of a cell address its a function address in different modules in vb.

dotnet-visual-basic
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Viorel-1 avatar image
0 Votes"
Viorel-1 answered Viorel-1 edited

Check this code:

 Dim x As String = "_Two"
 Dim ModuleName As String = "Module" & x
    
 Dim type As Type = Assembly.GetExecutingAssembly.GetTypes.First(Function(t) t.Name = ModuleName)
 Dim [sub] As MethodInfo = type.GetMethod("Main", BindingFlags.Static Or BindingFlags.Public Or BindingFlags.NonPublic)
    
 [sub].Invoke(Nothing, Nothing)

It assumes that the module is:

 Module Module_Two
    
     Public Sub Main()
         . . .
     End Sub
    
 End Module
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

StuartCoutts avatar image
0 Votes"
StuartCoutts answered StuartCoutts edited

That is incredible.

Three lines of code ive never used or even seen before.
Not sure how it works but it works exactly as I wanted.

I'm gona have to deconstruct that and learn exactly whats going on.

Cannot thank you enough.

You're a star!

Thanks again!

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.