Question

VB Macro to Count Blocks

Asked by: kgerb

This comment concerns AutoCAD 2002,
I need to create a little code that will enable the user see how many occurances of a block there are in a drawing simply by clicking on one.  Eventually I would like to make it functional enough so that the user could click them off one by one with each counted block turning a different color.  I have programmed extensively in Excel with VBA but have done absolutely nothing in AutoCAD.  I have looked into LISP but have not been able to make heads or tails of any of it.  What I need is just kind of a jump start.  For instance, how do you allow the user to select objects in code?  Is there a control that does this?  In Excel it's a Refedit control.  Do I need to change the selection mode?  Is there a blocks collection for each block in AutoCAD?  Can I do a For Each Block in BlockName.Blocks?  If anybody knows of any good tutorials on programming with VB in AutoCAD I would like to take a look at them.  

As you can see I'm pretty bogged down here.  Any suggestions will be appreciated.

Kyle

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-08-30 at 19:35:01ID21113145
Tags

autocad

,

block

,

vba

Topic

CAD & Architecture Software

Participating Experts
3
Points
500
Comments
8

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Display AutoCAD drawings in VB using OLE
    I need to display AutoCAD drawings in my VB Application. I used the OLE feature to accomplish this. I've set the class property at design time to AutoCAD.Drawing.14 I used the CreateEmbed method to link to a drawing at run-time. The drawing shows up alright, but It also opens...
  2. Using VB code to create AutoCad Drawing
    is there a way that VB can link Autocad commands in the same way you can create and write info to an Excel spreadsheet. (if LINK is the right word?) If not, is there a coded example or link to one, that gathers user input about an object (e.g. length and width ), and then b...
  3. Autocad + VB
    hi guys! I need to draw lines in autocad then extract the start and end point of line. Store these XY coordinates in a file. I have autolisp commands which will load on the draw links button. But the thing is how do i delete the coordinates and points again. Is it easier in a...
  4. Macros in AutoCad...
    I want to write a macro in cad to perform a simple task. I have: Sub Macro1() '<-- this will be in autocad vba editor <Draw a line from point A(5,10) to B(5, 40)> '<-- this is what I need. End Sub This will be my first macro in cad (I am somewhat fa...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: kgerbPosted on 2004-08-30 at 19:36:11ID: 11938281

Also, how "difficult" is my little endevour going to be.  Is this a monsterous project that I'm starting in on, or is it doable for a newbie to AutoCAD VBA.

 

by: oldelphiPosted on 2004-08-31 at 03:23:37ID: 11940316

I hope you can use some of this code to manage what you want, I am at work now but I have some lisp code that can be used if you want !!

Use scale factors with XP option of ZOOM command

Use VBA to access blocks and block reference data

Use VBA to access blocks and block reference data

Published date: 2002-02-21
ID: TS70489

Applies to:
AutoCAD® 2002
AutoCAD® 2000i
AutoCAD® 2000
AutoCAD® Release 14

Issue



This document explains how to access blocks and block reference data using VBA (Visual Basic for Applications).
Solution



Overview

You can use VBA to manage blocks and block references.

A block is a collection of objects that you associate together to form a single object, called a block definition.  When you insert a block in a drawing, you create a block reference. That is, the block reference references the block definition. It is important to know the difference between a block definition and a block reference, because it helps you to understand how you can manipulate these objects in VBA.

We explain how to do this by commenting a short program that illustrates the process. The following sections use commented code examples that show you how to access blocks (block definitions) and block reference data using VBA.

Create the application interface

Assume that you have defined a main form in VBA, with the following controls:
ListBox named lstBlockObject  
ListBox named lstBlockReference  
Command Button named cmdCreateBlock  
Command Button named cmdLister  
Command Button named cmdChangeColor

Create a module and add the following declarations.

'Blocks collection
Public blkColl As AcadBlocks
'Block object
Public BlkObj As AcadBlock
'Block reference object
Public BlkRefrence As AcadBlockReference
'ModelSpace collection
Public mspace As AcadModelSpace
'PaperSpace collection
Public pspace As AcadPaperSpace
Public count As Integer
Public I As Integer
Public elem As Object
Public subelem As Object
'Block insertion point
Public blkInsPnt (0 To 2) As Double
Public circleObj As AcadCircle
'Circle center point
Public center(0 To 2) As Double
'Circle radius
Public radius As Double
Public lineObj as AcadLine
'Line start point
Public startPnt (0 To 2) As Double
'Line end point
Public endPnt (0 To 2) As Double

Add the following declarations to the Initialize event of the form.

'Returns the ModelSpace collection
Set mspace = ThisDrawing.ModelSpace
'Returns the PaperSpace collection
Set pspace = ThisDrawing.PaperSpace
'Returns the blocks collection
Set blkColl = ThisDrawing.Blocks

Create a block

To create a block reference, first you must create a block definition (block). You do this using the Add method. After you create the block you can insert an instance of it into the drawing using the InsertBlock method. In this example, we create a block in model space that is made up of a circle and a line.

Add the following code to the Click event procedure of the cmdCreateBlock button.

blkInsPnt(0) = 0#: blkInsPnt(1) = 0#: blkInsPnt(2) = 0#
'Add the block to the blocks collection
Set BlkObj = blkColl.Add(blkInsPnt, "NewBlock")

Add elements to block

This section provides the code examples that add the elements to the block.

Add the circle

center(0) = 0#: center(1) = 0#: center(2) = 0#
radius = 1
'Add the circle to the block
Set circleObj = BlkObj.AddCircle(center, radius)

Add the line

startPnt(0) = 1#: startPnt(1) = 1#: startPnt(2) = 0#
endPnt(0) = 5#: endPnt(1) = 5#: endPnt(2) = 0#
'Add the line to the block
Set lineObj = BlkObj.AddLine(startPnt, endPnt)

Insert the block in model space

The following code example inserts the block in model space.

Set BlkRefrence = mspace.InsertBlock(blkInsPnt, "NewBlock", 1#, 1#, 1#, 0)
'Zooming the block
ZoomExtents

Access the Block and BlockReference Objects

VBA provides a link to the active drawing in the current AutoCAD session through the ThisDrawing object. By using ThisDrawing, you gain immediate access to the current Document object and all of its methods and properties, and all of the other objects in the hierarchy.

To access a block, you refer to the ThisDrawing object; to access a block reference you refer to the ModelSpace or PaperSpace collection.

Access the block objects

You now need to scan the Block collection, retrieve block names and put them in the ListBox lstBlockObject. There are two ways to scan the Block collection.

You can use an index to scan the Block collection. Once you know how many items the collection contains, you can use a For.Next conditional statement. To do this, add the following code to the Click event procedure of the cmdLister button.

'Returns number of blocks in the blocks collection
count = blkColl.count
'Clear the list box
lstBlockObject.Clear
'Create the block list
For I = 0 To count - 1
 lstBlockObject.AddItem blkColl.Item(I).Name
Next
lstBlockObject.ListIndex = 0

Note: In a collection of N items, the index goes from 0 to N-1.

However, a better way is to use a For Each.In.Next conditional statement. For example, the following statements repeat a block of statements for each object in a collection or each element in an array. VBA automatically sets a variable each time the loop runs. Therefore you could rewrite the previous code using the following example.

'Clear the list box
lstBlockObject.Clear
'Create the block list
For Each elem in ThisDrawing.Blocks
 lstBlockObject.AddItem elem.Name
Next
lstBlockObject.ListIndex = 0

By using this alternative code you
Reduce the number of operations.
Improve code readability.
Reduce the number of user variables.
Reduce the need for error checking (for example, the range control for conditional statements).
Implement a more elegant programming style.

Access the block references

To retrieve similar entities, you perform a similar set of operations; but instead of searching the Blocks collection, you need to search the ModelSpace or PaperSpace collection of an AutoCAD ActiveDocument. To do this, add the following code to the Click event procedure of the cmdLister button.

'Clear the list box
lstBlockReference.Clear
'Create the block list
'Scanning the Model Space collection
For Each elem In mspace
 'Filter only the block references
 If elem.EntityName = "AcDbBlockReference" Then
  lstBlockReference.AddItem elem.Name
 End If
Next
lstBlockReference.ListIndex = 0

At this point, every time you click the Create block button, you only have one block called NEWBLOCK in the ListBox lstBlockObject. However, a new block reference called NEWBLOCK is added to the ListBox lstBlockReference. The new block reference is appended, because you created a new reference to the block (block definition).

Note: Even if the block reference has the same name as existing block references, the handle is different. To AutoCAD, they are different objects.

Modify objects within the block

You can modify an object within a block without exploding the block. To do this, you need to go inside the block object, retrieve the entity to modify and change its properties. The following code example changes the color property of the line to Red.

Add the following code to the Click event procedure of the cmdChangeColor button:

'Scanning the blocks collection
For Each elem In blkColl'Searching the block we want
 If elem.Name = "NewBlock" Then
 'Scanning the block entities
  For Each subelem In elem
    'Filter the line
    If subelem.EntityName = "AcDbLine" Then
     'Assign a new color
     subelem.Color = acRed
    End If
  Next
 End If
Next
'Regenerating the drawing
ThisDrawing.Regen True

This code changes the color property for the line in all block references called NEWBLOCK. What actually happens is that the code changes the color property for the line in the block object (the block definition) and the references are updated because they reference the block object.
See also


Using VBA to modify how AutoCAD DesignCenter inserts blocks

Removing invisible text from a drawing

Drawing is completely empty but file size is very large


Regards
oldelphi

 

by: thenrichPosted on 2004-08-31 at 06:43:58ID: 11941991

Here is the exact code you need:

Sub main()
  Dim blk As AcadEntity
  Dim ent As AcadEntity
  Dim newblk As AcadBlockReference
  Dim pnt As Variant
  Dim cnt As Integer
  Dim blkName As String
 
  On Error GoTo ExitError
 
  AppActivate ("AutoCAD")
  ThisDrawing.Utility.GetEntity blk, pnt, "Select block:"
  If TypeName(blk) = "IAcadBlockReference" Then
       blkName = blk.Name
       For Each ent In ThisDrawing.ModelSpace
          If TypeName(ent) = "IAcadBlockReference" Then
             If ent.Name = blkName Then
                cnt = cnt + 1
             End If
          End If
       Next
    Else
     MsgBox "You've selected a " & TypeName(blk) & Chr(13) & "A block must be selected."
     Exit Sub
  End If
  MsgBox cnt & " occurences of " & blkName
  Exit Sub

ExitError:
  MsgBox Err.Description
End Sub

 

by: thenrichPosted on 2004-08-31 at 06:48:44ID: 11942043

Actually the help in AutoCAD is pretty good. In AutoCAD 2002 go under the help menu and select the 'Developer help' under the help menu vs. the regular help. Lots of good books out there especially from AutoDesk Press. Not much need for LISP any more - did it for years - ICK!!! Stick with the VBA, VB, or .NET when it comes to AutoDesk products.

 

by: kgerbPosted on 2004-09-01 at 10:12:45ID: 11955299

oldelphi,
Thanks for all the code and the generous explainations.  They are very informative.

thenrich,
your code works great!  Thank you!

I'm having a little trouble figuring out how to make it so that I can use the macro in any open drawing without having to find and load the .dvb file each time.  If I can't figure it out I'll ask another question.  Thanks so much to you both.

Kyle

 

by: thenrichPosted on 2004-09-01 at 11:07:02ID: 11956046

' If I can't figure it out I'll ask another question.'

yup - let me know

 

by: oldelphiPosted on 2004-09-01 at 13:09:12ID: 11957430

You can bay a book on the subjekt
Autocad 2005 Bible
the 2004 version includes a nice explenation on how to use
visual basicContains the Book on PDF and All the code in the book
ISBN 0-9645-3992-2
Lock at http://www.wiley.com/WileyCDA/WileyTitle/productCd-0764569899.html

best regards
Oldelphi

Cad instructor since 1988

 

by: daviperPosted on 2004-11-13 at 23:43:21ID: 12577396

There seems no easy way to make commands with Macros.  Thus I have this first bit of Code in my Acad.lsp file which is in our standards directory. This also gets the VBA system up and running when AutoCAD loads up allows AutoCAD to find the acad.DVB file. The DVB file has entries to load every macro we use.  The lisp just calls the appropriate Model.

This code is in my ACAD.lsp

      (setvar "acadlspasdoc" 0)
      
;***Used to Initialize the Visual Basic Sub System***

      (command "-vbarun" "InitVBA" )

I then have a bunch of entries such as this one in my ACADdoc.lsp file for each macro I would like a command for as AutoCAD starts up.

(load "S:/Standards/Programming/Lisp/cut.lsp")

That Cut.lsp file simply has this bit of code which basically calls a small bit of Code in a module which says frmCutsheet.show or something.

(defun c:cut () ;Begin defun

(command "-vbarun" "CUTSHEET")

) ;End defun


If you would like a more detailed explination and the VBA code as well let me know.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...