VBA Error help

VBA Error help

Anonymous
Not applicable
722 Views
2 Replies
Message 1 of 3

VBA Error help

Anonymous
Not applicable

The first time I run this VBA code, the first message box displays the correct number of sheets, and then throws an error "Object Required" on the "Set oSheetCount = ".  Subsequent attempts result in "Object Required" immediately. 

 

Translating the code to iLogic works perfectly, but i am trying to learn VBA, and successively VB.NET.  Can someone help me understand why this is happening?

 

VBA Code

 

Public Sub SheetCount()

    Dim oDoc As DrawingDocument
    Set oDoc = ThisApplication.ActiveDocument
        
    MsgBox (oDoc.Sheets.Count)
        
    Dim oSheetCount As Integer
    Set oSheetCount = oDoc.Sheets.Count
        
    MsgBox (oSheetCount)
       
End Sub

iLogic

 

Dim oDoc as DrawingDocument = ThisApplication.ActiveDocument

MessageBox.Show(oDoc.Sheets.Count)

Dim oSheetCount As Integer = oDoc.Sheets.Count

MessageBox.Show(oSheetCount)
0 Likes
Accepted solutions (1)
723 Views
2 Replies
Replies (2)
Message 2 of 3

JaneFan
Autodesk
Autodesk
Accepted solution

Hello @Anonymous,

 

Removing "Set" from oSheetCount can make it work. oSheetCount is integer type so Set is not working for this type.

Public Sub SheetCount()

    Dim oDoc As DrawingDocument
    Set oDoc = ThisApplication.ActiveDocument
       
    MsgBox (oDoc.Sheets.Count)
       
    Dim oSheetCount As Integer
    oSheetCount = oDoc.Sheets.Count
       
    MsgBox (oSheetCount)
      
End Sub




Jane Fan
Inventor/Fusion QA Engineer
0 Likes
Message 3 of 3

Anonymous
Not applicable

Thanks for that JaneFan,

 

After researching why this worked, I'm  stating it here for future reference. 

 

Set Statement

Generally, when you use Set to assign an object reference to a variable, no copy of the object is created for that variable. Instead, a reference to the object is created. More than one object variable can refer to the same object. Because such variables are references to the object rather than copies of the object, any change in the object is reflected in all variables that refer to it. However, when you use the New keyword in the Set statement, you are actually creating an instance of the object.

 

Let Statement (optional, and often omitted (the solution in this case))

Let statements can be used to assign one record variable to another only when both variables are of the same user-defined type. Use the LSet statement to assign record variables of different user-defined types. Use the Set statement to assign object references to variables.

 

Thanks again!

 

 

 

0 Likes