Convert VBA to .NET / iLogic

<?xml encoding=”UTF-8″>By Adam Nagy

Most of the sample code I publish is in VBA because that is by far the best place to test things out: it’s part of Inventor, it has intelli-sense, lets you step through code, you can place break points, use Watches window to check variable values, see all the objects and their functions and properties in the Object Browser, etc. 

When you try to convert VBA code to .NET / iLogic then the 2 main things you need to be aware of are these. I’ll show them through trying to run this VBA code from an iLogic rule:

Sub MySubMethod()
Dim doc As Document
Set doc = ThisApplication.ActiveDocument
Call MsgBox(doc.DisplayName)
End Sub
Sub MyMainMethod()
' Do something
' Then call another method
Call MySubMethod
End Sub

1) Main function needs to be the first

ILogicError1

If you have multiple methods then the first one should be the one where the whole code execution starts and should be named Sub Main(). In case of my sample I need to move Sub MyMainMethod() to the top of the code and rename it to Sub Main()

2) No Let/Set

ILogicError2

You simply have to delete the “Set” keywords from your code

The final iLogic code:

Sub Main()
' Do something
' Then call another method
Call MySubMethod
End Sub
Sub MySubMethod()
Dim doc As Document
doc = ThisApplication.ActiveDocument
Call MsgBox(doc.DisplayName)
End Sub

One more thing which is not necessary but I think worth changing is moving from On Error Resume Next to Try/Catch. So instead of doing this:  

On Error Resume Next
Dim doc As PartDocument
doc = ThisApplication.ActiveDocument
If Err.Number = 0 Then
Call MsgBox(doc.DisplayName)
Else
Call MsgBox("No active part document")
End If
On Error Goto 0

… you would do this:

Dim doc As PartDocument
Try
doc = ThisApplication.ActiveDocument
Call MsgBox(doc.DisplayName)
Catch
Call MsgBox("No active part document")
End Try

Comments

2 responses to “Convert VBA to .NET / iLogic”

  1. Kay Rethmeier Avatar
    Kay Rethmeier

    Hi,
    will there be a code translator to transfer code between iLogic and VBA? For example a couple of online code translators are available like https://kalkicode.com/ai/code-translator.
    Bye
    Kay

  2. I don’t think we are planning to provide anything, but there seem to be some translators between VBA and VB.NET, e.g. http://www.tooloscope.com/en/IT-tools/migrate-excel-vba-to-vb-net.php
    Have not tried any of them though.

Leave a Reply

Discover more from Autodesk Developer Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading