Community
Inventor Programming - iLogic, Macros, AddIns & Apprentice
Inventor iLogic, Macros, AddIns & Apprentice Forum. Share your knowledge, ask questions, and explore popular Inventor topics related to programming, creating add-ins, macros, working with the API or creating iLogic tools.
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Marco and VBA Programing Help

18 REPLIES 18
Reply
Message 1 of 19
AJ1227
1988 Views, 18 Replies

Marco and VBA Programing Help

Hello everyone,

 

I am new to macros and VBA programing and I could use your help.  I started out at my current company as a CNC programmer and have experience heavily modifying MasterCAM post processors and was hoping this would be a little easier.  However, with the post processors I was able to start with a default processor that had code already in place which made it much easier; I'm just at a loss at where to start on this because I do not know the programming language or structure.

 

I'm trying to create a macro that will do some of the work that is cumbersome and time consuming for us.  For one of our customers, we have to change our drawings to the customers title block and then save as AutoCAD and publish a PDF.  Our current customer title block requires us to resize and move drawings to fit but I have created a new customer title block that matches the size and shape of ours to eliminate the need to move things.

 

I would like to be able to open all drawings associated with an assembly and run a macro to do the following:

 

Public Sub Replace_Titleblock

-Begin with active document (first open drawing)

-Delete current titleblock from all sheets

-Insert new titleblock in all sheets from referenced template drawing

End Sub

 

Public Sub Save_As_CAD

-Begin with active document (still on first drawing)

-Save as AutoCAD dwg (specify location in code?)

End Sub

 

Public Sub Export_PDF

-Begin with active document (still on first drawing)

-Publish PDF (Same location as AutoCAD dwg)

-Close file

End Sub

 

Public Sub Repeat Process

-Begin with next open drawing and repeat process until all drawings closed

End Sub

 

If I had a list of all words and their definitions that were involved in the programming language I could probably figure out the structure by looking at other macros posted online.  I found one link that was supposed to provide this but the website was no longer available.

 

Any help to get me going in the right direction will be much appreciated!

 

Thanks!

18 REPLIES 18
Message 2 of 19
mehatfie
in reply to: AJ1227

Hi AJ1227,

 

If the only tasks you wish to perform are the ones you've listed, I don't see why the Task Scheduler cannot perform them:

 

http://wikihelp.autodesk.com/Inventor/enu/2013/Help/1310-Autodesk1310/1956-Task_Sch1956

 

You should be able to most things there.

 

As well, you can use the Drawing Resource Transfer Wizard to Convert all of the title blocks:

 

http://wikihelp.autodesk.com/Inventor_LT/enu/2013/Help/0305-Autodesk305/0649-Collabor649/0679-Tools6...

 

I believe both programs come with your subscription to Autodesk programs

 

 

Also, if you go to the "Tools" tab within Inventor and open the "VBA Editor," you'll be able to access the API and Object Browser. Once the Editor has opened, press F2 in order to hot key the Object Browser and have access to all of the classes with their respective help files. (Help files can be accessed by pressing F1 on a highlighted object)

 

 

Regards

Mitch

 

Let me know if it helps... Kudos if it works!!!

Message 3 of 19
AJ1227
in reply to: mehatfie

Hey Mitch,

 

Thanks for the info.  I would still like to setup a macro to complete these tasks (I've got some reading material to look at over the holidays) beause I've run into a few problems with your methods.  Maybe you know of a better way of doing things than I am trying.

 

1.  When using the Drawing Resource Transfer Wizard, I have to use the same title block names for the title block to be replaced, else the title block is just inserted into the drawing resources.  This works fine but I have to run all files through twice because our assembly and part drawing templates have different names for the title blocks.  This is why I wanted a macro to delete current title block and replace with new (regardless of name).

 

2.  I then setup Task Scheduler to export my files as AutoCAD dwg and then print files as PDF.  This process is rather cumbersome because I am selecting files from multiple folders (causing me to go through the file selection process repeatedly) and then for every file I must specify a new save location.  At least with the print to PDF process I am promted for a save location and after selecting the folder once, it prompts save to that folder.

 

I still think it would be much easier to open all files related to an assembly and run a VBA program.

 

Thanks for your help.  If I'm not using the Drawing Resource Transfer Wizard and Task Scheduler properly, please let me know what I'm doing wrong.

Message 4 of 19
AJ1227
in reply to: AJ1227

Ok, I have my macro started.

 

1. Start by opening the drawing needing a new template (source drawing).

2. Macro opens template drawing.

3. Selects title block.

4. Deletes title block from source drawing and replaces with template title block.

5. I'm stuck.  I need it to close my template drawing (oNewDocument)

 

After I close the template, I want to save the source document, then save as AutoCAD dwg, then publish PDF, then close source document and start process again with next open document.  If I can get the "close oNewDocument" part I think I can get the saves and save as'.

 

 

 

Public Sub TitleBlockCopy()
    Dim oSourceDocument As DrawingDocument
    Set oSourceDocument = ThisApplication.ActiveDocument
   
    ' Open the template drawing to copy the title block from.
    Dim oNewDocument As DrawingDocument
    Set oNewDocument = ThisApplication.Documents.Open("C:\TEMPLATE DRAWING LOCATION")
   
    ' Get the new title block definition.
    Dim oNewTitleBlockDef As TitleBlockDefinition
    Set oNewTitleBlockDef = oNewDocument.ActiveSheet.TitleBlock.Definition
   
    ' Set the new title block definition.
    Dim oSourceTitleBlockDef As TitleBlockDefinition
    Set oSourceTitleBlockDef = oNewTitleBlockDef.CopyTo(oSourceDocument)
   
    ' Iterate through the sheets.
    Dim oSheet As Sheet
    For Each oSheet In oSourceDocument.Sheets
        oSheet.Activate
       
        oSheet.TitleBlock.Delete
        Call oSheet.AddTitleBlock(oSourceTitleBlockDef)
                   
    ' Close template drawing.
    ?????
                    
    Next
End Sub

 

 

I've tried many different variations of things here based on the help menu with no luck.  Any help is greatly appreciated.

 

Thanks,

Message 5 of 19
ChrisVandeVoorde
in reply to: AJ1227

You need to open your template with the visible boolean to false, than you won't need to close it.

 

Sub TitleBlockCopy()

    Dim oSourceDocument As DrawingDocument
    Set oSourceDocument = ThisApplication.ActiveDocument
   
    ' Open the template drawing to copy the title block from.
    Dim oNewDocument As DrawingDocument
    ' if you put false here at the end it will not open visible, so you won't need to close it
    Set oNewDocument = ThisApplication.Documents.Open("C:template.idw", False)
   
    ' Get the new title block definition.
    Dim oNewTitleBlockDef As TitleBlockDefinition
    'make sure that in your template.idw the needed titleblock is active
    Set oNewTitleBlockDef = oNewDocument.ActiveSheet.TitleBlock.Definition
   
    ' Set the new title block definition.
    Dim oSourceTitleBlockDef As TitleBlockDefinition
    Set oSourceTitleBlockDef = oNewTitleBlockDef.CopyTo(oSourceDocument)
   
    ' Iterate through the sheets.
    Dim oSheet As Sheet
    For Each oSheet In oSourceDocument.Sheets
        oSheet.Activate
        
        'don't forget the Call command here
        Call oSheet.TitleBlock.Delete
        Call oSheet.AddTitleBlock(oSourceTitleBlockDef)
            
     ' not needed anymore
    ' Close template drawing.
    '?????
     Next
End Sub

 and to help you with the rest of the code. This is a piece of code that I call instant PDF. It saves a drawing to a pdf. The save location of the PDF is identical to that of the .idw. So make sure that the .idw is saved first otherwise it won't work! If you want a fixed location, just check out the code and set oDataMedium accordingly.

 

Public Sub InstantPDF()
    ' Enable error handling.
    On Error GoTo ErrorFound
    
    ' Get the PDF translator Add-In.
    Dim PDFAddIn As TranslatorAddIn
    Set PDFAddIn = ThisApplication.ApplicationAddIns.ItemById("{0AC6FD96-2F4D-42CE-8BE0-8AEA580399E4}")

    'Set a reference to the active document (the document to be published).
    Dim oDocument As Document
    Set oDocument = ThisApplication.ActiveDocument

    Dim oContext As TranslationContext
    Set oContext = ThisApplication.TransientObjects.CreateTranslationContext
    oContext.Type = kFileBrowseIOMechanism

    ' Create a NameValueMap object
    Dim oOptions As NameValueMap
    Set oOptions = ThisApplication.TransientObjects.CreateNameValueMap

    ' Create a DataMedium object
    Dim oDataMedium As DataMedium
    Set oDataMedium = ThisApplication.TransientObjects.CreateDataMedium

    ' Check whether the translator has 'SaveCopyAs' options
    If PDFAddIn.HasSaveCopyAsOptions(oDocument, oContext, oOptions) Then

        ' Options for drawings...

        oOptions.Value("All_Color_AS_Black") = 0

        'oOptions.Value("Remove_Line_Weights") = 0
        oOptions.Value("Vector_Resolution") = 720
        oOptions.Value("Sheet_Range") = kPrintAllSheets
        'oOptions.Value("Custom_Begin_Sheet") = 2
        'oOptions.Value("Custom_End_Sheet") = 4
        
    End If

    'Set the destination file name
    Dim FullFileLocation As String
    FullFileLocation = oDocument.FullFileName
        '! ! ! adjust the next line if you want to set it to a fixed location, delete the 2 above
    FileLocation = Left(FullFileLocation, Len(FullFileLocation) - 4) & ".pdf"
    oDataMedium.FileName = FileLocation

    'Publish document.
    Call PDFAddIn.SaveCopyAs(oDocument, oContext, oOptions, oDataMedium)
    
    'Publish succesfull
    'MsgBox ("De PDF is gemaakt")
    
' No errors were found so exit before the error handling code.
    Exit Sub

' Handle any errors
ErrorFound:
    MsgBox "ERROR :-( Check if your drawing file has been saved and that the PDF is not open (even by someone else)", vbOKOnly, "Error"
    Exit Sub
    
End Sub

 hope this helps

 

 

 

 

 

Message 6 of 19
AJ1227
in reply to: ChrisVandeVoorde

Thank you Chris, I think this is what I need.  I'm trying to modify what you have for the save copy as PDF and create one for AutoCAD as well for my other step.

 

Quick question - I see this uses a PDF Save Copy As add-in, is this something I need to download before using?  If so, where can I get it?  Do they have one for AutoCAD as well?

 

Thanks,

Message 7 of 19
FarrenYoung
in reply to: AJ1227

The translator addin is built into Inventor and you should already have it.  You're just calling the functions programmatically that would be called if you did this through the user interface.  If you serach the autocad forum http://forums.autodesk.com/t5/Visual-Basic-Customization/bd-p/33 or the AutoCAD API help file you will find a snippet of code to do the same thing without the need for third party addins.

 

 

--Farren

************************************************************************************
If this post helps, please click the "thumbs up" to give kudos
If this post answers your question, please click "Accept as Solution"
************************************************************************************
Message 8 of 19

In Inventor there are also add-in's for different export files. For instance for .dwg this is the start:

 

' Get the DWG translator Add-In.
'Dim DWGAddIn As TranslatorAddIn
'DWGAddIn = ThisApplication.ApplicationAddIns.ItemById("{C24E3AC4-122E-11D5-8E91-0010B541CD80}")

 

Message 9 of 19
AJ1227
in reply to: ChrisVandeVoorde

Thank you, I found that one for AutoCAD yesterday.  I also have it setup to find my AutoCAD2000.ini file so that it exports as an older AutoCAD 2000 file type.  As of this morning I can pull up a single sheet drawing, run my macro and it:

 

1. Deletes old title block; replaces with new one.

2. Saves file.

3. Publishes PDF to specified folder.

4. Saves As AutoCAD 2000 to same specified folder.

 

It's working perfectly so far.  My next step it to test it on a multi sheet document to make sure it publishes PDF of all sheets and saves AutoCAD files for all sheets.  Then I can add "close file" at the end and loop the program and hopefully it will contiue through all drawings that are open in Inventor.  I may have to create multiple macros because there are several title blocks that I will need to choose from (only difference is a "X" marking which stores the drawing goes to) and right now I'm using a blank for testing.  I've seen some sample macros that can give you a pop up box; I may play around with that later.  Looks like I will be busy here until Christmas break so I will work on it while we are off.

 

Thank you for all your help!  I'm well on my way!

Message 10 of 19
AJ1227
in reply to: AJ1227

Works on multiple sheets; however, I'm having trouble setting up a loop to continue the macro on the next open drawing once it finishes and closes the previous.

 

I think I need something at the beginning that counts # of open drawings and loops until all are closed?  I've been searching other posts for about an hour and I can't find how to loop this routine until all files are closed.

 

Is there a way to tell it to identify if a drawing is open and continue until no drawing remains open?

 

This is the last step I promise.  Smiley LOL

Message 11 of 19
mehatfie
in reply to: AJ1227

Hi AJ1227,

 

Why don't you simplly close the drawing after all of your tasks have been done to it and before you move on to the next drawing.

 

Regards

Mitch

Message 12 of 19
AJ1227
in reply to: mehatfie

The final step in my Sub is to close the drawing but then my Sub ends.  I have the macro set to a shortcut key so I could simply press the key once the previous drawing automatically closes and let the Sub run again on the next open drawing but I was hoping for the Sub to loop automatically until there are no open drawings remaining; but I don't know how to set up that kind of a loop.  Here is what I ended up with.

 

 

Public Sub TEMPLATE_PDF_CAD_PROGRAM()

 

        Dim oDocument As DrawingDocument

        Set oDocument = ThisApplication.ActiveDocument

   

        ' Open the template drawing to copy the title block from.

        Dim oNewDocument As DrawingDocument

        Set oNewDocument = ThisApplication.Documents.Open("TEMPLATE LOCATION HERE\TEMPLATE.DWG", False)

   

        ' Get the new title block definition.

        Dim oNewTitleBlockDef As TitleBlockDefinition

        Set oNewTitleBlockDef = oNewDocument.ActiveSheet.TitleBlock.Definition

   

        ' Set the new title block definition.

        Dim oTitleBlockDef As TitleBlockDefinition

        Set oTitleBlockDef = oNewTitleBlockDef.CopyTo(oDocument)

   

        ' Iterate through the sheets.

        Dim oSheet As Sheet

        For Each oSheet In oDocument.Sheets

        oSheet.Activate

       

        oSheet.TitleBlock.Delete

        Call oSheet.AddTitleBlock(oTitleBlockDef)

        Next

       

        ' Save Document

        oDocument.Save

   

        ' Pause for save

        Dim PauseTime

 

        PauseTime = 5 ' Set duration.

       

        ' Get the PDF translator Add-In.

        Dim PDFAddIn As TranslatorAddIn

        Set PDFAddIn = ThisApplication.ApplicationAddIns.ItemById("{0AC6FD96-2F4D-42CE-8BE0-8AEA580399E4}")

 

        Dim oContext As TranslationContext

        Set oContext = ThisApplication.TransientObjects.CreateTranslationContext

        oContext.Type = kFileBrowseIOMechanism

 

        ' Create a NameValueMap object

        Dim oOptions As NameValueMap

        Set oOptions = ThisApplication.TransientObjects.CreateNameValueMap

 

        ' Create a DataMedium object

        Dim oDataMedium As DataMedium

        Set oDataMedium = ThisApplication.TransientObjects.CreateDataMedium

 

        ' Check whether the translator has 'SaveCopyAs' options

        If PDFAddIn.HasSaveCopyAsOptions(oDocument, oContext, oOptions) Then

 

            ' Options for drawings...

 

            oOptions.Value("All_Color_AS_Black") = 0

 

            'oOptions.Value("Remove_Line_Weights") = 0

            oOptions.Value("Vector_Resolution") = 720

            oOptions.Value("Sheet_Range") = kPrintAllSheets

            'oOptions.Value("Custom_Begin_Sheet") = 2

            'oOptions.Value("Custom_End_Sheet") = 4

       

        End If

 

        'Set the destination file name

        oDataMedium.FileName = "SAVE LOCATION\" & Left(oDocument.DisplayName, Len(oDocument.DisplayName) - 4) & ".pdf"

 

        'Publish document.

        Call PDFAddIn.SaveCopyAs(oDocument, oContext, oOptions, oDataMedium)

   

        ' Pause for PDF publish

        PauseTime = 1000 ' Set duration.

 

        ' Get the DWG translator Add-In.

        Dim DWGAddIn As TranslatorAddIn

        Set DWGAddIn = ThisApplication.ApplicationAddIns.ItemById("{C24E3AC2-122E-11D5-8E91-0010B541CD80}")

 

        'Set the destination file name

        oDataMedium.FileName = "SAVE LOCATION\" & Left(oDocument.DisplayName, Len(oDocument.DisplayName) - 4) & ".dwg"

 

        'Publish document.

        Call DWGAddIn.SaveCopyAs(oDocument, oContext, oOptions, oDataMedium)

   

        'Pause for Save As DWG

        PauseTime = 5000 ' Set Duration

   

        'Save Document

        oDocument.Save

       

        'Pause for Save

        PauseTime = 5000 ' Set Duration

       

        'Close document

        oDocument.Close

      

       End Sub

Message 13 of 19
mehatfie
in reply to: AJ1227

Hi AJ1227,

 

I thought you originally wanted this program to process all drawings related to an assembly. 

 

Do your drawings have the same name as their parts / assembly? Also, where do your drawings exist relative to the models location?

 

Regards

Mitch

Message 14 of 19
AJ1227
in reply to: mehatfie

I do want it to process all drawings related to an assembly but it is a little complicated; let me see if I can explain.

 

We break our save locations into Assembly, Subassembly, and Part folders.  The models and drawings do have the same name and model/drawing are in the same folder.  But these are not the drawings that I am modifying.

 

We take all drawings associated with an assembly and save a copy of them all with _CAD at the end so that when they are saved with the customer title block we do not screw up our drawings.  We save the _CAD in the same folder as the model/our drawing.  (While testing this macro I have been using design assistant to accomplish this, then opening all _CAD drawings and testing the macro).

 

It would be nice to setup this macro so that I open the top level model or drawing (our version) and start the macro to (current macro steps are in red😞

 

1. Saves drawing as "current name_CAD" in same location

2. Replace title block

3. Save

4. Publish PDF (separate specified location)

5. Save As AutoCAD (separate specified location)

6. ReSave file

7. Close file

8. Open next drawing associated with assembly, repeat process until all drawings complete.

 

Can you help walk me through setting this up?

 

Thanks

Message 15 of 19
mehatfie
in reply to: AJ1227

AJ1227,

 

Attached you'll find a quick code that I through together with some other pieces I had. I've added some other things as well but I believe this is what you'd like to do.

 

The code would be run from an Assembly Model and iterates through all of the parts checking if a drawing exists in the same location with the same name. It then opens this drawing and saves a copy with "_CAD" next to it.

 

After this insert your current code and perform the tasks on "DrawDocNew"

 

save and close both documents.

 

 

 

Note that this code is NOT tested and was developed to be placed directly into an iLogic Rule. Changes may be needed to work directly in VBA.

 

This should be a good template to work with for what you're looking to do.

 

Regards

Mitch

 

Let me know if it helps... Kudos if it works!!!

Message 16 of 19
AJ1227
in reply to: mehatfie

Well, after much modifying I've got it working!  Two issues that I'm having:

 

1. The Sub starts with the first assembly within the model; it does not pull the drawing for the open assembly model that I begin with.  I need it to start with the drawing for the model that I have open then work through the referenced documents.

 

2. I'm getting the occasional "Save?" prompt for some of the drawings while the macro is running.  We just switched from Inventor 2010 to 2013 and part of this is because the data needs to be migrated; part of it is because Inventor is too sensative and even though nothing has been changed or updated it wants to prompt you to "Save" as if it was modified.  Is there any way to autorespond "NO" to any save prompts?

 

I'm giving Kudos to all replies in this post for all the help.  I couldn't have done it without you!

Message 17 of 19
mehatfie
in reply to: AJ1227

Hi AJ1227,

 

I would recommend you create a seperate sub in order to not increase the length of your code.

 

Create a sub that contains all of the information in between the "For" loop. Make this sub simply recieve a document, and place it inside the "For" loop instead of all the other code while inputting the DocFile into the code on each loop.

 

This way you can send your assembly file into this same sub prior to the For loop, avoiding copying and pasting the exact same code twice just to run the assembly document

 

Regards

Mitch

 

Let me know if it helps... Kudos if it works!!!

Message 18 of 19
AJ1227
in reply to: mehatfie

Used copy and paste rather than integrating a sub within a sub (wasn't sure where to start, it was faster to copy/paste).  It's doing everything I want it to and more; I have it deleting the revision tables as it replaces the borders and title blocks on each of the sheets within the drawings.  For the life of me I can't figure out how to delete the revision tags with VBA (I can't find a word within VBA to describe the revision tag and delete it).  Is there at least an option to link revision tags to the revision table so that when the table is deleted the tags are removed also?

 

Thanks,

Message 19 of 19
xiaodong_liang
in reply to: AJ1227

Hi AJ1227,

 

It looks the original question in this thread is about priting PDF but your newest question is not relevant. Could you log a new post with the new question ' Is there at least an option to link revision tags to the revision table so that when the table is deleted the tags are removed also' ? It will be more clear for the peers here to jump into.

 

In addition, please remember to attach a snapshot to show what you meant by "revision tags". 

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk Design & Make Report