Upload
vuongthu
View
313
Download
20
Embed Size (px)
Citation preview
<$nopage>ActiveXAutomationinterface:automationprojects.<$nopage>AutoCADColorIndexnumbers.<$nopage>Colorproperty:<$nopage>TrueColorproperty:<$nopage>VB:automationprojects.<$nopage>VBA:automationprojects.<$nopage>VisualBasicforApplications.<$nopage>VisualBasic.<$nopage>automationprojects:migratingtoAutoCAD2004:<$nopage>projects:automation.<$nopage>standardcolornames.
Introduction
ThisintroductiondescribestheconceptofexposingAutoCADobjectsthroughanActiveXAutomationinterfaceandprogrammingthoseobjectsusingtheVisualBasicforApplicationsprogrammingenvironment.
Topicsinthissection
OverviewofAutoCADActiveXTechnologyOverviewofAutoCADVisualBasicforApplications(VBA)InterfaceAutoCADActiveXandVBATogetherHowThisGuideIsOrganizedForMoreInformationSampleCodeMigrateAutomationProjects
Pleasesendusyourcommentaboutthispage
Introduction>
OverviewofAutoCADActiveXTechnology
AutoCAD®ActiveX®enablesyoutomanipulateAutoCADprogrammaticallyfromwithinoroutsideAutoCAD.ItdoesthisbyexposingAutoCADobjectstothe“outsideworld.”Oncetheseobjectsareexposed,theycanbeaccessedbymanydifferentprogramminglanguagesandenvironmentsandbyotherapplicationssuchasMicrosoft®WordVBAorExcelVBA.
TherearetwoadvantagestoimplementinganActiveXinterfaceforAutoCAD:
ProgrammaticaccesstoAutoCADdrawingsisopeneduptomanymoreprogrammingenvironments.BeforeActiveXAutomation,developerswerelimitedtoanAutoLISP®orC++interface.
SharingdatawithotherWindows®applications,suchasMicrosoftExcelandWord,ismadedramaticallyeasier.
AnobjectisthemainbuildingblockofanyActiveXapplication.EachexposedobjectrepresentsaprecisepartofAutoCAD.TherearemanydifferenttypesofobjectsintheAutoCADActiveXinterface.Forexample:
Graphicalobjectssuchaslines,arcs,text,anddimensionsareobjects.
Stylesettingssuchaslinetypesanddimensionstylesareobjects.
Organizationalstructuressuchaslayers,groups,andblocksareobjects.
Thedrawingdisplayssuchasviewandviewportareobjects.
EventhedrawingandtheAutoCADapplicationareconsideredobjects.
Pleasesendusyourcommentaboutthispage
Introduction>
OverviewofAutoCADVisualBasicforApplications(VBA)Interface
MicrosoftVBAisanobject-orientedprogrammingenvironmentdesignedtoproviderichdevelopmentcapabilitiessimilartothoseofVisualBasic6(VB).ThemaindifferencebetweenVBAandVBisthatVBArunsinthesameprocessspaceasAutoCAD,providinganAutoCAD-intelligentandveryfastprogrammingenvironment.
VBAalsoprovidesapplicationintegrationwithotherVBA-enabledapplications.ThismeansthatAutoCAD,usingotherapplicationobjectlibraries,canbeanAutomationcontrollerforotherapplicationssuchasMicrosoftWordorExcel.
ThestandalonedevelopmenteditionsofVisualBasic6,whichmustbepurchasedseparately,complementAutoCADVBAwithadditionalcomponents,suchasanexternaldatabaseengineandreport-writingcapabilities.
TherearefouradvantagestoimplementingVBAforAutoCAD:
VBAanditsenvironmentareeasytolearnanduse.
VBArunsin-processwithAutoCAD.Thistranslatestoveryfastprogramexecution.
Dialogboxconstructionisquickandeffective.Thisallowsdeveloperstoprototypeapplicationsandquicklyreceivefeedbackondesigns.
Projectscanbestandaloneorembeddedindrawings.Thischoiceallowsdevelopersgreatflexibilityinthedistributionoftheirapplications.
Note Microsofthasnotpromisedtoprovide64-bitVBASDKlibraries(.dll).Subsequently,64-bitAutoCADcannolongerrunVBAasanin-proccomponent;VBAcomponentsnowrunas32-bitout-of-processCOMcomponents,andprovidesastopgaparrangementfor64-bitAutoCADVBAusers.ThisarrangementmightrequireafewchangestoexistingVBAcode.This
stopgapprovisionwouldbedeprecatedinfutureversionsofAutoCADanditisadvisablefortheuserstoporttheirexisitingVBAcodetoVB.NET.
Topicsinthissection
HowVBAIsImplementedinAutoCAD
Pleasesendusyourcommentaboutthispage
Introduction>OverviewofAutoCADVisualBasicforApplications(VBA)Interface>
HowVBAIsImplementedinAutoCAD
VBAsendsmessagestoAutoCADbytheAutoCADActiveXAutomationinterface.AutoCADVBApermitstheVBAenvironmenttorunsimultaneouslywithAutoCADandprovidesprogrammaticcontrolofAutoCADthroughtheActiveXAutomationinterface.ThiscouplingofAutoCAD,ActiveXAutomation,andVBAprovidesanextremelypowerfulinterfacenotonlyformanipulatingAutoCADobjects,butforsendingdatatoorretrievingdatafromotherapplications.
TherearethreefundamentalelementsthatdefineActiveXandVBAprogramminginAutoCAD.ThefirstisAutoCADitself,whichhasarichsetofobjectsthatencapsulatesAutoCADentities,data,andcommands.BecauseAutoCADwasdesignedasanopen-architectureapplicationwithmultiplelevelsofinterface,familiaritywithAutoCADprogrammabilityishighlydesirableinordertouseVBAeffectively.Ifyou'veusedAutoLISPtocontrolAutoCADprogrammatically,youalreadyhaveagoodunderstandingoftheAutoCADfacilities.However,youwillfindtheVBAobject-basedapproachtobequitedifferentfromthatofAutoLISP.
ThesecondelementistheAutoCADActiveXAutomationinterface,whichestablishesmessages(communication)withAutoCADobjects.ProgramminginVBArequiresafundamentalunderstandingofActiveXAutomation.AdescriptionoftheAutoCADActiveXAutomationinterfacecanbefoundintheActiveXandVBAReference.EventheexperiencedVBprogrammerwillfindtheAutoCADActiveXAutomationinterfaceinvaluableforunderstandinganddevelopingAutoCADVBAapplications.
ThethirdelementistheVBAprogrammingenvironment,whichhasitsownsetofobjects,keywords,constants,andsoforththatprovidesprogramflow,control,debugging,andexecution.Microsoft'sownextensiveHelpforVBAisincludedwiththeAutoCADVBAHelpandisaccessiblefromtheVBAIDEbyanyofthe
followingmethods:
PressingF1onthekeyboard
ChoosingHelpfromtheVBAIDEmenubar
ClickingtheQuestionMarkiconontheVBAIDEtoolbar
Topicsinthissection
UsetheMicrosoft.NETFrameworkDependenciesandRestrictions
Pleasesendusyourcommentaboutthispage
Introduction>OverviewofAutoCADVisualBasicforApplications(VBA)Interface>HowVBAIsImplementedinAutoCAD>
UsetheMicrosoft.NETFramework
TofullyaccessAutoCADautomationobjectsfromMicrosoftVisualStudio®.NET,createreferencestothefollowingfiles:
TheAutoCAD2009typelibrary,acax17enu.tlb,locatedatc:\programfiles\commonfiles\autodeskshared.
TheAutoCAD/ObjectDBXCommon17.0typelibrary,axdb17enu.tlb,locatedatc:\programfiles\commonfiles\autodeskshared.
Thesereferenceswillmakeavailablethefollowingprimaryinteropassemblies:Autodesk.AutoCAD.Interop.dll(forAutoCAD-specifictypes),andAutodesk.AutoCAD.Interop.Common.dll(fortypessharedbyObjectDBXTMhostapplications).Theinteropassembliesarelocatedintheglobalassemblycache;theymapautomationobjectsto.NETcounterparts.
Afteryoureferencethetypelibraries,youcandeclareAutoCAD-basedvariablesinMicrosoftVisualStudio.NET,asinthefollowingexamples:
DimobjAcadAsAutodesk.AutoCAD.Interop.AcadApplication
DimobjLineAsAutodesk.AutoCAD.Interop.Common.AcadLine
Youcanloada.NETapplicationusingtheNETLOADcommandinAutoCAD.
Additionalinformationaboutusinga.NETapplicationwithAutoCADisavailablefromtheDeveloperCentersectionoftheAutodeskwebsite.
Pleasesendusyourcommentaboutthispage
Introduction>OverviewofAutoCADVisualBasicforApplications(VBA)Interface>HowVBAIsImplementedinAutoCAD>
DependenciesandRestrictions
Ifyouinstall,reinstall,oruninstallMicrosoftOfficeorotherVBAapplicationsafterinstallingAutoCAD,reinstallAutoCADandrebootyoursystem.
Pleasesendusyourcommentaboutthispage
Introduction>
AutoCADActiveXandVBATogether
TheAutoCADActiveX/VBAinterfacerepresentsseveraladvantagesoverotherAutoCADAPIenvironments:
Speed.Runningin-processwithVBA,ActiveXapplicationsarefasterthanAutoLISPapplications.
EaseofUse.TheprogramminglanguageanddevelopmentenvironmentareeasytouseandcomeinstalledwithAutoCAD.
WindowsInteroperability.ActiveXandVBAaredesignedtobeusedwithotherWindowsapplicationsandprovideanexcellentpathforcommunicationofinformationacrossapplications.
RapidPrototyping.TherapidinterfacedevelopmentofVBAprovidestheperfectenvironmentforprototypingapplications,evenifthoseapplicationswill-eventuallybedevelopedinanotherlanguage.
ProgrammerBase.AutoCADActiveXandVBAtechnologyprovideVisualBasic6programmerswiththeabilitytocustomizeAutoCADanddevelopapplicationsforit.
Pleasesendusyourcommentaboutthispage
Introduction>
HowThisGuideIsOrganized
ThisguideprovidesinformationregardingthedevelopmentofActiveXandVBAapplicationsforusewithAutoCAD.InformationspecifictodevelopingapplicationsusingVBAcanbefoundin“GettingStartedwithVBA”and“DevelopApplicationswithVBA.”ProgrammersusingActiveXfromadevelopmentenvironmentotherthanVBAcanskipthesetwochapters.However,beawarethatalloftheexamplecodeinthisguideispresentedinVBA.
Pleasesendusyourcommentaboutthispage
Introduction>
ForMoreInformation
ThisguideassumesthatyouhaveaworkingknowledgeoftheVisualBasic6programminglanguage,anddoesnotattempttoduplicateorreplacetheabundanceofdocumentationavailableonVisualBasic6.IfyouneedmoreinformationontheVisualBasic6languageordevelopmentenvironmentusage,seetheVisualBasicforApplicationsHelpfiledevelopedbyMicrosoft,availablefromtheHelpmenuintheinteractivedevelopmentenvironment(IDE).
Pleasesendusyourcommentaboutthispage
Introduction>
SampleCode
ThismanualandtheActiveXandVBAReferencetogethercontainover800exampleVBAsubroutinesthatdemonstratetheusageofActiveXmethods,properties,andevents.
TherearealsomanysampleapplicationsprovidedintheAutoCADSampledirectory.Thesesampleapplicationsshowawiderangeoffuctionality,fromextractingAutoCADdrawingdataintoMicrosoftExcelspreadsheetstodrawingandperformingstressanalysisonanelectricaltransmissiontower.
ThesesamplesalsoshowhowtocombinetheversatilityoftheVisualBasicforApplicationsprogrammingenvironmentwiththepoweroftheAutoCADActiveXinterfacetocreatecustomizedapplications.
Additionally,examplecodeintheActiveXandVBADeveloper'sGuideandActiveXandVBAReferencecanbecopiedfromtheHelpfiles,pasteddirectlyintotheAutoCADVBAenvironment,andthenexecutedwithonerequirement:thecurrentactivedrawinginAutoCADmustbeablankdrawingopentomodelspace.
ToruntheexamplesfromtheHelpfiles
1. CopytheexamplefromtheHelpfileintoanemptyVBAcodemodule.
2. VerifythatAutoCADhasablankdrawingopentomodelspace.
3. OpentheMacrosdialogboxbyenteringthecommandVBARUN.
4. ChoosethemacroandpressRun.MoreinformationonrunningmacrosandtheMacrosdialogboxisavailableinthetopic“RunaMacro.”
Pleasesendusyourcommentaboutthispage
Introduction>
MigrateAutomationProjects
YoucanuseAutoCADfeaturesbyusingtheobjectsandmethodsaddedtotheActiveXAutomationinterface.ThissectionincludesthechangesthatapplytoautomationprojectscreatedwithVisualBasicforApplications(VBA),VisualBasic6(VB),andotherautomation-compatibleenvironments.
ForadditionalinformationaboutusingfeaturesinAutoCAD,see“UseAutoCADFeatures”.
Topicsinthissection
NewObjectsChangedItemsHowtoMigrateProjects
Pleasesendusyourcommentaboutthispage
Introduction>MigrateAutomationProjects>
NewObjects
ThefollowingobjectsarenewinAutoCAD2009.Formoreinformationabouttheseobjects,seetheActiveXandVBAReferenceandtheObjectBrowserintheVBAIDE.
SortentsTable.Containsandmanipulatesdraworderinformation.
Table.Addsandmodifiestablesinadrawing.
TableStyle.Addsandmodifiesformattingfortables,suchasgridvisibility,lineweight,andcolor.
Inaddition,AutoCAD2009containsobjectsfortheautomationoftheSheetSetManager.Forinformationabouttheseobjects,seetheSheetSetObjectsReference.
Pleasesendusyourcommentaboutthispage
Introduction>MigrateAutomationProjects>
ChangedItems
Thissectiondescribesexistingitemsthathavechanged.
ChangedItems
AutoCAD2004item
AutoCAD2009item
Descriptionofchange
BeginCloseevent BeginDocCloseevent
YoucanusetheBeginDocCloseeventtopreventadrawingfrombeingclosed
Layerobject Layerobject AdditionoftheDescriptionpropertyandUsedproperty
Layerscollection Layerscollection AdditionoftheGenerateUsageDatamethod
ModelSpacecollectionPaperSpacecollectionBlockobject
ModelSpacecollectionPaperSpacecollectionBlockobject
AdditionoftheAddTablemethodtoallthecollectionsandtotheobject;additionofthePathpropertytotheBlockobject
MTextobject,Textobject
MTextobject,Textobject
AdditionoftheBackgroundFillpropertytotheMTextobject;additionofFieldCodemethodtotheMTextobjectandTextobject
Plotobject Plotobject TheBatchPlotProgresspropertyandStartBatchModepropertyareobsolete.ItisrecommendedthatMicrosoft.NETapplicationsbeusedforbatchplotting.TheDisplayPlotPreviewmethodnolongersupportspartialpreview
PreferencesFilesobject
PreferencesFilesobject
AdditionofthePlotLogFilePathproperty,PageSetupOverridesTemplateFileproperty,andQNewTemplateFileproperty
PreferencesOutputobject
PreferencesOutputobject
AdditionoftheAutomaticPlotLogproperty,DefaultPlotToFilePathproperty,andContinuousPlotLogproperty
Viewportobject Viewportobject AdditionoftheModelViewproperty,SheetViewproperty,LabelBlockIdproperty,HasSheetViewproperty,andSyncModelViewmethod
Viewobject Viewobject AdditionoftheCategoryNameproperty,LayoutIdproperty,LayerStateproperty,andHasVpAssociationproperty
Pleasesendusyourcommentaboutthispage
Introduction>MigrateAutomationProjects>
HowtoMigrateProjects
Ingeneral,anAutoCADautomationprojectcreatedintheVBAIDEorcreatedwithVisualBasic6shouldworkwithAutoCAD2009.
AutoCAD2009automationprojectsusethesametypelibrary(acax17enu.tlb)asAutoCADautomationprojects.ThetypelibraryislocatedinC:\ProgramFiles\CommonFiles\AutodeskShared.
AutoCAD2009automationprojectsalsousethesameversion-dependentProgIDfortheCreateObject,GetObject,andGetInterfaceObjectmethods.Forexample,ifyouareusingtheCreateObjectfunctioninanAutoCADautomationproject,youuseCreateObject("AutoCAD.Application.17").Ifanautomationprojectusesversion-independentProgIDs,changetheprojecttouseversion-dependentProgIDs.
Pleasesendusyourcommentaboutthispage
<$nopage>properties.<$nopage>objects:
GettingStartedwithVBA
ThischapterintroducesyoutoAutoCADVisualBasicforApplications(VBA)projectsandtheVBAinteractivedevelopmentenvironment(IDE).AlthoughmostVBAenvironmentsaresimilarinbehavior,theAutoCADVBAIDEhassomeuniquefeatures.TherearealsoseveralAutoCADcommandsthatcanbeusedtoloadprojects,runprojects,oropentheVBAIDE.ThischapterdefinestheuseofVBAprojects,VBAcommands,andtheVBAIDEingeneral.
Topicsinthissection
UnderstandEmbeddedandGlobalVBAProjectsOrganizeYourProjectswiththeVBAManagerHandleYourMacrosEditYourProjectswiththeVBAIDEPerformanIntroductoryExerciseMoreInformationAutoCADVBAProjectTermsAutoCADVBACommands
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>
UnderstandEmbeddedandGlobalVBAProjects
AnAutoCAD®VBAprojectisacollectionofcodemodules,classmodules,andformsthatworktogethertoperformagivenfunction.ProjectscanbestoredwithinanAutoCADdrawing,orasaseparatefile.
EmbeddedprojectsarestoredwithinanAutoCADdrawing.TheseprojectsareautomaticallyloadedwheneverthedrawinginwhichtheyarecontainedisopenedinAutoCAD,makingthedistributionofprojectsveryconvenient.EmbeddedprojectsarelimitedandnotabletoopenorcloseAutoCADdrawingsbecausetheyfunctiononlywithinthedocumentwheretheyreside.Usersofembeddedprojectsarenolongerrequiredtofindandloadprojectfilesbeforetheyrunaprogram.Atimelogthatistriggeredwhenthedrawingisopenedisanexampleofaprojectembeddedinadrawing.Withthismacrouserscanloginandrecordthelengthoftimetheyworkedonthedrawing.Theuserdoesnothavetoremembertoloadtheprojectbeforeopeningthedrawing;itsimplyisdoneautomatically.
Globalprojectsarestoredinseparatefilesandaremoreversatilebecausetheycanworkin,open,andcloseanyAutoCADdrawing,butarenotautomaticallyloadedwhenadrawingisopened.Usersmustknowwhichprojectfilecontainsthemacrotheyneedandthenloadthatprojectfilebeforetheycanrunthemacro.However,globalprojectsareeasiertosharewithotherusers,andtheymakeexcellentlibrariesforcommonmacros.Anexampleofaprojectyoumaystoreinaprojectfileisamacrothatcollectsabillofmaterialsfrommanydrawings.Thismacrocanberunbyanadministratorattheendofaworkcycleandcancollectinformationfrommanydrawings.
Atanygiventime,userscanhavebothembeddedandglobalprojectsloadedintotheirAutoCADsession.
AutoCADVBAprojectsarenotbinarycompatiblewithstandaloneVisualBasic6projects.However,theforms,modules,andclassescanbeexchangedbetweenprojectsusingtheIMPORTandEXPORTVBAcommandsintheVBAIDE.For
moreinformationabouttheVBAIDE,seeEditYourProjectswiththeVBAIDE.
TheuseofVisualStudio.NETtodriveandcustomizeAutoCADthroughCOMAutomationissupported.
Pleasesendusyourcommentaboutthispage
<$nopage>properties.<$nopage>objects:
GettingStartedwithVBA>
OrganizeYourProjectswiththeVBAManager
YoucanviewalltheVBAprojectsloadedinthecurrentAutoCADsessionbyusingtheVBAManager.ItisanAutoCADtoolthatallowsyoutoload,unload,save,create,embed,andextractVBAprojects.
ToopentheVBAManager
YoucanopentheVBAManagerfromtheToolsmenuor,inAutoCAD,byinvokingtheVBAMANcommand.
Topicsinthissection
LoadanExistingProjectUnloadaProjectEmbedaProjectintoaDrawingExtractaProjectfromaDrawingCreateaNewProjectSaveYourProject
Pleasesendusyourcommentaboutthispage
<$nopage>properties.<$nopage>objects:
GettingStartedwithVBA>OrganizeYourProjectswiththeVBAManager>
LoadanExistingProject
WhenyouloadaprojectintoAutoCAD,allthepublicsubroutines,alsocalledmacros,becomeavailableforuse.Projectsembeddedinadrawingareloadedwheneverthedrawingisopened.ProjectsstoredinDVBfilesmustbeloadedexplicitly.
Anytimeaprojectisloaded,anyotherprojectsthatarereferencedbythefirstprojectwillbeloadedautomatically.Additionally,AutoCADwillautomaticallyloadatstartupanyprojectfilewiththenameacad.dvb.
ToloadanexistingVBAprojectfile
1. IntheVBAManager,usetheLoadoptiontobringuptheOpenVBAProjectdialogbox.
2. IntheOpenVBAProjectdialogbox,selecttheprojectfiletoopen.TheVBAProjectdialogboxwillallowyoutoopenonlyvalidDVBfiles.Ifyouattempttoopenadifferenttypeoffile,youwillreceiveanerrormessage.
3. SelectOpen.
Youcanalsoloadaprojectfileusingoneofthefollowingmethods:
EntertheVBALOADcommand,whichopenstheOpenVBAProjectdialogbox.
DragaDVBfilefromWindowsExploreranddropitintoanopendrawingintheAutoCADwindow.
Topicsinthissection
VirusAlert
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>OrganizeYourProjectswiththeVBAManager>LoadanExistingProject>
VirusAlert
Eachtimeyouloadaprojectyouaregiventheoptionofenablingordisablingthecodewithinthatprojectasaprotectionagainstviruses.Ifyouenablethecode,virusesinthecodecanbeginexecuting.Ifyoudisablethecode,theprojectwillstillbeloaded,butallcodewithinthatprojectispreventedfromrunning.ThevirusalertisnotdisplayedwhenyouloadaprojectbydraggingaDVBfilefromWindowsExploreranddroppingitintoanopendrawingintheAutoCADwindow.
MoreinformationaboutthevirusalertisavailableinSettheProjectOptions.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>OrganizeYourProjectswiththeVBAManager>
UnloadaProject
Unloadingaprojectfreesupmemoryandkeepsthelistofloadedprojectsatalengththatiseasytomanage.
Youcannotunloadembeddedprojectsorprojectsthatarereferencedbyotherloadedprojects.
TounloadaVBAproject
YoucanunloadaVBAprojectbyselectingtheprojectyouwanttounloadandchoosingUnload,orbyusingtheVBAUNLOADcommand,whichpromptsyoufortheprojecttobeunloaded.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>OrganizeYourProjectswiththeVBAManager>
EmbedaProjectintoaDrawing
Whenyouembedaprojectyouplaceacopyoftheprojectinthedrawingdatabase.Theprojectisthenloadedorunloadedwheneverthedrawingcontainingitisopenedorclosed.
Adrawingcancontainonlyoneembeddedprojectatatime.Ifadrawingalreadycontainsanembeddedprojectyoumustextractitbeforeadifferentprojectcanbeembeddedintothedrawing.
ToembedaprojectinanAutoCADdrawing
1. OpentheVBAManagerandselecttheprojectyouwanttoembed.
2. ChooseEmbed.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>OrganizeYourProjectswiththeVBAManager>
ExtractaProjectfromaDrawing
Whenyouextractaprojectyouremovetheprojectfromthedrawingdatabaseandaregiventheopportunitytosavetheprojectinanexternalprojectfile.Ifyoudonotsavethefileinanexternalprojectfile,theprojectdatawillbedeleted.
ToextractaprojectfromanAutoCADdrawing
1. OpentheVBAManagerandselectthedrawingfromwhichtheprojectistobeextracted.
2. ChooseExtract.
3. Ifyouwanttosavetheprojectinformationinanexternalprojectfile,chooseYestotheprompt“DoyouwanttoexporttheVBAprojectbeforeremovingit?”TheSaveAsdialogboxwillbedisplayed,allowingyoutosavethefile.Ifyoudonotwanttosavetheprojectinformationinanexternalfile,chooseNototheprompt“DoyouwanttoexporttheVBAprojectbeforeremovingit?”Theprojectinformationwillberemovedfromthedrawingandwillnotbesaved.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>OrganizeYourProjectswiththeVBAManager>
CreateaNewProject
Newprojectsarecreatedasunsavedglobalprojects.Onceaprojecthasbeencreated,youcanthenembedtheprojectinadrawing,orsavetheprojectouttoaprojectfile.
TocreateanewVBAproject
1. OpentheVBAManager.
2. ChooseNew.AnewprojectwillbecreatedwiththedefaultnameofACADProject.TochangetheprojectnameyoumustgointotheVBAIDE.FormoreinformationonnamingyourprojectintheVBAIDE,seeNameYourProject.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>OrganizeYourProjectswiththeVBAManager>
SaveYourProject
Embeddedprojectsaresavedwheneverthedrawingissaved.GlobalprojectsmustbesavedusingtheVBAManagerortheVBAIDE.
TosaveyourprojectusingtheVBAManager
1. OpentheVBAManagerandselecttheprojecttobesaved.
2. ChooseSaveAs.TheSaveAsdialogboxwillopen.
3. Selectthefilenamefortheprojecttobesavedin.
4. ChooseSave.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>
HandleYourMacros
Amacroisapublic(executable)subroutine.Eachprojectusuallycontainsatleastonemacro.
Topicsinthissection
UsetheMacrosDialogBoxRunaMacroEditaMacroStepintoaMacroSettheProjectOptions
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>HandleYourMacros>
UsetheMacrosDialogBox
TheMacrosdialogboxallowsyoutorun,edit,delete,andcreatemacrosaswellassettheVBAprojectoptions.OpentheMacrosdialogboxfromtheAutoCADToolsmenubychoosingMacro Macros,orissueVBARUNattheAutoCADCommandprompt.
Thenamesofallmacrosinthevalidrangearedisplayedinthisdialogbox.YoucanchangethevalidrangebyusingtheMacrosIndrop-downlist.Thislistspecifiestheprojectsordrawingswhosemacrosaredisplayed.Youcanchoosetodisplaythemacrosin
Alldrawingsandprojects
Alldrawings
Allprojects
AnyindividualdrawingcurrentlyopeninAutoCAD
AnyindividualprojectcurrentlyloadedinAutoCAD
Bylimitingthevalidrangeyoucancontrolhowmanymacronamesappearinthelist.Thiswillhelpyouinthecaseswhenmanymacrosareavailableintheloadeddrawingsandprojects.
Tocreateanewmacro
1. OpentheMacrosdialogboxandenterthenameforthenewmacro.
2. IntheMacrosIndrop-downlist,selectaprojecttocreatethenewmacroin.
3. ChooseCreate.
Ifamacrowiththespecifiednamealreadyexists,youwillbeaskedifyouwant
toreplacetheexistingmacro.
IfyouselectYesattheprompt,thecodeintheexistingmacrowillbedeletedandanew,emptymacrowillbecreatedwiththespecifiedname.
IfyouselectNoattheprompt,youwillbereturnedtotheMacrosdialogboxtoenteranewnameforthemacro.
IfyouselectCancelattheprompt,theMacrosdialogboxwillbedismissedandnonewmacrowillbecreated.
Todeleteamacro
1. OpentheMacrosdialogboxandselectthemacrotodelete.
2. ChooseDelete.Youwillbepromptedtoconfirmthedelete.
3. Attheprompt,chooseYestodeletethemacro,orNotocancelthedelete.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>HandleYourMacros>
RunaMacro
RunningamacroexecutesthemacrocodewithinthecontextofthecurrentAutoCADsession.Thecurrentactivedrawingisconsideredtobetheopendrawingthathasthefocuswhenmacroexecutionbegins.AllVBAreferencestotheThisDrawingobjectwillrefertothecurrentactivedrawingformacrosinglobalprojects.Formacrosinembeddedprojects,theThisDrawingobjectalwaysreferstothedrawinginwhichthemacroisembedded.
TorunamacrofromtheMacrosdialogbox
1. OpentheMacrosdialogboxandselectthemacrotorun.
2. ChooseRun.
TorunamacrofromtheVBAIDE
FromtheRunmenu,usetheRunMacromenuoption.Ifnomacroorformiscurrent,adialogboxisdisplayed,allowingyoutochoosethemacrotorun.Ifagivenmacroiscurrent(thecursorisinaprocedure),thatmacrowillbeexecuted.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>HandleYourMacros>
EditaMacro
EditingamacrowillopentheVBAIDEwiththechosenmacroopenintheCodewindow.FormoreinformationoneditingmacrosintheVBAIDEseeEditYourProjectswiththeVBAIDE.
Toeditamacro
1. OpentheMacrosdialogboxandselectthemacrotoedit.
2. ChooseEdit.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>HandleYourMacros>
StepintoaMacro
Steppingintoamacrobeginsexecutionofthemacroandthenhaltstheexecutiononthefirstlineofcode.TheVBAIDEisopenedwiththechosenmacroopenintheCodewindowatthelineofexecution.
Tostepintoamacro
1. IntheMacrosdialogbox,selectthemacrotostepinto.
2. ChooseStepInto.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>HandleYourMacros>
SettheProjectOptions
TherearethreeoptionsthatcanbesetforAutoCADVBAprojects:
EnableAutoEmbedding
AllowBreakonErrors
EnableMacroVirusProtection
EnableAutoEmbedding
TheautoembedfeatureautomaticallycreatesanembeddedVBAprojectforalldrawingswhenthedrawingisopened.
AllowBreakonErrors
ThisoptionallowsVBAtoenterBreakmodewhenanerrorisencountered.Breakmodeisatemporarysuspensionofprogramexecutionintheinteractivedevelopmentenvironment.InBreakmode,youcanexamine,debug,reset,stepthrough,orcontinueprogramexecution.
Whenthisoptionisenabled,unhandlederrorsfoundduringtheexecutionofaVBAmacrowillsuspendtheexecutionofthemacroanddisplaytheVBAIDEatthepointoftheerrorinthemacro.
Whenthisoptionisdisabled,untrappederrorsfoundduringtheexecutionofaVBAmacrowilldisplayamessageboxalertingyoutotheerror,andthenendexecutionofthemacro.
EnableMacroVirusProtection
Thevirusprotectionmechanismdisplaysabuilt-inwarningmessagewheneveryouopenadrawingthatmaycontainmacroviruses.
TosettheAutoCADVBAprojectoptions
1. FromtheToolsmenuchooseMacro MacrostoopentheVBAMacrosdialogbox.
2. FromtheVBAMacrosdialogbox,chooseOptionstoopentheOptionsdialogbox.
3. FromtheOptionsdialogbox,selecttheoptionsyouwanttoenable.
4. ChooseOK.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>
EditYourProjectswiththeVBAIDE
OnceaprojecthasbeenloadedintoAutoCAD,youcaneditthecode,forms,andreferencesforthatprojectusingtheVBAinteractivedevelopmentenvironment.YoucanalsodebugandrunprojectsfromtheVBAIDE.Onceopen,theVBAIDEprovidesaccesstoallloadedprojects.
ToopentheVBAIDEondemand
YoucanopentheVBAIDEfromthecommandlineorfromthemenubar.
Fromthecommandline,enterVBAIDE,orfromtheToolsmenu,chooseMacro VisualBasicEditor.
Topicsinthissection
ViewProjectInformationDefinetheComponentsinaProjectImportExistingComponentsEditComponentsNameYourProjectSaveYourProjectReferenceOtherVBAProjectsSettheVBAIDEOptions
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>
ViewProjectInformation
TheVBAIDEcontainsawindowcalledtheProjectwindow,whichdisplaysalistofallloadedVBAprojects.Italsodisplaysthecode,class,andformmodulesincludedintheproject,thedocumentassociatedwiththeproject,allotherVBAprojectsreferencedfromtheproject,andthephysicallocation(path)oftheproject.
TheProjectwindowhasitsowntoolbar,whichcanbeusedtoopenvariousprojectcomponentsforediting.UsetheViewCodebuttontoopenthecodeforaselectedmodule.UsetheViewObjectbuttontodisplayselectedobjectssuchasforms.
TheProjectwindowisvisiblebydefault.Ifitisnotvisible,selectProjectwindowfromtheViewmenu,orpressCTRL+R.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>
DefinetheComponentsinaProject
Eachprojectcancontainmanydifferentcomponents.Thedifferentcomponentsaprojectcancontainareobjects,forms,standardmodules,classmodules,andreferences.
Topicsinthissection
ObjectsFormsStandardModulesClassModulesReferencesAddNewComponents
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>DefinetheComponentsinaProject>
Objects
Theobjectcomponentrepresentsthetypeofobject,ordocument,thattheVBAcodewillaccess.ForAutoCADVBAprojects,thisobjectrepresentsthecurrentAutoCADdrawing.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>DefinetheComponentsinaProject>
Forms
Theformcomponentcontainsthecustomdialogboxesyouconstructedforusewithyourproject.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>DefinetheComponentsinaProject>
StandardModules
Thecodemodulecomponentcontainsyourgenericproceduresandfunctions.Astandardmoduleisalsoreferredtoasacodemodule,orassimplyamodule.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>DefinetheComponentsinaProject>
ClassModules
Theclassmodulecomponentcontainsallyourownobjects,whicharedefinedasclasses.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>DefinetheComponentsinaProject>
References
Thereferencecomponentcontainsallyourreferencestootherprojectsorlibraries.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>DefinetheComponentsinaProject>
AddNewComponents
Addingnewcomponentscreatesablankcomponentinyourproject.Youcanaddnewmodules,forms,andclassmodulestoyourproject.Youareresponsibleforupdatingallthepropertiesofthecomponent(suchasthenameofthecomponent)andforfillingintheappropriatecode.Whennamingnewcomponents,rememberthatotherdevelopersmaywanttouseyourcomponentsinfutureapplications.Followtheappropriatenamingconventionsforyourdevelopmentteam.
Toaddanewcomponenttoyourproject
1. IntheProjectwindowoftheVBAIDE,selecttheprojecttowhichyouwillbeaddingthecomponent.
2. FromtheInsertmenu,selectUserForm,Module,orClassModuletoaddthenewcomponenttoyourproject.ThenewcomponentwillbeaddedtoyourprojectandwillappearintheProjectwindow.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>
ImportExistingComponents
Importingallowsyoutoaddanexistingcomponenttoyourproject.Youcanimportforms,modules,orclassmodules.FormsareimportedasFRMfiles,modulesareimportedasBASfiles,andclassmodulesareimportedasCLSfiles.
Whenyouimportacomponentfile,acopyofthefileyouareimportingisaddedtotheproject.Theoriginalfileisleftintact.Changesyoumaketotheimportedcomponentdonotaltertheoriginalcomponentfile.
Ifyouimportacomponentwiththesamenameasanexistingone,thefileisaddedtoyourprojectwithanumberappendedtoit.
TheimportedcomponentwillbeaddedtoyourprojectandwillappearintheProjectwindow.Toeditthepropertiesofthecomponent,selectthatcomponentintheProjectwindow.ThepropertiesfortheselectedcomponentwillbelistedandcanbeeditedinthePropertieswindow.
Toimportanexistingcomponenttoyourproject
1. IntheProjectwindowoftheVBAIDE,selecttheprojecttowhichyouwillbeaddingthecomponent.
2. FromtheFilemenu,selectImportFiletoopentheImportFiledialogbox.
3. FromtheImportFiledialogbox,selectthefiletoimportandpressOpen.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>
EditComponents
Youcaneditstandardmodules,classmodules,andformsintheVBAIDE.StandardandclassmodulesareeditedinaCodewindow.FormsareeditedintheUserFormwindowusingaspecialtoolbox.
YoucanopenasmanyCodewindowsasyouhavemodules,soyoucaneasilyviewthecodeindifferentformsormodules,andcopyandpastebetweenthem.
Toeditacomponentinyourproject
1. IntheProjectwindowoftheVBAIDE,selectthecomponentyouwanttoedit.
2. SelecttheViewCodebuttonintheProjectwindowtoopenaCodewindow.
3. SelecttheViewObjectbuttonintheProjectwindowtoopenaUserFormwindowandassociatedtoolbox.
Toaccessthecodeassociatedwithaform
Toaccessthecodeassociatedwithacontrol,double-clickonanycontrolintheFormwindow.ThecodeassociatedwiththatcontrolwillopeninaCodewindow.
Topicsinthissection
UsetheCodeWindowUsetheUserFormWindow
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>EditComponents>
UsetheCodeWindow
TheCodewindowcontainstwodrop-downlists,asplitbar,amarginindicatorbar,andtheFullViewandProcedureViewicons.
Thetwodrop-downlistsatthetopoftheCodewindowdisplaythecurrentobjectandprocedure.Youcanmoveaboutyourprojectbychangingtheobjectorprocedureinthesedrop-downlists.
ThesplitbarontherightsideoftheCodewindowallowsyoutosplitthewindowhorizontally.Simplydragthisbardowntocreateanotherwindowpane.Thisfeatureallowsyoutoviewtwopartsofcodesimultaneouslyinthesamemodule.Toclosethepane,dragthesplitbarbacktoitsoriginallocation.
ThemarginindicatorbarislocateddowntheleftsideoftheCodewindow.Itisusedtodisplaymarginindicatorsthatareusedduringcodeeditinganddebugging.
TheFullViewandProcedureViewiconsarelocatedatthebottom-leftcorneroftheCodewindowandtogglethedisplayfromonlyoneprocedureatatimetoviewingtheentiremoduleatonetime.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>EditComponents>
UsetheUserFormWindow
TheUserFormwindowallowsyoutocreatecustomdialogboxesinyourproject.
Toaddacontrolsimplydragthedesiredcontrolfromthetoolboxandplaceitontheform.YoucansetyourcontrolstoalignwiththegridofyourformfromtheGeneraltaboftheOptionsdialogbox.YoucanviewtheformgridanddeterminethesizeofthegridlinesfromtheGeneraltaboftheOptionsdialogbox.(SeeSettheVBAIDEOptionsformoreinformationontheOptionsdialogbox.)
EachformyoudesignwillautomaticallyhaveaMaximize,Minimize,andClosebutton.Thesebuttonshavealreadybeenimplementedforyou.
Toaddcodetothecontrol,simplydouble-clickonthecontrolonceithasbeenplacedontheform.ThiswillopenaCodewindowforthecontrol.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>
NameYourProject
Theprojectnameandthenameofthe.dvbfilewheretheprojectisstoredaretwodifferentvalues.Youestablishthenameofthe.dvbfiletheprojectisstoredinwhenyousavetheproject.TheprojectnameissetinthePropertieswindowoftheVBAIDE.
Ifyoudonotsettheprojectnameandfilename,AutoCADautomaticallyassignsthefollowingdefaultnames:
Projectname:ACADProject
Filename:Project.dvb
Tochangethenameofaproject
1. IntheProjectwindowoftheVBAIDE,selecttheprojecttochange.
2. InthePropertieswindow,edittheNamepropertyfortheproject.
Tochangethefilenameforaproject
1. IntheVBAIDE,selecttheSaveoptionfromtheFilemenu.
2. IntheSaveAsdialogbox,enterthenewnameandlocationfortheprojectfile.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>
SaveYourProject
ThereisnoexplicitSAVEcommandinAutoCADforVBAprojects.Instead,theSAVEcommandresidesintheFilemenuoftheVBAIDEandintheVBAManager.AnychangestoaVBAprojectwillaccessastandardSaveVBAProjectdialogboxwhenoneoftheseeventsoccurs:
YouselecttheSAVEcommandfromtheVBAIDE.
YouchoosetheSaveAsoptionintheVBAManager.
YourAutoCADsessionisabouttoendorquitandtheVBAprojectisnotsaved.
Note Beforeyousaveaproject,itisassignedthedefaultfilenameproject.dvb.Itisimportantthatyouassignanewnametoyourprojectfilewhenyousavetheproject.Ifyousaveaprojectwiththedefaultfilenameproject.dvb,youwillnolongerbeabletocreatenewemptyprojects.Eachtimeyoucreateanewproject,youwillactuallybeloadingthesavedprojectcalledproject.dvb.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>
ReferenceOtherVBAProjects
ReferencingoneVBAprojectfromanotherallowsdeveloperstosharecodemoreeasily.Developerscancreatelibrariesofcommonlyusedmacrosandthenreferencethelibrarywhenneeded.Thiskeepsthesharedcodecentrallylocatedandsupported,whileallowingalargenumberofdeveloperstoutilizethecode.
Onceanotherprojecthasbeensuccessfullyreferenced,youwillnoticeanewfolderintheProjectswindowoftheVBAIDE.ThisnewfolderistitledReferencesandcontainsthenameoftheprojectreferenced.
Onceyouhavereferencedaproject,youcanuseanypubliccodeorformcomponentinthatproject.
WhenaprojectthatreferencesanotherprojectisloadedintoAutoCAD,thereferencedprojectisautomaticallyloadedintoAutoCADaswell.Thereferencedprojectcannotbecloseduntilallprojectsthatreferenceitareclosedfirst.
Youcannotmakecircularreferences.Thatis,youcannotreferenceaprojectthatcontainsareferencebacktothefirstproject.Ifyouaccidentallycreateacircularreference,youwillbenotifiedbyVBA.
ProjectreferencingisastandardfeatureofMicrosoftVBA.ThereisnoadditionalworkinAutoCADtoextendthisfunctionality.YoucanfindmoreinformationonreferencingprojectsintheMicrosoftVBAHelp.YoucanopentheMicrosoftVBAHelpfromtheHelpmenuintheVBAIDE.
Note YoucannotreferenceembeddedprojectsorVBAprojectsfromotherapplications.
ToreferenceanotherVBAproject
1. IntheProjectwindowoftheVBAIDE,selecttheprojecttowhichyouwillbeaddingthereference.
2. FromtheToolsmenu,selecttheReferencesoptiontoopentheReferencesdialogbox.
3. FromtheReferencesdialogbox,presstheBrowsebuttontoopentheAddReferencedialogbox.
4. FromtheAddReferencedialogbox,selecttheprojectfileyouwanttoreferenceandthenpresstheOpenbutton.
5. FromtheAddReferencedialogbox,selecttheOKbuttontocompletethereferenceaddition.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>
SettheVBAIDEOptions
YoucanchangethecharacteristicsoftheVBAIDEusingtheOptionsdialogbox.ToopentheOptionsdialogbox,usetheToolsmenuandselectOptions.
TheOptionsdialogboxcontainsfourtabs:Editor,EditorFormat,General,andDocking.
Topicsinthissection
EditorEditorFormatGeneralDocking
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>SettheVBAIDEOptions>
Editor
TheEditortabspecifiestheCodewindowandProjectwindowsettings.
Codesettingsinclude
AutoSyntaxCheck
RequireVariableDeclaration
AutoListMember
AutoQuickInfo
AutoDataTips
AutoIndent
TabWidth
Windowsettingsinclude
DragandDropTextEditing
DefaulttoFullModuleView
ProcedureSeparatorDisplay
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>SettheVBAIDEOptions>
EditorFormat
TheEditorFormattabspecifiestheappearanceofyourcode.
Youcan
Changecolorofthecode
Changetextlistitems
Changeforeground
Changebackground
Changemarginindicators
Changetextfontandsize
Displayorhidethemarginindicator
Displayorhidesampletextforyoursettings
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>SettheVBAIDEOptions>
General
TheGeneraltabspecifiesthesettings,errorhandling,andcompilesettingsforyourcurrentVBAproject.
Youcan
Changethegridsettingsfortheformgrid
Displayorhidetooltips
Settheautomaticcollapseofwindows
Choosetoreceivestatelossnotifications
Determinehowerrorsarehandled
Settheprojecttocompileondemandorperformbackgroundcompilations
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>EditYourProjectswiththeVBAIDE>SettheVBAIDEOptions>
Docking
TheDockingtaballowsyoutochoosewhichwindowsyouwanttobedockable.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>
PerformanIntroductoryExercise
NowthatyouhavelearnedthebasicsofprogramminginAutoCADVBA,let'strycreatingasimple“HelloWorld”exercise.InthisexerciseyouwillcreateanewAutoCADdrawing,addalineoftexttothatdrawing,thensavethedrawing,allfromVBA.
Tocreatethe“HelloWorld”textobject
1. OpentheVBAIDEbyenteringthefollowingcommandfromtheAutoCADcommandline:Command:VBAIDE
2. OpentheCodewindowbyselectingtheCodeoptionfromtheViewmenuintheVBAIDE.
3. CreateanewprocedureintheprojectbyselectingtheProcedureoptionfromtheInsertmenuintheVBAIDE.
4. Whenpromptedfortheprocedureinformation,enteranamesuchasHelloWorld.MakesuretheTypeselectedisSub,andtheScopeselectedisPublic.
5. ChooseOK.
6. Enterthefollowingcode(thatopensanewdrawing)betweenthelinesPublicSubHelloWorld()andEndSub.
ThisDrawing.Application.Documents.Add
7. Enterthefollowingcode(thatcreatesthetextstringanddefinesitsinsertionlocation)immediatelyfollowingthecodeenteredinstep6.
DiminsPoint(0To2)AsDouble'Declareinsertionpoint
DimtextHeightAsDouble'Declaretextheight
DimtextStrAsString'Declaretextstring
DimtextObjAsAcadText'Declaretextobject
insPoint(0)=2'Setinsertionpointxcoordinate
insPoint(1)=4'Setinsertionpointycoordinate
insPoint(2)=0'Setinsertionpointzcoordinate
textHeight=1'Settextheightto1.0
textStr="HelloWorld!"'Setthetextstring
'CreatetheTextobject
SettextObj=ThisDrawing.ModelSpace.AddText_
(textStr,insPoint,textHeight)
8. Enterthecode(thatsavesthedrawing)immediatelyfollowingthecodeenteredinstep7.
ThisDrawing.SaveAs("Hello.dwg")
9. RunyourprogrambyselectingtheRunSub/UserFormoptionfromtheRunmenuintheVBAIDE.Whentheprogramfinishesrunning,bringtheAutoCADapplicationtothefront.Youshouldseeyourtext“HelloWorld!”visibleinyourdrawing.ThedrawingnameshouldbeHello.dwg.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>
MoreInformation
MoreinformationontheVBAIDEandtheVBAprogramminglanguageisavailableintheHelpfilesprovidedbyMicrosoft.ToaccesstheMicrosoftHelpfiles,chooseMicrosoftVisualBasicHelpfromtheHelpmenuintheVBAIDE.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>
AutoCADVBAProjectTerms
GlobalProject
AVBAprojectstoredina.dvbfile.
EmbeddedProject
AVBAprojectstoredinanAutoCADdrawing.
RegularDocument
AnAutoCADdrawingthatdoesnotcontainVBAembeddedprojects.
SmartDocument
AnAutoCADdrawingthatcontainsoneormoreVBAembeddedprojects.
CurrentProject
TheprojectcurrentlyselectedintheVBAIDE.
ThisDrawing
ThisDrawingisaVBAprogrammingtermusedtorepresentthecurrentdrawing.Forglobalprojects,ThisDrawingalwaysreferstotheactivedocumentinAutoCAD.Forembeddedprojects,ThisDrawingalwaysreferstothedocumentcontainingtheproject.
VBAIDE
TheVBAinteractivedevelopmentenvironment.Thisapplicationallowsyoutoeditthecodeandformsinyourproject,orcopycodeandformsfromotherprojects.ItalsoallowsyoutosetreferencestootherapplicationObjectModels.
VBAManager
TheVBAManagerallowsyoutomanageyourprojects.Youcancreate,delete,embed,orextractprojects.Youcanalsoviewwhichprojects,ifany,
areembeddedinanopendrawing.
MacrosDialogBox
TheMacrosdialogboxallowsyoutorun,delete,andcreatenewmacros,andprovidesaccesstotheVBAprojectoptions.
Pleasesendusyourcommentaboutthispage
GettingStartedwithVBA>
AutoCADVBACommands
VBAIDE
BringsuptheVBAIDE.TheVBAIDEallowsyoutoedit,run,anddebugprogramsinteractively.AlthoughtheVBAIDEisinvokedonlywhenAutoCADisrunning,itcanbeminimized,opened,andclosedindependentoftheAutoCADApplicationwindow.
VBALOAD
LoadsaVBAprojectintothecurrentAutoCADsession.
VBARUN
RunsaVBAmacrofromtheMacrosdialogboxorfromtheAutoCADcommandline.
VBAUNLOAD
UnloadsaVBAprojectfromthecurrentAutoCADsession.IftheVBAprojectismodifiedbutnotsaved,theuserisaskedtosaveitwiththeSaveProjectdialogbox(orcommandlineequivalent).
VBAMAN
DisplaystheVBAManagerallowingyoutoview,create,load,close,embed,andextractprojects.
VBASTMT
ExecutesaVBAstatementfromtheAutoCADcommandline.
Pleasesendusyourcommentaboutthispage
<$nopage>xdata.<$nopage>rootobject:
ActiveXAutomationBasics
TouseAutoCADActiveXAutomationeffectivelyyoushouldbefamiliarwiththeAutoCADentities,objects,andfeaturesrelatingtothetypeofapplicationyouaredeveloping.Thegreateryourknowledgeofanobject'sgraphicalandnongraphicalproperties,theeasieritisforyoutomanipulatethemthroughAutoCADActiveXAutomation.
RememberthattheAutoCADActiveXAutomationHelpfileisavailable—justpressF1.Ifyouarehavingtroublewithaparticularobject,method,orproperty,highlighttheobject,method,orpropertyintheVBAIDEandpressF1.
Topicsinthissection
UnderstandtheAutoCADObjectModelAccesstheObjectHierarchyCollectionObjectsUnderstandPropertiesandMethodsUnderstandParentObjectsLocatetheTypeLibraryUseVariantsinMethodsandPropertiesUsingOtherProgrammingLanguages
Pleasesendusyourcommentaboutthispage
<$nopage>xdata.
ActiveXAutomationBasics>
UnderstandtheAutoCADObjectModel
AnobjectisthemainbuildingblockoftheAutoCAD®ActiveX®interface.EachexposedobjectrepresentsaprecisepartofAutoCAD.TherearemanydifferenttypesofobjectsintheAutoCADActiveXinterface.Forexample:
Graphicalobjectssuchaslines,arcs,text,anddimensionsareobjects.
Stylesettingssuchaslinetypesanddimensionstylesareobjects.
Organizationalstructuressuchaslayers,groups,andblocksareobjects.
Thedrawingdisplaysuchasviewandviewportareobjects.
EventhedrawingandtheAutoCADapplicationareconsideredobjects.
Theobjectsarestructuredinahierarchicalfashion,withtheApplicationobjectattheroot.TheviewofthishierarchicalstructureisreferredtoastheObjectModel.TheObjectModelshowsyouwhichobjectprovidesaccesstothenextlevelofobjects.
Topicsinthissection
TheApplicationObjectTheDocumentObjectTheCollectionObjectsTheGraphicalandNongraphicalObjectsThePreferences,Plot,andUtilityObjectsUseNewAutoCADFeatures
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>UnderstandtheAutoCADObjectModel>
TheApplicationObject
TheApplicationobjectistheRootobjectfortheAutoCADActiveXAutomationObjectModel.FromtheApplicationobject,youcanaccessanyoftheotherobjects,orthepropertiesormethodsassignedtoanyobject.
Forexample,theApplicationobjecthasaPreferencespropertythatreturnsthePreferencesobject.Thisobjectprovidesaccesstotheregistry-storedsettingsintheOptionsdialogbox.(Drawing-storedsettingsarecontainedintheDatabasePreferencesobject,whichwillbediscussedlater.)OtherpropertiesoftheApplicationobjectgiveyouaccesstoapplication-specificdatasuchastheapplicationnameandversion,andtheAutoCADsize,location,andvisibility.ThemethodsoftheApplicationobjectperformapplication-specificactionssuchaslisting,loading,andunloadingADSandARXapplications,andquittingAutoCAD.
TheApplicationobjectalsoprovideslinkstotheAutoCADdrawingsthroughtheDocumentscollection,theAutoCADmenusandtoolbarsthroughtheMenuBarandMenuGroupscollections,andtheVBAIDEthroughapropertycalledVBE.
TheApplicationobjectisalsotheGlobalobjectfortheActiveXinterface.ThismeansthatallthemethodsandpropertiesfortheApplicationobjectareavailableintheglobalnamespace.
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>UnderstandtheAutoCADObjectModel>
TheDocumentObject
TheDocumentobject,whichisactuallyanAutoCADdrawing,isfoundintheDocumentscollectionandprovidesaccesstoallofthegraphicalandmostofthenongraphicalAutoCADobjects.Accesstothegraphicalobjects(lines,circles,arcs,andsoforth)isprovidedthroughtheModelSpaceandPaperSpacecollections,andaccesstonongraphicalobjects(layers,linetypes,textstyles,andsoforth)isprovidedthroughlike-namedcollectionssuchasLayers,Linetypes,andTextStyles.TheDocumentobjectalsoprovidesaccesstothePlotandUtilityobjects.
Toaccessdrawingproperties,usetheSummaryInfopropertyoftheDocumentobject.
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>UnderstandtheAutoCADObjectModel>
TheCollectionObjects
AutoCADgroupsmostobjectsincollections.Althoughthesecollectionscontaindifferenttypesofdata,theycanbeprocessedusingsimilartechniques.Eachcollectionhasamethodforaddinganobjecttothecollection.MostcollectionsusetheAddmethodforthispurpose.However,entityobjectsareusuallyaddedusingamethodtitledAdd<Entityname>.Forexample,toaddalineyouwouldusetheAddLinemethod.
Collectionsalsohavesomeothermethodsandpropertiesincommon.TheCountpropertycanbeusedtoobtainazero-basedcountoftheobjectsinacollection.TheItemmethodcanbeusedtoobtainanyobjectwithinacollection.
Pleasesendusyourcommentaboutthispage
<$nopage>xdata.
ActiveXAutomationBasics>UnderstandtheAutoCADObjectModel>
TheGraphicalandNongraphicalObjects
Graphicalobjects,alsoknownasentities,arethevisibleobjects(lines,circles,rasterimages,andsoforth)thatmakeupadrawing.Tocreatetheseobjects,usetheappropriateAdd<Entityname>method.Tomodifyorquerytheseobjects,usethemethodsorpropertiesoftheobjectitself.EachgraphicalobjecthasmethodsthatallowanapplicationtoperformmostoftheAutoCADeditingcommandssuchasCopy,Erase,Move,Mirror,andsoforth.Theseobjectsalsohavemethodsforsettingandretrievingextendeddata(xdata),highlightingandupdating,andretrievingtheboundingboxoftheobject.GraphicalobjectshavetypicalpropertiessuchasLayer,Linetype,Color,andHandle.Theyalsohavespecificproperties,dependingontheirobjecttype,suchasCenter,Radius,andArea.
Nongraphicalobjectsaretheinvisible(informational)objectsthatarepartofadrawing,suchasLayers,Linetypes,DimStyles,SelectionSets,andsoforth.Tocreatetheseobjects,usetheAddmethodoftheparentCollectionobject.Tomodifyorquerytheseobjects,usethemethodsorpropertiesoftheobjectitself.Eachnongraphicalobjecthasmethodsandpropertiesspecifictoitspurpose;allhavemethodsforsettingandretrievingextendeddata(xdata),anddeletingthemselves.
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>UnderstandtheAutoCADObjectModel>
ThePreferences,Plot,andUtilityObjects
UnderthePreferencesobjectisasetofobjects,eachcorrespondingtoatabintheOptionsdialogbox.Together,theseobjectsprovideaccesstoalltheregistry-storedsettingsintheOptionsdialogbox.Drawing-storedsettingsarecontainedintheDatabasePreferencesobject.Youcanalsosetandmodifyoptions(andsystemvariablesthatarenotpartoftheOptionsdialogbox)withtheSetVariableandGetVariablemethods.FormoreinformationaboutsettingoptionsseeSetAutoCADPreferences.
ThePlotobjectprovidesaccesstosettingsinthePlotdialogboxandgivesanapplicationtheabilitytoplotthedrawingusingvariousmethods.Formoreinformationonplotting,seePlotYourDrawing.
TheUtilityobjectprovidesuserinputandconversionfunctions.TheuserinputfunctionsaremethodsthatprompttheuserontheAutoCADcommandlineforinputofvarioustypesofdata,suchasstrings,integers,reals,points,andsoforth.TheconversionfunctionsaremethodsthatoperateonAutoCAD-specificdatatypessuchaspointsandangles,inadditiontostringandnumberhandling.Formoreinformationontheuserinputfunctions,seePromptforUserInput.
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>UnderstandtheAutoCADObjectModel>
UseNewAutoCADFeatures
IfyourAutomationprojectusesafeaturethatwasnotinapreviousAutoCADversion,youmustexplicitlydeclaretheAutoCADinterfaceyouareusingintheproject.
IfanAutomationprojectcontainsexplicitdeclarationsofinterfacesthatarenewinaspecificversionofAutoCAD,donotusethatprojectwithearlierversionsofAutoCAD.
Pleasesendusyourcommentaboutthispage
<$nopage>rootobject:
ActiveXAutomationBasics>
AccesstheObjectHierarchy
AccessingtheobjecthierarchyiseasyfromwithinVBA.ThisisbecauseVBAisrunningin-processwiththecurrentAutoCADsessionsothereisnoadditionalstepneededtoconnectittotheapplication.
VBAprovidesalinktotheactivedrawinginthecurrentAutoCADsessionthroughtheThisDrawingobject.ByusingThisDrawingyougainimmediateaccesstothecurrentDocumentobjectandallofitsmethodsandproperties,andalloftheotherobjectsinthehierarchy.
Whenusedinglobalprojects,ThisDrawingalwaysreferstotheactivedocumentinAutoCAD.Whenusedinembeddedprojects,ThisDrawingalwaysreferstothedocumentcontainingtheproject.Forexample,thefollowinglineofcodeinaglobalprojectsaveswhateverdrawingiscurrentlyactiveinAutoCAD:
ThisDrawing.Save
Topicsinthissection
ReferenceObjectsintheObjectHierarchyAccesstheApplicationObject
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>AccesstheObjectHierarchy>
ReferenceObjectsintheObjectHierarchy
Youcanreferenceobjectsdirectlyorthroughauser-definedvariable.Toreferencetheobjectsdirectly,includetheobjectinthecallinghierarchy.Forexample,thefollowingstatementaddsalineinmodelspace.NoticethatthehierarchystartswithThisDrawing,goestotheModelSpaceobject,andthencallstheAddLinemethod:
DimstartPoint(0To2)AsDouble,endPoint(0To2)AsDouble
DimLineObjasAcadLine
startPoint(0)=0:startPoint(1)=0:startPoint(2)=0
endPoint(0)=30:endPoint(1)=20:endPoint(2)=0
SetLineObj=ThisDrawing.ModelSpace.AddLine(startPoint,endPoint)
Toreferencetheobjectsthroughauser-definedvariable,definethevariableasthedesiredtype,thensetthevariabletotheappropriateobject.Forexample,thefollowingcodedefinesavariable(moSpace)oftypeAcadModelSpaceandsetsthevariableequaltothecurrentmodelspace:
DimmoSpaceAsAcadModelSpace
SetmoSpace=ThisDrawing.ModelSpace
Thefollowingstatementthenaddsalinetothemodelspaceusingtheuser-definedvariable:
DimstartPoint(0To2)AsDouble,endPoint(0To2)AsDouble
DimLineObjasAcadLine
startPoint(0)=0:startPoint(1)=0:startPoint(2)=0
endPoint(0)=30:endPoint(1)=20:endPoint(2)=0
SetLineObj=moSpace.AddLine(startPoint,endPoint)
Retrievingthefirstentityinmodelspace
Thefollowingexamplereturnsthefirstentityobjectinmodelspace.Similarcodecandothesameforpaperspaceentities.Notethatalldrawingobjectscan
bedefinedasAcadEntityobjects:
SubCh2_FindFirstEntity()
'Thisexamplereturnsthefirstentityinmodelspace
OnErrorResumeNext
DimentityAsAcadEntity
IfThisDrawing.ModelSpace.count<>0Then
Setentity=ThisDrawing.ModelSpace.Item(0)
MsgBoxentity.ObjectName+_
"isthefirstentityinmodelspace."
Else
MsgBox"Therearenoobjectsinmodelspace."
EndIf
EndSub
Pleasesendusyourcommentaboutthispage
<$nopage>rootobject:
ActiveXAutomationBasics>AccesstheObjectHierarchy>
AccesstheApplicationObject
TheApplicationpropertyoftheDocumentobjectprovidesaccesstotheApplicationobject.TheApplicationobjectisabovetheDocumentobjectintheobjecthierarchy.
TheThisDrawingobjectprovidesaccesstotheDocumentobject.Forexample,thefollowinglineofcodeupdatestheapplication:
ThisDrawing.Application.Update
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>
CollectionObjects
ACollectionobjectisapredefinedobjectthatcontains(isaparentobjectfor)allinstancesofasimilarobject.Thefollowingisalistofcollectionobjects:
Collection
ContainsalldocumentsopeninthecurrentAutoCADsession.
ModelSpaceCollection
Containsallgraphicalobjects(entities)inmodelspace.
PaperSpaceCollection
Containsallgraphicalobjects(entities)intheactivepaperspacelayout.
BlockObject
Containsallentitieswithinaspecificblockdefinition.
BlocksCollection
Containsallblocksinthedrawing.
DictionariesCollection
Containsalldictionariesinthedrawing.
DimStylesCollection
Containsalldimensionstylesinthedrawing.
FileDependenciesCollection
ContainsallitemsintheFileDependencyList.
GroupsCollection
Containsallgroupsinthedrawing.
HyperlinksCollection
Containsallhyperlinksforagivenentity.
LayersCollection
Containsalllayersinthedrawing.
LayoutsCollection
Containsalllayoutsinthedrawing.
LinetypesCollection
Containsalllinetypesinthedrawing.
MenuBarCollection
ContainsallmenuscurrentlydisplayedinAutoCAD.
MenuGroupsCollection
ContainsallmenusandtoolbarscurrentlyloadedinAutoCAD.
PlotConfigurationsCollection
Containsnamedplotsettingsinthedrawing.
RegisteredApplicationsCollection
Containsallregisteredapplicationsinthedrawing.
SelectionSetsCollection
Containsallselectionsetsinthedrawing.
TextStylesCollection
Containsalltextstylesinthedrawing.
UCSsCollection
Containsallusercoordinatesystems(UCS's)inthedrawing.
ViewsCollection
Containsallviewsinthedrawing.
ViewportsCollection
Containsallviewportsinthedrawing.
Topicsinthissection
AccessaCollectionAddaNewMembertoaCollectionObjectIteratethroughaCollectionObjectDeleteaMemberofaCollectionObject
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>CollectionObjects>
AccessaCollection
MostcollectionobjectsareaccessedthroughtheDocumentobject.TheDocumentobjectcontainsapropertyforeachoftheCollectionobjects.Forexample,thefollowingcodedefinesavariableandsetsittotheLayerscollectionofthecurrentdrawing:
DimlayerCollectionasAcadLayers
SetlayerCollection=ThisDrawing.Layers
TheDocumentscollection,MenuBarcollection,andMenuGroupscollectionareaccessedthroughtheApplicationobject.TheApplicationobjectcontainsapropertyforeachofthesecollections.Forexample,thefollowingcodedefinesavariableandsetsittotheMenuGroupscollectionfortheapplication:
DimMenuGroupsCollectionasAcadMenuGroups
SetMenuGroupsCollection=ThisDrawing.Application.MenuGroups
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>CollectionObjects>
AddaNewMembertoaCollectionObject
Toaddanewmembertothecollection,usetheAddmethod.Forexample,thefollowingcodecreatesanewlayerandaddsittotheLayerscollection:
DimnewLayerasAcadLayer
SetnewLayer=ThisDrawing.Layers.Add("MyNewLayer")
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>CollectionObjects>
IteratethroughaCollectionObject
ToselectaspecificmemberofaCollectionobject,usetheItemmethod.TheItemmethodrequiresanidentifieraseitheranindexnumberspecifyingthelocationoftheitemwithinthecollectionorastringrepresentingthenameoftheitem.
TheItemmethodisthedefaultmethodforacollection.Ifyoudonotspecifyamethodnamewhenreferringtoacollection,Itemisassumed.Thefollowingstatementsareequivalent:
ThisDrawing.Layers.Item("ABC")
ThisDrawing.Layers("ABC")
Note Donotusetheentityeditmethods(Copy,Array,Mirror,andsoforth)onanyobjectwhilesimultaneouslyiteratingthroughacollectionusingtheForEachmechanism.Eitherfinishyouriterationbeforeyouattempttoeditanobjectinthecollectionorcreateatemporaryarrayandsetitequaltothecollection.Thenyoucaniteratethroughthecopiedarrayandperformyouredits.
IteratethroughtheLayerscollection
Thefollowingexampleiteratesthroughacollectionanddisplaysthenamesofalllayersinthecollection:
SubCh2_IterateLayer()
'Iteratethroughthecollection
OnErrorResumeNext
DimIAsInteger
DimmsgAsString
msg=""
ForI=0ToThisDrawing.Layers.count-1
msg=msg+ThisDrawing.Layers.Item(I).Name+vbCrLf
Next
MsgBoxmsg
EndSub
FindthelayernamedMyLayer
ThefollowingexamplereferstolayernamedMyLayer,andissuesamessageifthelayerdoesnotexist:
SubCh2_FindLayer()
'UsetheItemmethodtofindalayernamedMyLayer
OnErrorResumeNext
DimABCLayerAsAcadLayer
SetABCLayer=ThisDrawing.Layers("MyLayer")
IfErr<>0Then
MsgBox"Thelayer'MyLayer'doesnotexist."
EndIf
EndSub
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>CollectionObjects>
DeleteaMemberofaCollectionObject
Todeleteaspecificdimensionstyle,usetheDeletemethodfoundonthememberobject.Forexample,thefollowingcodedeletesthelayerABC:
DimABCLayerasAcadLayer
SetABCLayer=ThisDrawing.Layers.Item("ABC")
ABCLayer.Delete
Onceanobjecthasbeendeleted,youmustneverattempttoaccesstheobjectagainlaterintheprogram.
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>
UnderstandPropertiesandMethods
Eachobjecthasassociatedpropertiesandmethods.Propertiesdescribeaspectsoftheindividualobject,whilemethodsareactionsthatcanbeperformedontheindividualobject.Onceanobjectiscreated,youcanqueryandedittheobjectthroughitspropertiesandmethods.
Forexample,aCircleobjecthastheCenterproperty.Thispropertyrepresentsthe3Dworldcoordinatesystemcoordinateatthecenterofthatcircle.Tochangethecenterofthecircle,simplysetthispropertytothenewcoordinate.TheCircleobjectalsohasamethodcalledOffset.Thismethodcreatesanewobjectataspecifiedoffsetdistancefromtheexistingcircle.ToseealistofallpropertiesandmethodsfortheCircleobject,refertotheCircleobjectintheAutoCADActiveXandVBAReference.
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>
UnderstandParentObjects
Eachobjecthasaparentobjecttowhichitispermanentlylinked.AllobjectsoriginatefromasingleparentobjectcalledtheRootobject.Youcanaccessalltheobjectsintheinterfacebyfollowingthelinksfromtheroottothechildobjects.Additionally,objectshaveapropertycalledApplicationthatlinksdirectlybacktotheRootobject.
TheRootobjectfortheAutoCADinterfaceistheAutoCADapplication.
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>
LocatetheTypeLibrary
Theobjects,properties,andmethodsexposedbyAutomationobjectsarecontainedinatypelibrary.Atypelibraryisafileorpartofafilethatdescribesthetypeofoneormoreobjects.
Typelibrariesdonotstoreobjects;theystoreinformation.Byaccessingatypelibrary,applicationsandbrowserscandeterminethecharacteristicsofanobject,suchastheinterfacessupportedbytheobjectandthenamesandaddressesofthemembersofeachinterface.
BeforeyoucanusetheAutomationobjectexposedbyanapplication,youmustreferenceitstypelibrary.ThereferenceisautomaticallysetintheVBAIDE.ForotherinteractivedevelopmentenvironmentsyoumustcreateareferencetotheAutoCADtypelibraryfile,acax17enu.tlb,whichislocatedatc:\programfiles\commonfiles\autodeskshared.ToaccessSheetSetManagerobjectsintheVBAIDEorinotherenvironments,youmustcreateareferencetotheAcSmComponents171.0typelibraryfile,AcSmComponents17.tlb,whichislocatedatc:\programfiles\commonfiles\autodeskshared.
Youcanuseanapplication'sobjectswithoutreferencingtheapplication'stypelibrary.However,itispreferabletoaddthetypelibraryreferenceforthefollowingreasons:
Globallyaccessiblefunctionsmaybeaccesseddirectlywithoutqualification.
Invocationoffunctions,properties,andmethodscanbecheckedatcompiletimeforcorrectness,andthereforewillexecutemorequicklyatruntime.
Itispossibletodeclarevariablesofthetypesdefinedinthelibrary,whichincreasesruntimereliabilityandreadability.
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>
UseVariantsinMethodsandProperties
ActiveXAutomationusesvariantstopassarraysofdata.Althoughthismayseemconfusingtoanoviceuser,itisnotdifficultonceyoulearnthebasics.Inaddition,AutoCADActiveXAutomationprovidesutilitiestohelpyouconvertyourdatatypes.
Topicsinthissection
WhatIsaVariant?UseVariantsforArrayDataConvertArraystoVariantsInterpretVariantArrays
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>UseVariantsinMethodsandProperties>
WhatIsaVariant?
Avariantisaspecialdatatypethatcancontainanykindofdataexceptfixed-lengthstringdataanduser-definedtypes.AvariantcanalsocontainthespecialvaluesEmpty,Error,Nothing,andNULL.YoucandeterminehowthedatainavariantistreatedusingtheVarTypeorTypeNameVBAfunction.
YoucanusetheVariantdatatypeinplaceofmostanydatatypetoworkwithdatainamoreflexibleway.
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>UseVariantsinMethodsandProperties>
UseVariantsforArrayData
VariantsareusedtopassarraydatainandoutofAutoCADActiveXAutomation.ThismeansthatyourarraymustbeavarianttobeacceptedbyAutoCADActiveXAutomationmethodsandproperties.Inaddition,arraydataoutputfromAutoCADActiveXAutomationmustbehandledasavariant.
Note InAutoCAD,VBAinputarraysareautomaticallyconvertedtovariants.Thismeansthatyoudon'thavetoprovideavariantarrayasinputtotheActiveXAutomationmethodsandpropertieswhenusingthemfromVBA.However,alltheoutputarrayswillbeintheformofvariants,soremembertohandlethemappropriately.
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>UseVariantsinMethodsandProperties>
ConvertArraystoVariants
AutoCADActiveXAutomationprovidesautilitymethodtoconvertanarrayofdataintoavariant.ThismethodistheCreateTypedArraymethod,whichcreatesavariantthatcontainsanarrayofintegers,floatingnumbers,doubles,andsoforth.YoucanpasstheresultingvariantintoanyAutoCADmethodorpropertythatacceptsanarrayofnumbersasavariant.
TheCreateTypedArraymethodtakesasinputthetypeofvaluesthatareinthearray,andthearrayofdatatobeconverted.Itreturnsthearrayofvaluesasavariant.
CreateasplinewiththeCreateTypedArraymethod
ThefollowingcodeconvertsthreearraysusingCreateTypedArray:thecoordinatesforaspline'sfitpoints,andthestartandendtangentofthespline.ItthenpassesthevariantintotheAddSplinemethodtocreatethespline.
SubCh2_CreateSplineUsingTypedArray()
'Thisexamplecreatesasplineobjectinmodelspace
'usingtheCreateTypedArraymethod.
DimsplineObjAsAcadSpline
DimstartTanAsVariant
DimendTanAsVariant
DimfitPointsAsVariant
DimutilObjAsObject'latebindtheUtilityobject
SetutilObj=ThisDrawing.Utility
'DefinetheSplineObject
utilObj.CreateTypedArray_
startTan,vbDouble,0.5,0.5,0
utilObj.CreateTypedArray_
endTan,vbDouble,0.5,0.5,0
utilObj.CreateTypedArray_
fitPoints,vbDouble,0,0,0,5,5,0,10,0,0
SetsplineObj=ThisDrawing.ModelSpace.AddSpline_
(fitPoints,startTan,endTan)
'Zoominonthenewlycreatedspline
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>UseVariantsinMethodsandProperties>
InterpretVariantArrays
ArrayinformationpassedbackfromAutoCADActiveXAutomationispassedbackasavariant.Ifyouknowthedatatypeofthearray,youcansimplyaccessthevariantasanarray.Ifyoudon'tknowthedatatypecontainedinthevariant,usetheVBAfunctionsVarTypeorTypename.Thesefunctionsreturnthetypeofdatainthevariant.Ifyouneedtoiteratethroughthearray,youcanusetheVBAForEachstatement.
Calculatethedistancebetweentwopoints
Thefollowingcodedemonstratescalculatingthedistancebetweentwopointsinputbytheuser.Inthisexample,thedatatypeisknownbecauseallcoordinatesaredoubles.3Dcoordinatesareathree-elementarrayofdoublesand2Dcoordinatesareatwo-elementarrayofdoubles.
SubCh2_CalculateDistance()
Dimpoint1AsVariant
Dimpoint2AsVariant
'Getthepointsfromtheuser
point1=ThisDrawing.Utility.GetPoint_
(,vbCrLf&"Firstpoint:")
point2=ThisDrawing.Utility.GetPoint_
(point1,vbCrLf&"Secondpoint:")
'Calculatethedistancebetweenpoint1andpoint2
DimxAsDouble,yAsDouble,zAsDouble
DimdistAsDouble
x=point1(0)-point2(0)
y=point1(1)-point2(1)
z=point1(2)-point2(2)
dist=Sqr((Sqr((x^2)+(y^2))^2)+(z^2))
'Displaytheresultingdistance
MsgBox"Thedistancebetweenthepointsis:"_
&dist,,"CalculateDistance"
EndSub
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>
UsingOtherProgrammingLanguages
ThismanualiswrittenfortheVBAprogramminglanguage.TheprogrammingexamplesandsampleapplicationsarewritteninVBA.Tousethecodeinotherprogrammingenvironments,youmustupdateitforthechosenenvironment.
Usethedocumentationforyourdevelopmentenvironmenttohelpyouconverttheexamplecode.
Note TheregistrykeyforCOMapplicationaccessforAutoCAD2009isAutoCAD.Application.17.
Topicsinthissection
ConverttheVBACodetoVB
Pleasesendusyourcommentaboutthispage
ActiveXAutomationBasics>UsingOtherProgrammingLanguages>
ConverttheVBACodetoVB
ToupdateacodeexampleforusewithVB,youmustfirstreferencetheAutoCADtypelibrary.TodothisinVB,selecttheReferencesoptionfromtheProjectmenutolaunchtheReferencesdialogbox.FromtheReferencesdialogbox,choosethetypelibraryforAutoCAD,andthenclickOK.
Next,inthecodeexample,replaceallreferencestoThisDrawingwithauser-specifiedvariablereferencingtheactivedocument.Todothis,defineavariablefortheAutoCADapplication(acadApp)andforthecurrentdocument(acadDoc).Then,settheapplicationvariabletothecurrentAutoCADapplication.
IfAutoCADisrunning,theVBGetObjectfunctionretrievestheAutoCADApplicationobjectwhenyouspecifytheAutoCADversionnumber.IfAutoCADisnotrunning,anerroroccursthat(inthisexample)istrapped,thencleared.TheCreateObjectfunctionthenattemptstocreateanAutoCADApplicationobject.Ifitsucceeds,AutoCADisstarted;ifitfails,amessageboxdisplaysadescriptionoftheerror.
WhenrunningmultiplesessionsofAutoCAD,theGetObjectfunctionwillreturnthefirstinstanceofAutoCADintheWindowsRunningObjectTable.SeetheMicrosoftVBAdocumentationontheRunningObjectTable(ROT)andtheGetObjectfunctionformoreinformationonverifyingthesessionreturnedbyGetObject.
YoumustsettheAutoCADapplication'sVisiblepropertytoTRUEinordertodisplaytheAutoCADdrawingwindow.
IfGetObjectcreatesanewinstanceofAutoCAD(thatis,AutoCADwasnotalreadyrunningwhenyouissuedGetObject),failuretosetVisibletoTRUEresultsinaninvisibleAutoCADapplication;AutoCADwillnotevenappearontheWindowstaskbar.
Note Useversion-dependentProgIDs.IfaCreateObjectorGetObjectfunctionusesaversion-independentProgID,changethefunctiontouseaversion-dependentProgID.Forexample,ifyouareusingCreateObject,youchangeCreateObject("AutoCAD.Application")toCreateObject("AutoCAD.Application.17").Additionally,ifaGetInterfaceObjectmethodusesaversion-independentProgID,themethodmustbechangedtouseaversion-dependentProgID.
ConnecttoAutoCADfromVisualBasic6
ThefollowingcodeexampleusestheClearandDescriptionpropertiesofErr.Ifyourcodingenvironmentdoesnotsupporttheseproperties,youwillneedtomodifytheexampleappropriately:
SubCh2_ConnectToAcad()
DimacadAppAsAcadApplication
OnErrorResumeNext
SetacadApp=GetObject(,"AutoCAD.Application.17")
IfErrThen
Err.Clear
SetacadApp=CreateObject("AutoCAD.Application.17")
IfErrThen
MsgBoxErr.Description
ExitSub
EndIf
EndIf
MsgBox"Nowrunning"+acadApp.Name+_
"version"+acadApp.Version
EndSub
Next,setthedocumentvariabletotheDocumentobjectintheAutoCADapplication.TheDocumentobjectisreturnedbytheActiveDocumentpropertyoftheApplicationobject.
DimacadDocasAcadDocument
SetacadDoc=acadApp.ActiveDocument
Fromthispointon,usetheacadDocvariabletoreferencethecurrentAutoCADdrawing.
VBAversusVBComparisonCodeExample
ThefollowingcodeexampledemonstratescreatingalineinbothVBAandVB.
CreatingalineusingVBA:
SubCh2_AddLineVBA()
'Thisexampleaddsaline
'inmodelspace
DimlineObjAsAcadLine
DimstartPoint(0To2)AsDouble
DimendPoint(0To2)AsDouble
'Definethestartandend
'pointsfortheline
startPoint(0)=1
startPoint(1)=1
startPoint(2)=0
endPoint(0)=5
endPoint(1)=5
endPoint(2)=0
'Createthelineinmodelspace
SetlineObj=ThisDrawing._
ModelSpace.AddLine_
(startPoint,endPoint)
'Zoominonthenewlycreatedline
ZoomAll
EndSub
CreatingalineusingVB:
SubCh2_AddLineVB()
OnErrorResumeNext
'ConnecttotheAutoCADapplication
DimacadAppAsAcadApplication
SetacadApp=GetObject_
(,"AutoCAD.Application.17")
IfErrThen
Err.Clear
SetacadApp=CreateObject_
("AutoCAD.Application.17")
IfErrThen
MsgBoxErr.Description
ExitSub
EndIf
EndIf
'ConnecttotheAutoCADdrawing
DimacadDocAsAcadDocument
SetacadDoc=acadApp.ActiveDocument
'Establishtheendpointsoftheline
DimlineObjAsAcadLine
DimstartPoint(0To2)AsDouble
DimendPoint(0To2)AsDouble
startPoint(0)=1
startPoint(1)=1
startPoint(2)=0
endPoint(0)=5
endPoint(1)=5
endPoint(2)=0
'CreateaLineobjectinmodelspace
SetlineObj=acadDoc.ModelSpace.AddLine_
(startPoint,endPoint)
ZoomAll
acadApp.visible=True
EndSub
Pleasesendusyourcommentaboutthispage
<$nopage>methods.
ControltheAutoCADEnvironment
ThischapterdescribesthefundamentalsfordevelopinganapplicationinAutoCAD.ItexplainshowtocontrolandworkeffectivelyintheAutoCADenvironment.
Topicsinthissection
Open,Save,andCloseDrawingsSetAutoCADPreferencesControltheApplicationWindowControltheDrawingWindowsResetActiveObjectsSetandReturnSystemVariablesDrawwithPrecisionPromptforUserInputAccesstheAutoCADCommandLineWorkwithNoDocumentsOpenImportOtherFileFormatsExporttoOtherFileFormats
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>
Open,Save,andCloseDrawings
TheDocumentscollectionandDocumentobjectprovideaccesstotheAutoCAD®filefunctions.
Tocreateanewdrawing,oropenanexistingdrawing,usethemethodsontheDocumentscollection.TheAddmethodcreatesanewdrawingandaddsthatdrawingtotheDocumentscollection.TheOpenmethodopensanexistingdrawing.ThereisalsoaClosemethodontheDocumentscollectionthatclosesallthedrawingsopenintheAutoCADsession.
UseeithertheSaveorSaveAsmethodtosaveadrawing.Occasionallyyouwillwanttocheckiftheactivedrawinghasanyunsavedchanges.ItisagoodideatodothisbeforeyouquittheAutoCADsessionorstartanewdrawing.UsetheSavedpropertytomakesurethatthecurrentdrawingdoesnotcontainanyunsavedchanges.
Toimportandexportdrawings,usetheImportandExportmethodsontheDocumentobject.
Openanexistingdrawing
ThisexampleusestheOpenmethodtoopenanexistingdrawing.TheVBADirfunctionisusedtocheckfortheexistenceofthefilebeforetryingtoopenit.YoushouldchangethedrawingfilenameorpathtospecifyanexistingAutoCADdrawingfileonyoursystem.
SubCh3_OpenDrawing()
DimdwgNameAsString
dwgName="c:\campus.dwg"
IfDir(dwgName)<>""Then
ThisDrawing.Application.Documents.OpendwgName
Else
MsgBox"File"&dwgName&"doesnotexist."
EndIf
EndSub
Createanewdrawing
ThisexampleusestheAddmethodtocreateanewdrawingbasedonthedefaulttemplate.
SubCh3_NewDrawing()
DimdocObjAsAcadDocument
SetdocObj=ThisDrawing.Application.Documents.Add
EndSub
Savetheactivedrawing
Thisexamplesavestheactivedrawingunderitscurrentnameandagainunderanewname.
SubCh3_SaveActiveDrawing()
'Savetheactivedrawingunderthecurrentname
ThisDrawing.Save
'Savetheactivedrawingunderanewname
ThisDrawing.SaveAs"MyDrawing.dwg"
EndSub
Testifadrawinghasunsavedchanges
ThisexamplecheckstoseeifthereareunsavedchangesandverifieswiththeuserthatitisOKtosavethedrawing(ifitisnotOK,skiptotheend).IfOK,usetheSavemethodtosavethecurrentdrawing,asshownhere:
SubCh3_TestIfSaved()
IfNot(ThisDrawing.Saved)Then
IfMsgBox("Doyouwishtosavethisdrawing?",_
vbYesNo)=vbYesThen
ThisDrawing.Save
EndIf
EndIf
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>
SetAutoCADPreferences
Therearenineobjectspertainingtooptions,eachrepresentingatabintheOptionsdialogbox.Theseobjectsprovideaccesstoalloftheregistry-storedoptionsintheOptionsdialogbox.YoucancustomizemanyoftheAutoCADsettingsbyusingpropertiesfoundontheseobjects.Theseobjectsare
PreferencesDisplay
PreferencesDrafting
PreferencesFiles
PreferencesOpenSave
PreferencesOutput
PreferencesProfiles
PreferencesSelection
PreferencesSystem
PreferencesUser
TheseobjectsareaccessiblewiththePreferencesobject.TogainaccesstothePreferencesobject,usethePreferencespropertyoftheApplicationobject:
DimacadPrefasAcadPreferences
SetacadPref=ThisDrawing.Application.Preferences
YoucanthenaccessanyofthespecificPreferencesobjectsusingtheDisplay,Drafting,Files,OpenSave,Output,Profile,Selection,System,andUserproperties.
Setthecrosshairstofullscreen
SubCh2_PrefsSetCursor()
'ThisexamplesetsthecrosshairsoftheAutoCADdrawingcursor
'tofullscreen.
'AccessthePreferencesobject
DimacadPrefAsAcadPreferences
SetacadPref=ThisDrawing.Application.Preferences
'UsetheCursorSizepropertytosetthesizeofthecrosshairs
acadPref.Display.CursorSize=100
EndSub
Displaythescreenmenuandscrollbars
SubCh2_PrefsSetDisplay()
'Thisexampleenablesthescreenmenuanddisablesthescroll
'barswiththeDisplayScreenMenuandDisplayScrollBars
'properties.
'AccessthePreferencesobject
DimacadPrefAsAcadPreferences
SetacadPref=ThisDrawing.Application.Preferences
'Displaythescreenmenuanddisablescrollbars
acadPref.Display.DisplayScreenMenu=True
acadPref.Display.DisplayScrollBars=False
EndSub
Topicsinthissection
DatabasePreferences
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>SetAutoCADPreferences>
DatabasePreferences
InadditiontotheninePreferencesobjects,theDatabasePreferencesobjectcontainsalltheoptionsstoredinthedrawing.Thisseparateobjectwasprovidedtomakethedrawing-storedoptionsavailabletoapplicationsaccessingAutoCADdrawingswithoutfirststartingtheAutoCADapplication(ObjectDBXapplications).
TheDatabasePreferencesobjectisfoundundertheDocumentobject.
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>
ControltheApplicationWindow
TheabilitytocontroltheApplicationwindowallowsdeveloperstheflexibilitytocreateeffectiveandintelligentapplications.TherewillbetimeswhenitisappropriateforyourapplicationtominimizetheAutoCADwindow,perhapswhileyourcodeisperformingworkinanotherapplicationsuchasExcel.Additionally,youwilloftenwanttoverifythestateoftheAutoCADwindowbeforeperformingsuchtasksaspromptingforinputfromtheuser.
UsingmethodsandpropertiesfoundontheApplicationobject,youcanchangetheposition,size,andvisibilityoftheApplicationwindow.YoucanalsousetheWindowStatepropertytominimize,maximize,andcheckthecurrentstateoftheApplicationwindow.
PositionandsizetheApplicationwindow
ThisexampleusestheWindowTop,WindowLeft,Width,andHeightpropertiestopositiontheAutoCADApplicationwindowintheupper-leftcornerofthescreenandsizeitto400pixelswideby400pixelshigh.
SubCh3_PositionApplicationWindow()
ThisDrawing.Application.WindowTop=0
ThisDrawing.Application.WindowLeft=0
ThisDrawing.Application.width=400
ThisDrawing.Application.height=400
EndSub
MaximizetheApplicationwindow
SubCh3_MaximizeApplicationWindow()
ThisDrawing.Application.WindowState=acMax
EndSub
MinimizetheApplicationwindow
SubCh3_MinimizeApplicationWindow()
ThisDrawing.Application.WindowState=acMin
EndSub
FindthecurrentstateoftheApplicationwindow
ThisexamplequeriesthestateoftheApplicationwindowanddisplaysthestateinamessageboxtotheuser.
SubCh3_CurrentWindowState()
DimCurrWindowStateAsInteger
DimmsgAsString
CurrWindowState=ThisDrawing.Application.WindowState
msg=Choose(CurrWindowState,"normal",_
"minimized","maximized")
MsgBox"Theapplicationwindowis"+msg
EndSub
MaketheApplicationwindowinvisible
ThefollowingcodeusestheVisiblepropertytomaketheAutoCADapplicationinvisibletotheenduser.
SubCh3_HideWindowState()
ThisDrawing.Application.Visible=False
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>
ControltheDrawingWindows
LiketheAutoCADApplicationwindow,youcanminimize,maximize,reposition,resize,andcheckthestateofanyDocumentwindow.Butyoucanalsochangethewaythedrawingisdisplayedwithinawindowbyusingviews,viewports,andzoomingmethods.
AutoCADActiveXprovidesmanywaystodisplayviewsofyourdrawing.Youcancontrolthedrawingdisplaytomovequicklytodifferentareasofyourdrawingwhileyoutracktheoveralleffectofyourchanges.Youcanzoomtochangemagnificationorpantorepositiontheviewinthegraphicsarea,saveaviewandthenrestoreitwhenyouneedtoplotorrefertospecificdetails,ordisplayseveralviewsatonetimebysplittingthescreenintoseveraltiledviewports.
Topicsinthissection
PositionandSizetheDocumentWindowUseZoomUseNamedViewsUseTiledViewportsUpdatetheGeometryintheDocumentWindow
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>ControltheDrawingWindows>
PositionandSizetheDocumentWindow
UsetheDocumentobjecttomodifythepositionandsizeofanydocumentwindow.TheDocumentwindowcanbeminimizedormaximizedbyusingtheWindowStateproperty,andyoucanfindthecurrentstateoftheDocumentwindowbyusingtheWindowStateproperty.
PositionaDocumentwindow
ThisexampleusestheWidthandHeightpropertiestosettheactiveDocumentwindowto400pixelswideby400pixelshigh.
SubCh3_SizeDocumentWindow()
ThisDrawing.Width=400
ThisDrawing.Height=400
EndSub
MaximizetheactiveDocumentwindow
SubCh3_MaximizeDocumentWindow()
ThisDrawing.WindowState=acMax
EndSub
MinimizetheactiveDocumentwindow
SubCh3_MinimizeDocumentWindow()
ThisDrawing.WindowState=acMin
EndSub
FindthecurrentstateoftheactiveDocumentwindow
SubCh3_CurrentWindowState()
DimCurrWindowStateAsInteger
DimmsgAsString
CurrWindowState=ThisDrawing.WindowState
msg=Choose(CurrWindowState,"normal",_
"minimized","maximized")
MsgBox"Thedocumentwindowis"+msg
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>ControltheDrawingWindows>
UseZoom
Aviewisaspecificmagnification,position,andorientationofadrawing.ThemostcommonwaytochangeaviewistouseoneofthemanyAutoCADZoomoptions,whichincreasesordecreasesthesizeoftheimagedisplayedinthegraphicsarea.FormoreinformationonzoominginAutoCAD,see“MagnifyaView(Zoom)”intheUser'sGuide.
Topicsinthissection
DefineaZoomWindowScaleaViewCenterObjectsDisplayDrawingLimitsandExtents
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>ControltheDrawingWindows>UseZoom>
DefineaZoomWindow
Youcanquicklyzoominonanareabyspecifyingthecornersthatdefineit.Tozoominonanareabyspecifyingitsboundaries,useeithertheZoomWindoworZoomPickWindowmethod.TheZoomWindowmethodallowsyoutodefinetwopointsrepresentingtheZoomwindowprogrammatically.TheZoomPickWindowmethodrequirestheusertopicktwopoints.ThesetwopickedpointsbecometheZoomwindow.
Zoomtheactivedrawingtoawindowdefinedbytwopoints
SubCh3_ZoomWindow()
'ZoomWindow
MsgBox"PerformaZoomWindowwith:"&vbCrLf&_
"1.3,7.8,0"&vbCrLf&_
"13.7,-2.6,0",,"ZoomWindow"
Dimpoint1(0To2)AsDouble
Dimpoint2(0To2)AsDouble
point1(0)=1.3:point1(1)=7.8:point1(2)=0
point2(0)=13.7:point2(1)=-2.6:point2(2)=0
ThisDrawing.Application.ZoomWindowpoint1,point2
'ZoomPickWindow
MsgBox"PerformaZoomPickWindow",,"ZoomPickWindow"
ThisDrawing.Application.ZoomPickWindow
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>ControltheDrawingWindows>UseZoom>
ScaleaView
Ifyouneedtoincreaseordecreasethemagnificationoftheimagebyaprecisescale,youcanspecifyazoomscaleinthreeways:
Relativetothedrawinglimits
Relativetothecurrentview
Relativetopaperspaceunits
Toscaleaview,usetheZoomScaledmethod.Thismethodtakestwoparametersasinput:thescaleandthetypeofscale.Thescaleissimplyanumber.HowthatnumbergetsinterpretedbyAutoCADdependsonthetypeofscaleyouchoose.
Thetypeofscaledeterminesifthescalevalueiscreatedrelativetothedrawinglimits,thecurrentview,orthepaperspaceunits.Toscalerelativetothedrawinglimits,usetheconstantacZoomScaledAbsolute.Toscaletheviewrelativetothecurrentview,usetheconstantacZoomScaledRelative.Toscalerelativetopaperspaceunits,usetheconstantacZoomScaledRelativePSpace.
Zoominontheactivedrawingusingaspecifiedscale
SubCh3_ZoomScaled()
MsgBox"PerformaZoomScaledusing:"&vbCrLf&_
"ScaleType:acZoomScaledRelative"&vbCrLf&_
"ScaleFactor:2",,"ZoomScaled"
DimscalefactorAsDouble
DimscaletypeAsInteger
scalefactor=2
scaletype=acZoomScaledRelative
ThisDrawing.Application.ZoomScaledscalefactor,scaletype
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>ControltheDrawingWindows>UseZoom>
CenterObjects
ZoominontheactivedrawingtoaspecifiedcenterYoucanmoveaspecificpointinyourdrawingtothecenterofthegraphicsarea.TheZoomCentermethodisusefulforresizinganobjectandbringingittothecenteroftheviewport.WithZoomCenter,youcanspecifyascalesizebyenteringamagnificationrelativetothecurrentview.
Zoominontheactivedrawingtoaspecifiedcenter
ThefollowingexampleshowstheeffectsofusingZoomCentertodisplayaviewatthesamesizeandattwicethesize:
SubCh3_ZoomCenter()
MsgBox"PerformaZoomCenterusing:"&vbCrLf&_
"Center3,3,0"&vbCrLf&_
"Magnification:10",,"ZoomCenter"
DimCenter(0To2)AsDouble
DimmagnificationAsDouble
Center(0)=3:Center(1)=3:Center(2)=0
magnification=10
ThisDrawing.Application.ZoomCenterCenter,magnification
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>ControltheDrawingWindows>UseZoom>
DisplayDrawingLimitsandExtents
Todisplayaviewbasedonthedrawingboundariesortheextentsoftheobjectsinthedrawing,usetheZoomAll,ZoomExtents,orZoomPreviousmethod.
ZoomAlldisplaystheentiredrawing.Iftheobjectsextendbeyondthelimits,ZoomAlldisplaystheextentsoftheobjects.Iftheobjectsaredrawnwithinthelimits,ZoomAlldisplaysthelimits.
ZoomExtentscalculateszoomsbasedontheextentsoftheactiveviewport,notthecurrentview.Usuallytheactiveviewportisentirelyvisible,sotheresultsareobviousandintuitive.However,whenusingtheZoommethodsinmodelspacewhileworkinginapaperspaceviewport,ifyouarezoomedinbeyondthepaperspaceviewport'sborders,someoftheareazoomedmaynotbevisible.
ZoomExtentschangestheviewtoencompasstheentityextentsforthecurrentdrawing.Insomecases(forbothZoomAllandZoomExtents),thismaycausearegeneration.Regenerationwillnotoccuronlayersthatarefrozenorturnedoff.Ifyourdrawinghasnoobjects,ZoomExtentsdisplaysthedrawinglimits.
For3Dviews,ZoomAllandZoomExtentshavethesameeffect.Infiniteconstructionlines(xlines)andraysdonotaffecteitheroption.
ZoomPreviouszoomsthecurrentviewporttoitspreviousextents.
See“MagnifyaView(Zoom)”intheUser'sGuideforillustrationsofhowzoomingworks.
Zoominontheactivedrawingtoallcontentsandtothedrawingextents
SubCh3_ZoomAll()
'ZoomAll
MsgBox"PerformaZoomAll",,"ZoomAll"
ThisDrawing.Application.ZoomAll
'ZoomExtents
MsgBox"PerformaZoomExtents",,"ZoomExtents"
ThisDrawing.Application.ZoomExtents
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>ControltheDrawingWindows>
UseNamedViews
Youcannameandsaveaviewyouwanttoreuse.Whenyounolongerneedtheview,youcandeleteit.
Tocreateanewview,usetheAddmethodtoaddanewviewtotheViewscollection.Whenyousavethedrawing,theviewingpositionandscaleoftheviewaresaved.
Younametheviewwhenyoucreateit.Thenameoftheviewcanbeupto255characterslongandcontainletters,digits,andthespecialcharactersdollarsign($),hyphen(-),andunderscore(_).
Todeleteanamedview,simplyusetheDeletemethod.TheDeletemethodfortheViewobjectliesontheViewobject,notitsparent.
AddaViewobject
ThefollowingexampleaddsaViewobject(viewObj).
SubCh3_AddView()
'Addanamedviewtotheviewscollection
DimviewObjAsAcadView
SetviewObj=ThisDrawing.Views.Add("View1")
EndSub
DeleteaViewobject
ThefollowingexampledeletesaViewobject(viewObj).
SubCh3_DeleteView()
DimviewObjAsAcadView
SetviewObj=ThisDrawing.Views("View1")
'Deletetheview
viewObj.Delete
EndSub
DeleteanamedviewfromtheViewscollection
ThisexampledeletesanamedviewfromtheViewscollection.
SubCh3_DeleteViewFromCollection()
ThisDrawing.Views("View1").Delete
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>ControltheDrawingWindows>
UseTiledViewports
AutoCADusuallybeginsanewdrawingusingasingleviewportthatfillstheentiregraphicsarea.Youcansplitthedrawingareatodisplayseveralviewportssimultaneously.Forexample,ifyoukeepboththefullandthedetailviewsvisible,youcanseetheeffectsofyourdetailchangesontheentiredrawing.Ineachtiledviewport,youcandothefollowing:
Zoom,settheSnap,Grid,andUCSiconmodes,andrestorenamedviewsinindividualviewports
Drawfromoneviewporttoanotherwhenexecutingacommand
Nameaconfigurationofviewportssoyoucanreuseit
Youcandisplaytiledviewportsinvariousconfigurations.Howyoudisplaytheviewportsdependsonthenumberandsizeoftheviewsyouneedtosee.
Forfurtherinformationandillustrationsdescribingviewports,see“SetModelSpaceViewports”intheUser'sGuide.
Topicsinthissection
SplittheActiveViewportMakeAnotherTiledViewportCurrent
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>ControltheDrawingWindows>UseTiledViewports>
SplittheActiveViewport
Tosplittheactiveviewport,usetheSplitmethod.Thismethodtakesoneparameter,thetypeofconfigurationtosplittheviewportinto.Tospecifythewindowconfiguration,useoneofthefollowingconstantsthatcorrespondtothedefaultconfigurationspreviouslyshown:acViewport2Horizontal,acViewport2Vertical,acViewport3Left,acViewport3Right,acViewport3Horizontal,acViewport3Vertical,acViewport3Above,acViewport3Below,oracViewport4.
Forfurtherinformationonchangingviewportconfiguration,see“SetModelSpaceViewports”intheUser'sGuide.
Splitaviewportintotwohorizontalwindows
Thefollowingexamplecreatesanewviewportandthensplitstheviewportintotwohorizontalwindows.
SubCh3_SplitAViewport()
'Createanewviewport
DimvportObjAsAcadViewport
SetvportObj=ThisDrawing.Viewports.Add("TEST_VIEWPORT")
'SplitvportObjinto2horizontalwindows
vportObj.SplitacViewport2Horizontal
'NowsetvportObjtobetheactiveviewport
ThisDrawing.ActiveViewport=vportObj
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>ControltheDrawingWindows>UseTiledViewports>
MakeAnotherTiledViewportCurrent
Youenterpointsandselectobjectsinthecurrentviewport.Tomakeaviewportcurrent,usetheActiveViewportproperty.
Youcaniteratethroughexistingviewportstofindaparticularviewport.Todothis,firstidentifythenameoftheviewportconfigurationonwhichthedesiredviewportresidesusingtheNameproperty.Additionally,iftheviewportconfigurationhasbeensplit,eachindividualviewportontheconfigurationcanbeidentifiedthroughtheLowerLeftCornerandUpperRightCornerproperties.
TheLowerLeftCornerandUpperRightCornerpropertiesrepresentthegraphicplacementoftheviewportonthedisplay.Thesepropertiesaredefinedasfollows(usingafour-waysplitasanexample):
Inthisexample:
Viewport1-LowerLeftCorner=(0,.5),UpperRightCorner=(.5,1)
Viewport2-LowerLeftCorner=(.5,.5),UpperRightCorner=(1,1)
Viewport3-LowerLeftCorner=(0,0),UpperRightCorner=(.5,.5)
Viewport4-LowerLeftCorner=(.5,0),UpperRightCorner=(1,.5)
Splitaviewport,theniteratethroughthewindows
Thisexamplesplitsaviewportintofourwindows.Ittheniteratesthroughalltheviewportsinthedrawinganddisplaystheviewportnameandthelower-leftand
upper-rightcornerforeachviewport.
SubCh3_IteratingViewportWindows()
'Createanewviewportandmakeitactive
DimvportObjAsAcadViewport
SetvportObj=ThisDrawing.Viewports.Add("TEST_VIEWPORT")
ThisDrawing.ActiveViewport=vportObj
'Splitvportinto4windows
vportObj.SplitacViewport4
'Iteratethroughtheviewports,
'highlightingeachviewportanddisplaying
'theupperrightandlowerleftcorners
'foreach.
DimvportAsAcadViewport
DimLLCornerAsVariant
DimURCornerAsVariant
ForEachvportInThisDrawing.Viewports
ThisDrawing.ActiveViewport=vport
LLCorner=vport.LowerLeftCorner
URCorner=vport.UpperRightCorner
MsgBox"Viewport:"&vport.Name&"isnowactive."&_
vbCrLf&"Lowerleftcorner:"&_
LLCorner(0)&","&LLCorner(1)&vbCrLf&_
"Upperrightcorner:"&_
URCorner(0)&","&URCorner(1)
Nextvport
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>ControltheDrawingWindows>
UpdatetheGeometryintheDocumentWindow
ManyoftheactionsyouperformthroughAutoCADActiveXAutomationmodifywhatisdisplayedintheAutoCADdrawing.Notalloftheseactionsimmediatelyupdatethedisplayofthedrawing.Thisisdesignedsoyoucanmakeseveralchangestothedrawingwithoutwaitingforthedisplaytobeupdatedaftereverysingleaction.Instead,youcanbundleyouractionstogetherandmakeasinglecalltoupdatethedisplaywhenyouhavefinished.
ThemethodsthatwillupdatethedisplayareUpdateandRegen.
TheUpdatemethodupdatesthedisplayofasingleobjectonly.TheRegenmethodregeneratestheentiredrawingandrecomputesthescreencoordinatesandviewresolutionforallobjects.Italsoreindexesthedrawingdatabaseforoptimumdisplayandobjectselectionperformance.
Updatethedisplayofasingleobject
Thisexamplecreatesacircle.ItthenupdatesthecircleusingtheUpdatemethodsothecircleisvisibleinAutoCAD.
SubCh3_UpdateDisplay()
DimcircleObjAsAcadCircle
Dimcenter(0To2)AsDouble
DimradiusAsDouble
center(0)=1:center(1)=1:center(2)=0
radius=1
'Createthecircle
SetcircleObj=ThisDrawing.ModelSpace.AddCircle(center,radius)
'Updatethecircle
circleObj.Update
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>
ResetActiveObjects
Changestomostactiveobjects,suchastheactivelayerandactivelinetype,willappearimmediately.However,thereareseveralactiveobjectsthatmustberesetforchangestoappear.Theseobjectsaretheactivetextstyle,theactiveusercoordinatesystem(UCS),andtheactiveviewport.Ifchangesaremadetoanyoftheseobjects,theobjectmustbereset,andtheRegenmethodmustbecalledforthechangestoappear.
Toresettheseobjects,simplysettheActiveTextStyle,ActiveUCS,orActiveViewportproperty,usingtheupdatedobject.
Resettheactiveviewport
Thefollowingexamplechangesthedisplayofthegridintheactiveviewportandthenresetstheviewportastheactiveviewporttodisplaythechange.
SubCh3_ResetActiveViewport()
'Togglethesettingofthegriddisplay
'fortheactiveviewport
ThisDrawing.ActiveViewport.GridOn=_
Not(ThisDrawing.ActiveViewport.GridOn)
'Resettheactiveviewport
ThisDrawing.ActiveViewport=ThisDrawing.ActiveViewport
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>
SetandReturnSystemVariables
TheDocumentobjectprovidestheSetVariableandGetVariablemethodsforsettingandretrievingAutoCADsystemvariables.Forexample,toassignanintegertotheMAXSORTsystemvariable,usethefollowingcode:
ThisDrawing.SetVariable"MAXSORT",100
Pleasesendusyourcommentaboutthispage
<$nopage>methods.
ControltheAutoCADEnvironment>
DrawwithPrecision
WithAutoCADyoucancreateyourdrawingswithprecisegeometrywithoutperformingtediouscalculations.Oftenyoucanspecifyprecisepointswithoutknowingthecoordinates.Withoutleavingthedrawingscreen,youcanperformcalculationsonyourdrawinganddisplayvarioustypesofstatusinformation.
Atthistime,AutoCADActiveXAutomationdoesnotprovideamethodforthefollowingAutoCADcapabilities:
Settingobjectsnaps
Specifyingmeasuredintervalsonobjectsordividingobjectsintosegments
Topicsinthissection
AdjustSnapandGridAlignmentUseOrthoModeDrawConstructionLinesCalculatePointsandValuesCalculateAreas
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>DrawwithPrecision>
AdjustSnapandGridAlignment
YoucanusethegridasavisualguidelineandturnonSnapmodetorestrictcursormovement.Inadditiontosettingthespacing,youcanadjustthesnapandgridalignment.Youcanrotatethealignment,oryoucansetitforusewithisometricdrawings.
Ifyouneedtodrawalongaspecificalignmentorangle,youcanrotatethesnapangle.Thecenterpointofthesnapanglerotationisthesnapbasepoint.Ifyouneedtoalignahatchpattern,youcanchangethispoint,whichisnormallysetto0,0.
Torotatethesnapangle,usetheSnapRotationAngleproperty.Tochangethebasepointofthesnapanglerotation,usetheSnapBasePointproperty.
Note BothpropertiesrequireacalltotheUpdatemethodtoupdatetheAutoCADdisplay.
See“AdjustGridandGridSnap”intheUser'sGuideformoreinformationonusingandsettingsnapsandgrids.
Changethesnapbasepointandrotationangle
Thisexamplechangesthesnapbasepointto(1,1)andthesnaprotationangleto30degrees.Thegridisturnedonsothatthechangesarevisible.
SubCh3_ChangeSnapBasePoint()
'Turnonthegridfortheactiveviewport
ThisDrawing.ActiveViewport.GridOn=True
'Changethesnapbasepointto1,1
DimnewBasePoint(0To1)AsDouble
newBasePoint(0)=1:newBasePoint(1)=1
ThisDrawing.ActiveViewport.SnapBasePoint=newBasePoint
'Changethesnaprotationangleto30degrees(0.575radians)
DimrotationAngleAsDouble
rotationAngle=0.575
ThisDrawing.ActiveViewport.SnapRotationAngle=rotationAngle
'resettheviewport
ThisDrawing.ActiveViewport=ThisDrawing.ActiveViewport
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>DrawwithPrecision>
UseOrthoMode
Asyoudrawlinesormoveobjects,youcanuseOrthomodetorestrictthecursortothehorizontalorverticalaxis.(TheorthogonalalignmentdependsonthecurrentsnapangleortheUCS.)Orthomodeworkswithactivitiesthatrequireyoutospecifyasecondpoint.YoucanuseOrthonotonlytoestablishverticalorhorizontalalignmentbutalsotoenforceparallelismorcreateregularoffsets.
ByallowingAutoCADtoimposeorthogonalrestraints,youcandrawmorequickly.Forexample,youcancreateaseriesofperpendicularlinesbyturningonOrthomodebeforeyoustartdrawing.Becausethelinesareconstrainedtothehorizontalandverticalaxes,youcandrawfaster,knowingthatthelinesareperpendicular.
Asyoumovethecursor,arubber-bandlinethatdefinesthedisplacementfollowsthehorizontalorverticalaxis,dependingonwhichaxisisnearesttothecursor.AutoCADignoresOrthomodeinperspectiveviews,orwhenyouentercoordinatesonthecommandlineorspecifyanobjectsnap.
ToturnOrthomodeonoroff,usetheOrthoOnproperty.ThispropertyrequiresaBooleanforinput.SettoTRUEtoturnOrthomodeon,andtoFALSEtoturnOrthomodeoff.Forexample,thefollowingstatementturnsOrthomodeonfortheactiveviewport:
ThisDrawing.ActiveViewport.OrthoOn=True
Pleasesendusyourcommentaboutthispage
<$nopage>methods.
ControltheAutoCADEnvironment>DrawwithPrecision>
DrawConstructionLines
Youcancreateconstructionlinesthatextendtoinfinityinoneorbothdirections.Constructionlinesthatextendinonedirectionareknownasrays.Constructionlinesthatextendinbothdirectionsareknownasxlines.Theseconstructionlinescanbeusedasareferenceforcreatingotherobjects.Forexample,youcanuseconstructionlinestofindthecenterofatriangle,preparemultipleviewsofthesameitem,orcreatetemporaryintersectionsthatyoucanuseforobjectsnaps.
Topicsinthissection
CreateConstructionXLinesQueryConstructionXLinesCreateRaysQueryRays
Pleasesendusyourcommentaboutthispage
<$nopage>methods.
ControltheAutoCADEnvironment>DrawwithPrecision>DrawConstructionLines>
CreateConstructionXLines
Aconstructionxlinecanbeplacedanywherein3Dspaceandextendstoinfinityinbothdirections.Tocreateanxline,usetheAddXLinemethod.Thismethodspecifiesthelinebythetwo-pointmethod;youenterorselecttwopointstodefinetheorientation.Thefirstpoint,theroot,isconsideredthemidpointoftheconstructionline.
Addaconstructionline
ThefollowingexamplecodecreatesanXLineobjectusingthetwopoints(5,0,0)and(1,1,0).
SubCh3_AddXLine()
DimxlineObjAsAcadXline
DimbasePoint(0To2)AsDouble
DimdirectionVec(0To2)AsDouble
'Definethexline
basePoint(0)=2#:basePoint(1)=2#:basePoint(2)=0#
directionVec(0)=1#:directionVec(1)=1#:directionVec(2)=0#
'Createthexlineinmodelspace
SetxlineObj=ThisDrawing.ModelSpace.AddXLine_
(basePoint,directionVec)
ThisDrawing.Application.ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>DrawwithPrecision>DrawConstructionLines>
QueryConstructionXLines
Oncecreated,youcanquerythefirstpointofaconstuctionxlineusingtheBasePointproperty.Thesecondpointusedtocreatethexlineisnotstoredwiththeobject.Instead,usetheDirectionVectorpropertytoobtainthedirectionalvectorforthexline.
Queryaconstructionline
ThisexamplefindsthebasepointanddirectionalvectorforthexlinecreatedinAddaconstructionline
DimBPointAsVariant
DimVectorAsVariant
BPoint=xlineObj.basePoint
Vector=xlineObj.DirectionVector
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>DrawwithPrecision>DrawConstructionLines>
CreateRays
Arayisalinein3Dspacethatstartsatapointyouspecifyandextendstoinfinity.Unlikexlineconstructionlines,whichextendintwodirections,raysextendinonlyonedirection.Asaresult,rayshelpreducethevisualcluttercausedbynumerousconstructionlines.
Likeconstructionlines,raysareignoredbycommandsthatdisplaythedrawingextents.
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>DrawwithPrecision>DrawConstructionLines>
QueryRays
Oncecreated,youcanquerythefirstpointofarayusingtheBasePointproperty.Thesecondpointusedtocreatetherayisnotstoredwiththeobject.Instead,usetheDirectionVectorpropertytoobtainthedirectionalvectorfortheray.
Add,query,andeditaRayobject
ThefollowingexamplecodecreatesaRayobjectusingthetwopoints(5,0,0)and(1,1,0).Itthenqueriesthecurrentbasepointanddirectionvectoranddisplaystheresultsinamessagebox.Thedirectionvectoristhenchangedandthebasepointandnewdirectionvectorarequeriedanddisplayed.
SubCh3_EditRay()
DimrayObjAsAcadRay
DimbasePoint(0To2)AsDouble
DimsecondPoint(0To2)AsDouble
'Definetheray
basePoint(0)=3#:basePoint(1)=3#:basePoint(2)=0#
secondPoint(0)=4#:secondPoint(1)=4#:secondPoint(2)=0#
'CreatesaRayobjectinmodelspace
SetrayObj=ThisDrawing.ModelSpace.AddRay_
(basePoint,secondPoint)
ThisDrawing.Application.ZoomAll
'FindthecurrentstatusoftheRay
MsgBox"Thebasepointoftherayis:"&_
rayObj.basePoint(0)&","&_
rayObj.basePoint(1)&","&_
rayObj.basePoint(2)&vbCrLf&_
"Thedirectionalvectorfortherayis:"&_
rayObj.DirectionVector(0)&","&_
rayObj.DirectionVector(1)&","&_
rayObj.DirectionVector(2),,"EditRay"
'Changethedirectionalvectorfortheray
DimnewVector(0To2)AsDouble
newVector(0)=-1
newVector(1)=1
newVector(2)=0
rayObj.DirectionVector=newVector
ThisDrawing.RegenFalse
MsgBox"Thebasepointoftherayis:"&_
rayObj.basePoint(0)&","&_
rayObj.basePoint(1)&","&_
rayObj.basePoint(2)&vbCrLf&_
"Thedirectionalvectorfortherayis:"&_
rayObj.DirectionVector(0)&","&_
rayObj.DirectionVector(1)&","&_
rayObj.DirectionVector(2),,"EditRay"
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>DrawwithPrecision>
CalculatePointsandValues
ByusingthemethodsprovidedbytheUtilityobject,youcanquicklysolveamathematicalproblemorlocatepointsonyourdrawing.ByusingmethodsontheUtilityobject,youcandothefollowing:
FindtheangleofalinefromtheXaxiswiththeAngleFromXAxismethod
Convertanangleasastringtoareal(double)valuewiththeAngleToRealmethod
Convertananglefromareal(double)valuetoastringwiththeAngleToStringmethod
Convertadistancefromastringtoareal(double)valuewiththeDistanceToRealmethod
Createavariantthatcontainsanarrayofintegers,floatingnumbers,doubles,andsoforth,withtheCreateTypedArraymethod
FindthepointataspecifiedangleanddistancefromagivenpointwiththePolarPointmethod
TranslateapointfromonecoordinatesystemtoanothercoordinatesystemwiththeTranslateCoordinatesmethod
FindthedistancebetweentwopointsenteredbytheuserwiththeGetDistancemethod
FindthedistancebetweentwopointswiththeGetDistancemethod
ThisexampleusestheGetDistancemethodtoobtainthepointcoordinates,andtheMsgBoxfunctiontodisplaythecalculateddistance.
SubCh3_GetDistanceBetweenTwoPoints()
DimreturnDistAsDouble
'Returnthevalueenteredbyuser.Apromptisprovided.
returnDist=ThisDrawing.Utility.GetDistance_
(,"Picktwopoints.")
MsgBox"Thedistancebetweenthetwopointsis:"&returnDist
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>DrawwithPrecision>
CalculateAreas
CalculatetheareadefinedbypointsenteredfromtheuserYoucanfindtheareaofanarc,circle,ellipse,lightweightpolyline,polyline,region,orplanar-closedsplinebyusingtheAreaproperty.
Ifyouneedtocalculatethecombinedareaofmorethanoneobject,youcankeeparunningtotalasyouaddorusetheBooleanmethodonaseriesofregionstoobtainasingleregionrepresentingthedesiredarea.FromthissingleregionyoucanusetheAreapropertytoobtainitsarea.
Thecalculatedareadiffersaccordingtothetypeofobjectyouquery.Foranexplanationofhowareaiscalculatedforeachobjecttype,see“ObtainAreaInformation”intheUser'sGuide.
Topicsinthissection
CalculateaDefinedArea
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>DrawwithPrecision>CalculateAreas>
CalculateaDefinedArea
CalculatetheareadefinedbypointsenteredfromtheuserToobtaintheareaspecifiedbypointsfromtheuserYoucanmeasureanarbitraryclosedregiondefinedbythe2Dor3Dpointsspecifiedbytheuser.Thepointsmustbecoplanar.
Toobtaintheareaspecifiedbypointsfromtheuser
1. UsetheGetPointmethodinalooptoobtainthepointsfromtheuser.
2. Createalightweightpolylinefromthepointsprovidedbytheuser.UsetheAddLightweightPolylinemethodtocreatethepolyline.
3. UsetheAreapropertytoobtaintheareaofthenewlycreatedpolyline.
4. ErasethepolylineusingtheErasemethod.
Calculatetheareadefinedbypointsenteredfromtheuser
Thisexamplepromptstheusertoenterfivepoints.Apolylineisthencreatedoutofthepointsentered.Thepolylineisclosed,andtheareaofthepolylineisdisplayedinamessagebox.
SubCh3_CalculateDefinedArea()
Dimp1AsVariant
Dimp2AsVariant
Dimp3AsVariant
Dimp4AsVariant
Dimp5AsVariant
'Getthepointsfromtheuser
p1=ThisDrawing.Utility.GetPoint(,vbCrLf&"Firstpoint:")
p2=ThisDrawing.Utility.GetPoint(p1,vbCrLf&"Secondpoint:")
p3=ThisDrawing.Utility.GetPoint(p2,vbCrLf&"Thirdpoint:")
p4=ThisDrawing.Utility.GetPoint(p3,vbCrLf&"Fourthpoint:")
p5=ThisDrawing.Utility.GetPoint(p4,vbCrLf&"Fifthpoint:")
'Createthe2Dpolylinefromthepoints
DimpolyObjAsAcadLWPolyline
Dimvertices(0To9)AsDouble
vertices(0)=p1(0):vertices(1)=p1(1)
vertices(2)=p2(0):vertices(3)=p2(1)
vertices(4)=p3(0):vertices(5)=p3(1)
vertices(6)=p4(0):vertices(7)=p4(1)
vertices(8)=p5(0):vertices(9)=p5(1)
SetpolyObj=ThisDrawing.ModelSpace.AddLightWeightPolyline_
(vertices)
polyObj.Closed=True
ThisDrawing.Application.ZoomAll
'Displaytheareaforthepolyline
MsgBox"Theareadefinedbythepointsis"&_
polyObj.Area,,"CalculateDefinedArea"
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>
PromptforUserInput
TheUtilityobject,whichisachildoftheDocumentobject,definestheuserinputmethods.TheuserinputmethodsdisplayapromptontheAutoCADcommandlineandrequestinputofvarioustypes.Thistypeofuserinputismostusefulforinteractiveinputofscreencoordinates,entityselection,andshort-stringornumericvalues.Ifyourapplicationrequirestheinputofnumerousoptionsorvalues,adialogboxmaybemoreappropriatethanindividualprompts.
EachuserinputmethoddisplaysapromptontheAutoCADcommandlineandreturnsavaluespecifictothetypeofinputrequested.Forexample,GetStringreturnsastring,GetPointreturnsavariant(whichcontainsathree-elementarrayofdoubles),andGetIntegerreturnsanintegervalue.YoucanfurthercontroltheinputfromtheuserwiththeInitializeUserInputmethod.ThismethodletsyoucontrolthingssuchasNULLinput(pressingENTER),inputofzeroornegativenumbers,andinputofarbitrarytextvalues.
Toforcetheprompttobedisplayedonalinebyitself,usethecarriagereturn/linefeedconstant(vbCrLf)atthebeginningofyourpromptstrings.
Topicsinthissection
GetStringMethodGetPointMethodGetKeywordMethodControlUserInput
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>PromptforUserInput>
GetStringMethod
TheGetStringmethodpromptstheuserforinputofastringattheAutoCADCommandprompt.Thismethodacceptstwoparameters.Thefirstparametercontrolstheinputofspacesintheinputstring.Ifitissetto0,spacesarenotallowed(SPACEBARterminatestheinput);ifsetto1,thestringcancontainspaces(ENTERmustbeusedtoterminatetheinput).Thesecondparameteristhepromptstring.
GetastringvaluefromtheuserattheAutoCADcommandline
ThefollowingexampledisplaystheEnterYourNameprompt,andrequiresthattheinputfromtheuserbeterminatedbypressingENTER(spacesareallowedintheinputstring).ThestringvalueisstoredintheretValvariableandisdisplayedusingamessagebox.
SubCh3_GetStringFromUser()
DimretValAsString
retVal=ThisDrawing.Utility.GetString_
(1,vbCrLf&"Enteryourname:")
MsgBox"Thenameenteredwas:"&retVal
EndSub
TheGetStringmethoddoesnothonorapriorcalltotheInitializeUserInputmethod.
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>PromptforUserInput>
GetPointMethod
TheGetPointmethodpromptstheuserforthespecificationofapointattheAutoCADCommandprompt.Thismethodacceptstwoparameters,anoptionalfrompointandthepromptstring.Ifthefrompointisprovided,AutoCADdrawsarubber-bandlinefromthatpoint.Tocontroltheuserinput,thismethodcanbeprecededbyacalltotheInitializeUserInputmethod.
Getapointselectedbytheuser
Thefollowingexamplepromptstheuserfortwopoints,thendrawsalineusingthosepointsasthestartpointandendpoint.
SubCh3_GetPointsFromUser()
DimstartPntAsVariant
DimendPntAsVariant
Dimprompt1AsString
Dimprompt2AsString
prompt1=vbCrLf&"Enterthestartpointoftheline:"
prompt2=vbCrLf&"Entertheendpointoftheline:"
'Getthefirstpointwithoutenteringabasepoint
startPnt=ThisDrawing.Utility.GetPoint(,prompt1)
'Usethepointenteredaboveasthebasepoint
endPnt=ThisDrawing.Utility.GetPoint(startPnt,prompt2)
'Createalineusingthetwopointsentered
ThisDrawing.ModelSpace.AddLinestartPnt,endPnt
ThisDrawing.Application.ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>PromptforUserInput>
GetKeywordMethod
TheGetKeywordmethodpromptstheuserforinputofakeywordattheAutoCADCommandprompt.Thismethodacceptsonlyoneparameter,whichisthepromptstring.ThekeywordsandinputparametersaredefinedwithacalltotheInitializeUserInputmethod.
GetakeywordfromtheuserattheAutoCADcommandline
ThefollowingexampleforcestheusertoenterakeywordbysettingthefirstparameterofInitializeUserInputto1,whichdisallowsNULLinput(pressingENTER).Thesecondparameterestablishesthelistofvalidkeywords.
SubCh3_KeyWord()
DimkeyWordAsString
ThisDrawing.Utility.InitializeUserInput1,"LineCircleArc"
keyWord=ThisDrawing.Utility.GetKeyword_
(vbCrLf&"Enteranoption(Line/Circle/Arc):")
MsgBoxkeyWord,,"GetKeywordExample"
EndSub
Amoreuser-friendlykeywordpromptisonethatprovidesadefaultvalueiftheuserpressesENTER(NULLinput).Noticetheminormodificationstothefollowingexample:
SubCh3_KeyWord2()
DimkeyWordAsString
ThisDrawing.Utility.InitializeUserInput0,"LineCircleArc"
keyWord=ThisDrawing.Utility.GetKeyword_
(vbCrLf&"Enteranoption(Line/Circle/<Arc>):")
IfkeyWord=""ThenkeyWord="Arc"
MsgBoxkeyWord,,"GetKeywordExample"
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>PromptforUserInput>
ControlUserInput
YoucanusetheInitializeUserInputmethodtodefinekeywordsorrestrictthetypeofinputtotheuserinputmethod.TheuseandparametervaluesaresimilartotheAutoLISPinitgetfunction.InitializeUserInputcanbeusedwiththefollowingmethods:GetAngle,GetCorner,GetDistance,GetInteger,GetKeyword,GetOrientation,GetPoint,andGetReal.InitializeUserInputcannotbeusedwiththeGetStringmethod.UsetheGetInputmethodtoretrievethestringvalue(keywordorarbitraryinput)whentheuserinputmethoddoesnotreturnastringvalue.
TheInitializeUserInputmethodacceptstwoparameters.Thefirstparameterisabit-codedintegervaluethatdeterminestheinputoptionsfortheuserinputmethod.Thesecondparameterisastringthatdefinesthevalidkeywords.
GetanintegervalueorakeywordfromtheuserattheAutoCADcommandline
Thefollowingexamplepromptstheuserforapositive,non-negativeintegervalueorakeyword:
SubCh3_UserInput()
'ThefirstparameterofInitializeUserInput(6)
'restrictsinputtopositiveandnon-negative
'values.Thesecondparameteristhelistof
'validkeywords.
ThisDrawing.Utility.InitializeUserInput6,"BigSmallRegular"
'Setthepromptstringvariable
DimpromptStrAsString
promptStr=vbCrLf&"Enterthesizeor(Big/Small/<Regular>):"
'AttheGetIntegerprompt,enteringakeywordorpressing
'ENTERwithoutenteringavalueresultsinanerror.Toallow
'yourapplicationtocontinueandcheckfortheerror
'description,youmustsettheerrorhandlertoresumeonerror.
OnErrorResumeNext
'Getthevalueenteredbytheuser
DimreturnIntegerAsInteger
returnInteger=ThisDrawing.Utility.GetInteger(promptStr)
'Checkforanerror.Iftheerrornumbermatchesthe
'oneshownbelow,thenuseGetInputtogetthereturned
'string;otherwise,usethevalueofreturnInteger.
IfErr.Number=-2145320928Then
DimreturnStringAsString
Debug.PrintErr.Description
returnString=ThisDrawing.Utility.GetInput()
IfreturnString=""Then'ENTERreturnsnullstring
returnString="Regular"'Settodefault
EndIf
Err.Clear
Else'Otherwise,
returnString=returnInteger'Usethevalueentered
EndIf
'Displaytheresult
MsgBoxreturnString,,"InitializeUserInputExample"
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>
AccesstheAutoCADCommandLine
YoucansendcommandsdirectlytotheAutoCADcommandlinebyusingtheSendCommandmethod.TheSendCommandmethodsendsasinglestringtothecommandline.Thestringmustcontaintheargumentstothecommandlistedintheorderexpectedbythepromptsequenceoftheexecutedcommand.AblankspaceortheASCIIequivalentofacarriagereturninthestringisequivalenttopressingENTERonthekeyboard.UnliketheAutoLISPenvironment,invokingtheSendCommandmethodwithnoargumentisinvalid.
SendacommandtotheAutoCADcommandline
Thefollowingexamplecreatesacirclewithacenterof(2,2,0)andaradiusof4.Thedrawingisthenzoomedtoallthegeometryinthedrawing.NoticethatthereisaspaceattheendofthestringwhichrepresentsthefinalENTERtobeginexecutionofthecommand.
SubCh3_SendACommandToAutoCAD()
ThisDrawing.SendCommand"_Circle2,2,04"
ThisDrawing.SendCommand"_zooma"
EndSub
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>
WorkwithNoDocumentsOpen
AutoCADalwaysstartsupwithaneworexistingdocumentopen.Itispossible,however,toclosealldocumentsduringthecurrentsession.
IfyoucloseallthedocumentsintheAutoCADuserinterface,youwillnoticeafewchangestotheapplicationwindow.TheavailablemenusarereducedtosimplytheFile,View,Window,andHelpmenus.Thesemenusalsohavereducedavailableoptionsonthem.Youwillalsonoticethatthereisnocommandline.
Similarly,theActiveXinterfaceonlyallowsthefollowingactionswhennodocumentsareopen:
Youcanopenadocument.
Youcancreateanewdocument.
Youcanimportadocument.
YoucanexitoutofAutoCAD.
TheseactionsareallavailablefromtheDocumentscollection.ThemethodsandpropertiesoftheDocumentscollection,inadditiontoalimitedsetofmethodsandpropertiesoftheApplicationobject,aretheonlyvalidinterfaceavailablewhentherearenodocumentsopen.Ifyouperformanyotheraction,suchasattemptingtoaccessuseroptions,youractionswillresultinanerror.
UsetheCountpropertyontheDocumentscollectiontodetermineifAutoCADisinazerodocumentstate.IfDocuments.Count=0,thenAutoCADisinazerodocumentstate.IfDocuments.Count>0,thenthereisatleastonedrawingopen.
ItisalsoimportanttonotethatinVBAtheThisDrawingobjectisnotdefinedwhenAutoCADisinazerodocumentstate.ThismakessensesinceThisDrawingnormallyreferstotheactivedrawingandinthezerodocument
statetherearenodrawingsopen.AttemptingtoexecuteamacrothatusesThisDrawingwillresultinaruntimeerror.Toavoidtheerror,usetheVBAGetObjectfunction,andspecifytheAutoCADversion,toobtainaconnectiontoAutoCADwhentherearenodocumentsopen.
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>
ImportOtherFileFormats
Youcanusedrawingsorimagesfromotherapplicationsbyopeningtheminspecificformats.AutoCADhandlessomeformofconversionfordrawinginterchangeformat(DXF)TM,SAT,andWMFfiles.Forallversions,youcanimportthefilebyusingtheImportmethod.Thismethodtakesthreevaluesasinput:thenameofthefiletoimport,theinsertionpointinthedrawingtoplacethefile,andthescalefactortousewhenplacingtheimporteddrawing.
Pleasesendusyourcommentaboutthispage
ControltheAutoCADEnvironment>
ExporttoOtherFileFormats
IfyouneedtouseanAutoCADdrawinginanotherapplication,youcanconvertittoaspecificformatbyusingtheExportmethod.ThismethodexportstheAutoCADdrawingtoaWMF,SAT,EPS,DXF,orBMPformat.TheExportmethodtakesthreevaluesasinput:thenameforthenewfiletobecreated,theextensionforthenewfile,andtheselectionsetofobjectstoexport.
WhenexportingtoWMF,SAT,orBMPformat,youmustprovideanonemptyselectionset.Thisselectionsetspecifiestheobjectsfromthedrawingtoexport.Ifnoselectionsetisspecified,nothingisexportedandatrappableinvalidargumenterrorresults.
WhenexportingtoEPSandDXFformats,Exportignorestheselectionsetargument,butitisstillrequired.Theentiredrawingisautomaticallyexportedfortheseformats.
ExportadrawingasaDXFfileandimportitagain
Thisexamplecreatesacircleinthecurrentdrawing.ItthenexportsthedrawingtoafilecalledDXFExprt.DXF,opensanewdrawing,andimportsthefile.NotethatanemptyselectionsetisprovidedasanargumenttoExport.TheExportmethodignoresselectionsetinformationwhenexportingaDXFfile,butasyntaxerrorresultsiftheargumentisomitted.
SubCh3_ImportingAndExporting()
'Createthecircleforvisualrepresentation
DimcircleObjAsAcadCircle
DimcenterPt(0To2)AsDouble
DimradiusAsDouble
centerPt(0)=2:centerPt(1)=2:centerPt(2)=0
radius=1
SetcircleObj=ThisDrawing.ModelSpace.AddCircle_
(centerPt,radius)
ThisDrawing.Application.ZoomAll
'Createanemptyselectionset
DimssetAsAcadSelectionSet
Setsset=ThisDrawing.SelectionSets.Add("NEWSSET")
'ExportthecurrentdrawingtoaDXFfileinthe
'AutoCADtemporaryfiledirectory
DimtempPathAsString
DimexportFileAsString
ConstdxfnameAsString="DXFExprt"
tempPath=_
ThisDrawing.Application.preferences.Files.TempFilePath
exportFile=tempPath&dxfname
ThisDrawing.ExportexportFile,"DXF",sset
'Deletetheemptyselectionset
ThisDrawing.SelectionSets.Item("NEWSSET").Delete
'Openanewdrawing
ThisDrawing.Application.Documents.Add"acad.dwt"
'Definetheimport
DimimportFileAsString
DiminsertPoint(0To2)AsDouble
DimscalefactorAsDouble
importFile=tempPath&dxfname&".dxf"
insertPoint(0)=0:insertPoint(1)=0:insertPoint(2)=0
scalefactor=2#
'Importthefile
ThisDrawing.ImportimportFile,insertPoint,scalefactor
ThisDrawing.Application.ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
<$nopage>solid-filledareas:<$startrange>selectionsets:filterlists,<$startrange>filterlists,<$startrange>filtering:selectionsets,DXFcodes,andfiltertypes(table),filtertypes,andDXFcodes(table),<$startrange>filterlists:examplecode,SelectionSetobject:examplecode,filtering:examplecode,<$endrange>selectionsets:filterlists,<$endrange>filterlists,<$endrange>filtering:selectionsets,<$endrange>filterlists:examplecode,selectionsets:removingobjects,objects:removingfromselectionsets,RemoveItemsmethod:inselectionsets,Clearmethod:inselectionsets,Erasemethod:inselectionsets,Deletemethod:inselectionsets,objects:existing,modifying,Updatemethod:redrawingobjects,2Dobjects:editing,editing:2Dobjects,nongraphicalobjects,editing,editing:nongraphicalobjects,namedobjects:specifying,objects:named,specifying,namedobjects:purging,purging,namedobjects,PurgeAllmethod:examplecode,namedobjects:renaming,namedobjects:characterlength,Nameproperty:examplecode,Addmethod:layers,examplecode,Layerobject:examplecode,copying:offsetting,copying:mirroring,copying:arraying,offsetting,objects,mirroring:objects,arraying,patterns,Copymethod,copying:singleobject,CopyObjectsmethod,copying:multipleobjects,copying:fromonedrawingtoanother,copying:objectstootherdrawings,CopyObjectsmethod:examplecode,Circleobject:examplecode,CopyObjectsmethod:examplecode,copying:fromonedrawingtoanother,copying:objectstootherdrawings,objects:offsetting,Offsetmethod,AddLightweightPolylinemethod:examplecode,LightweightPolylineobject:examplecode,Offsetmethod:examplecode,Offsetmethod:examplecode,Mirrormethod,mirroring:withtwocoordinates,Mirrormethod:illustration,Erasemethod,MIRRTEXTsystemvariable,Textobject:mirroringtext,mirroring:Textobjects,mirroring:examplecode,LightweightPolylineobject:examplecode,Mirrormethod:examplecode,arrays:polararrays,arrays:rectangulararrays,ArrayPolarmethod:creatingarrays,polararrays:creating,polararrays:centerpoint,specifying,polararrays:referencepoints,referencepoints,inpolararrays,polararrays:examplecode,ArrayRectangularmethod,arrays:rectangular,rectangulararrays,snaprotationangle:rectangulararrays,rectangulararrays:snaprotationangle,SnapRotationAngleproperty,rectangulararrays:examplecode,vectors:movingobjects,objects:movingalongavector,Movemethod:vectors,displacementvector,Moveobject:illustration,Moveobject:examplecode,rotatingobjects:illustration,basepoint,rotatingobjects,Rotatemethod,rotatingobjects,Rotatemethod:examplecode,Deletemethod:collections,scaling:objects,objects:scaling,ScaleEntitymethod,scalefactor:objectdimensions,objects:scalefactor,scalefactor:illustration,ScaleEntitymethod:examplecode,
TransformBymethod,objects:transforming,<$nopage>matrix:<$nopage>layerproperties,saving.<$endrange>layersettings:storing,layersettings:saving:examplecode,layersettings:renamingsavedsettings:examplecode,layersettings:deletingsavedsettings:examplecode,layersettings:restoringsavedsettings,layersettings:restoringsavedsettings:examplecode,layersettings:exportingsavedsettings,layersettings:importingsavedsettings,Exportmethod:forsavedlayersettings,Importmethod:forsavedlayersettings,layersettings:exportingsavedsettings:examplecode,layersettings:importingsavedsettings:examplecode,Textobject:usedindrawings,Textobject:linetext,Textobject:mtext,mtext:indrawings,drawings:textstyles,textstyles:properties(table),textstyles:current,textstyles:default,textstyles:creating,Addmethod:textstyles,TextStylescollection,TextStyleobject,TextStyleobject:properties(list),FontFileproperty,BigFontFileproperty:TextStyleobject,Heightproperty,Widthproperty,ObliqueAngleproperty,TextGenerationFlagproperty,textstyles:changingproperties,Regenmethod:fortextstyles,Updatemethod:fortextstyles,fonts:assigningindrawings,TextGenerationFlagproperty,GetFontmethod:examplecode,SetFontmethod:examplecode,fonts:TrueType,fonts:SHXfonts,fonts:exportingindrawings,fonts:TEXTFILLsystemvariable,TrueTypefonts,SHXfonts,TEXTFILLsystemvariable,fonts:Unicode,Unicodefonts,fonts:BigFontfiles,BigFontfiles,FontFileproperty,BigFontFileproperty:examplecode,FontFileproperty:examplecode,TextStyleobject:examplecode,Textobject:heightsettings,TrueTypefonts:heightsettings,Heightproperty,Heightproperty:examplecode,Textobject:examplecode,AddTextmethod:examplecode,Textobject:angles,setting,rotationangles,obliquingangles,intext:illustration,ObliqueAngleproperty,Textobject:ObliqueAngleproperty,TextGenerationFlagproperty:examplecode,Textobject:textgenerationflag,Textobject:displayingbackward,Textobject:displayingupsidedown,TextGenerationFlagproperty,TextGenerationFlagproperty:examplecode,Textobject:examplecode,Textobject:linetext,creating,Textobject:formatting,StyleNameproperty,Textobject:properties(list),Alignmentproperty,InsertionPointproperty,ObliqueAngleproperty,Rotationproperty,ScaleFactorproperty,TextAlignmentPointproperty,TextGenerationFlagproperty,TextStringproperty,Updatemethod:Textobject,Alignmentproperty:intext,Textobject:aligningindrawings(illustration),Textobject:examplecode,SetVariablemethod:examplecode,Alignmentproperty:examplecode,TextAlignmentPointproperty:examplecode,Textobject:modifying,MIRRTEXTsystemvariable,Textobject:methods(list),ArrayPolarmethod:Textobject,ArrayRectangularmethod:Textobject,Copymethod,Erasemethod,Mirrormethod,Movemethod,Rotatemethod,
mtext:usesfor,mtext:modifying,<$nopage>multilinetext.
CreateandEditAutoCADEntities
Youcancreatearangeofobjects,fromsimplelinesandcirclestosplinecurves,ellipses,andassociativehatchareas.Ingeneral,youaddobjectstomodelspaceusingoneoftheAddmethods.Youcanalsocreateobjectsinpaperspace,orinablock.
Onceanobjectiscreated,youcanchangethelayer,color,andlinetypeoftheobject.Youcanalsoaddtexttoannotateyourdrawing.
Topicsinthissection
CreateObjectsWorkwithSelectionSetsEditObjectsUseLayers,Colors,andLinetypesSaveandRestoreLayerSettingsAddTexttoDrawings
Pleasesendusyourcommentaboutthispage
<$nopage>solid-filledareas:
CreateandEditAutoCADEntities>
CreateObjects
WhilethereareoftenseveraldifferentwaystocreatethesamegraphicalobjectinAutoCAD®,ActiveXAutomationoffersonlyonecreationmethodperobject.Forexample,inAutoCADtherearefourdifferentwaysyoucancreateacircle:(1)byspecifyingthecenterandradius,(2)bytwopointsdefiningthediameter,(3)bythreepointsdefiningthecircumference,or(4)bytwotangentsandaradius.However,inActiveXAutomationthereisonlyonecreationmethodprovidedtocreateacircle,andthatmethodusesthecenterandradius.
Note TheVBandVBAmethodsofcreatingobjectsusingeitherCreateObjectorDimwiththeNewkeywordcanonlybeusedtocreatetheAutoCADApplicationobject.AllotherAutoCADobjectsmustbecreatedusingtheAddorAdd<objectname>methodprovidedintheAutoCADinterface.
Topicsinthissection
DeterminetheContainerObjectCreateLinesCreateCurvedObjectsCreatePointObjectsCreateSolid-FilledAreasWorkwithRegionsCreateHatches
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>CreateObjects>
DeterminetheContainerObject
GraphicalobjectsarecreatedineithertheModelSpacecollection,thePaperSpacecollection,oraBlockobject.
TheModelSpacecollectionisreturnedbytheModelSpacepropertyandthePaperSpacecollectionbythePaperSpaceproperty.
Youcanreferencetheseobjectsdirectly,orthroughauser-definedvariable.Toreferencetheobjectsdirectly,includetheobjectinthecallinghierarchy.Forexample,thefollowingstatementaddsalinetothemodelspace:
SetlineObj=ThisDrawing.ModelSpace.AddLine(startPoint,endPoint)
Toreferencetheobjectsthroughauser-definedvariable,definethevariableastypeAcadModelSpaceorAcadPaperSpace,andthensetthevariabletotheappropriatepropertyoftheactivedocument.Thefollowingexampledefinestwovariablesandsetsthemequaltothecurrentmodelspaceandpaperspace,respectively:
DimmoSpaceAsAcadModelSpace
DimpaSpaceAsAcadPaperSpace
SetmoSpace=ThisDrawing.ModelSpace
SetpaSpace=ThisDrawing.PaperSpace
Thefollowingstatementaddsalinetothemodelspaceusingtheuser-definedvariable:
SetlineObj=moSpace.AddLine(startPoint,endPoint)
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>CreateObjects>
CreateLines
ThelineisthemostbasicobjectinAutoCAD.Youcancreateavarietyoflines—singlelines,andmultiplelinesegmentswithandwithoutarcs.Ingeneral,youdrawlinesbyspecifyingcoordinatepoints.ThedefaultlinetypeisCONTINUOUS,anunbrokenline,butvariouslinetypesareavailablethatusedotsanddashes.
Tocreatealine,useoneofthefollowingmethods:
AddLine
Createsalinepassingthroughtwopoints.
AddLightweightPolyline
Createsa2Dlightweightpolylinefromalistofvertices.
AddMLine
Createsamultiline.
AddPolyline
Createsa2Dor3Dpolyline.
StandardlinesandmultilinesarecreatedontheXYplaneoftheworldcoordinatesystem.PolylinesandLightweightPolylinesarecreatedintheobjectcoordinatesystem(OCS).ForinformationaboutconvertingOCScoordinates,seeConvertCoordinates.
CreateaPolylineobject
ThisexampleusestheAddLightweightPolylinemethodtocreateasimpletwo-segmentpolylineusingthe2Dcoordinates(2,4),(4,2),and(6,4).
SubCh4_AddLightWeightPolyline()
DimplineObjAsAcadLWPolyline
Dimpoints(0To5)AsDouble
'Definethe2Dpolylinepoints
points(0)=2:points(1)=4
points(2)=4:points(3)=2
points(4)=6:points(5)=4
'CreatealightweightPolylineobjectinmodelspace
SetplineObj=ThisDrawing.ModelSpace._
AddLightWeightPolyline(points)
ThisDrawing.Application.ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>CreateObjects>
CreateCurvedObjects
YoucancreateavarietyofcurvedobjectswithAutoCAD,includingsplinecurves,circles,arcs,andellipses.AllcurvesarecreatedontheXYplaneofthecurrentWCS.
Tocreateacurve,useoneofthefollowingmethods:
AddArc
Createsanarcgiventhecenter,radius,startandendangles.
AddCircle
Createsacirclegiventhecenterpointandradius.
AddEllipse
Createsanellipsegiventhecenterpoint,apointonthemajoraxis,andtheradiusratio.
AddSpline
CreatesaquadraticorcubicNURBS(nonuniformrationalB-spline)curve.
CreateaSplineobject
Thisexamplecreatesasplineinmodelspaceusingthreepoints(0,0,0),(5,5,0),and(10,0,0).Thesplinehasstartandendtangentsof(0.5,0.5,0.0).
SubCh4_CreateSpline()
'Thisexamplecreatesasplineobjectinmodelspace.
'Declarethevariablesneeded
DimsplineObjAsAcadSpline
DimstartTan(0To2)AsDouble
DimendTan(0To2)AsDouble
DimfitPoints(0To8)AsDouble
'Definethevariables
startTan(0)=0.5:startTan(1)=0.5:startTan(2)=0
endTan(0)=0.5:endTan(1)=0.5:endTan(2)=0
fitPoints(0)=1:fitPoints(1)=1:fitPoints(2)=0
fitPoints(3)=5:fitPoints(4)=5:fitPoints(5)=0
fitPoints(6)=10:fitPoints(7)=0:fitPoints(8)=0
'Createthespline
SetsplineObj=ThisDrawing.ModelSpace.AddSpline_
(fitPoints,startTan,endTan)
ZoomAll
EndSub
Formoreinformationaboutsplines,seetheSplineobjectandAddSplinemethoddocumentationintheAutoCADActiveXandVBAReference.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>CreateObjects>
CreatePointObjects
Pointobjectscanbeuseful,forexample,asnodeorreferencepointsthatyoucansnaptoandoffsetobjectsfrom.Youcansetthestyleofthepointanditssizerelativetothescreenorinabsoluteunits.
ThePDMODEandPDSIZEsystemvariablescontroltheappearanceofPointobjects.ThePDMODEvalues0,2,3,and4specifyafiguretodrawthroughthepoint.Avalueof1selectsnothingtobedisplayed.
Adding32,64,or96tothepreviousvalueselectsashapetodrawaroundthepointinadditiontothefiguredrawnthroughit:
PDSIZEcontrolsthesizeofthepointfigures,exceptforPDMODEvalues0and1.A0settinggeneratesthepointat5percentofthegraphicsareaheight.ApositivePDSIZEvaluespecifiesanabsolutesizeforthepointfigures.Anegativevalueisinterpretedasapercentageoftheviewportsize.Thesizeofallpointsisrecalculatedwhenthedrawingisregenerated.
AfteryouchangePDMODEandPDSIZE,theappearanceofexistingpointschangesthenexttimethedrawingisregenerated.
TosetPDMODEandPDSIZE,usetheSetVariablemethod.
CreateaPointobjectandchangeitsappearance
ThefollowingcodeexamplecreatesaPointobjectinmodelspaceatthecoordinate(5,5,0).ThePDMODEandPDSIZEsystemvariablesarethenupdated.
SubCh4_CreatePoint()
DimpointObjAsAcadPoint
Dimlocation(0To2)AsDouble
'Definethelocationofthepoint
location(0)=5#:location(1)=5#:location(2)=0#
'Createthepoint
SetpointObj=ThisDrawing.ModelSpace.AddPoint(location)
ThisDrawing.SetVariable"PDMODE",34
ThisDrawing.SetVariable"PDSIZE",1
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
<$nopage>solid-filledareas:
CreateandEditAutoCADEntities>CreateObjects>
CreateSolid-FilledAreas
Youcancreatetriangularandquadrilateralareasfilledwithacolor.Forquickerresults,createtheseareaswiththeFILLMODEsystemvariableoff,thenturnFILLMODEontofillthefinishedarea.
Whenyoucreateaquadrilateralsolid-filledarea,thesequenceofthethirdandfourthpointsdeterminesitsshape.Comparethefollowingillustrations:
Thefirsttwopointsdefineoneedgeofthepolygon.Thethirdpointisdefineddiagonallyoppositefromthesecond.Ifthefourthpointissetequaltothethirdpoint,thenafilledtriangleiscreated.
Tocreateasolid-filledarea,usetheAddSolidmethod.
Formoreinformationaboutfillingsolids,see“CreateSolid-FilledAreas”intheUser'sGuide.
Createasolid-filledobject
Thefollowingcodeexamplecreatesaquadrilateralsolidinmodelspaceusingthecoordinates(0,0,0),(5,0,0),(5,8,0),and(0,8,0).
SubCh4_CreateSolid()
DimsolidObjAsAcadSolid
Dimpoint1(0To2)AsDouble
Dimpoint2(0To2)AsDouble
Dimpoint3(0To2)AsDouble
Dimpoint4(0To2)AsDouble
'Definethesolid
point1(0)=0#:point1(1)=0#:point1(2)=0#
point2(0)=5#:point2(1)=0#:point2(2)=0#
point3(0)=5#:point3(1)=8#:point3(2)=0#
point4(0)=0#:point4(1)=8#:point4(2)=0#
'Createthesolidobjectinmodelspace
SetsolidObj=ThisDrawing.ModelSpace.AddSolid_
(point1,point2,point3,point4)
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>CreateObjects>
WorkwithRegions
Regionsaretwo-dimensionalenclosedareasyoucreatefromclosedshapescalledloops.Aloopisacurveorasequenceofconnectedcurvesthatdefinesanareaonaplanewithaboundarythatdoesnotintersectitself.Loopscanbecombinationsoflines,lightweightpolylines,circles,arcs,ellipses,ellipticalarcs,splines,3Dfaces,traces,andsolids.Theobjectsthatmakeuptheloopsmusteitherbeclosedorformclosedareasbysharingendpointswithotherobjects.Theymustalsobecoplanar(onthesameplane).Theloopsthatmakeuparegionmustbedefinedasanarrayofobjects.
Formoreinformationaboutworkingwithregions,see“CreateandCombineAreas(Regions)intheUser'sGuide.
Topicsinthissection
CreateRegionsCreateCompositeRegionsUniteRegionsFindtheIntersectionofTwoRegions
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>CreateObjects>WorkwithRegions>
CreateRegions
Tocreatearegion,usetheAddRegionmethod.Thismethodwillcreatearegionoutofeveryclosedloopformedbytheinputarrayofcurves.AutoCADconvertsclosed2Dandplanar3Dpolylinestoseparateregions,thenconvertspolylines,lines,andcurvesthatformclosedplanarloops.Ifmorethantwocurvesshareanendpoint,theresultingregionmightbearbitrary.Becauseofthis,severalregionsmayactuallybecreatedwhenusingtheAddRegionmethod.Useavarianttoholdthenewlycreatedarrayofregions.
TocalculatethetotalnumberofRegionobjectscreated,usetheUBoundandLBoundVBAfunctions,asinthefollowingexample:
UBound(objRegions)-LBound(objRegions)+1
whereobjRegionsisavariantcontainingthereturnvaluefromAddRegion.Thisstatementwillcalculatethetotalnumberofregionscreated.
Createasimpleregion
Thefollowingcodeexamplecreatesaregionfromasinglecircle.
SubCh4_CreateRegion()
'Defineanarraytoholdthe
'boundariesoftheregion.
Dimcurves(0To0)AsAcadCircle
'Createacircletobecomea
'boundaryfortheregion.
Dimcenter(0To2)AsDouble
DimradiusAsDouble
center(0)=2
center(1)=2
center(2)=0
radius=5#
Setcurves(0)=ThisDrawing.ModelSpace.AddCircle_
(center,radius)
'Createtheregion
DimregionObjAsVariant
regionObj=ThisDrawing.ModelSpace.AddRegion(curves)
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>CreateObjects>WorkwithRegions>
CreateCompositeRegions
Youcancreatecompositeregionsbysubtracting,combining,orfindingtheintersectionofregionsor3Dsolids.Youcanthenextrudeorrevolvecompositeregionstocreatecomplexsolids.Tocreateacompositeregion,usetheBooleanmethod.
Whenyousubtractoneregionfromanother,youcalltheBooleanmethodfromthefirstregion.Thisistheregionfromwhichyouwanttosubtract.Forexample,tocalculatehowmuchcarpetingisneededforafloorplan,calltheBooleanmethodfromtheouterboundaryofthefloorspaceandusetheuncarpetedareas,suchaspillarsandcounters,astheobjectintheBooleanparameterlist.
Createacompositeregion
SubCh4_CreateCompositeRegions()
'Createtwocircles,onerepresentingaroom,
'theotherapillarinthecenteroftheroom
DimRoomObjects(0To1)AsAcadCircle
Dimcenter(0To2)AsDouble
DimradiusAsDouble
center(0)=4
center(1)=4
center(2)=0
radius=2#
SetRoomObjects(0)=ThisDrawing.ModelSpace._
AddCircle(center,radius)
radius=1#
SetRoomObjects(1)=ThisDrawing.ModelSpace._
AddCircle(center,radius)
'Createaregionfromthetwocircles
DimregionsAsVariant
regions=ThisDrawing.ModelSpace.AddRegion(RoomObjects)
'Copytheregionsintotheregionvariablesforeaseofuse
DimRoundRoomObjAsAcadRegion
DimPillarObjAsAcadRegion
Ifregions(0).Area>regions(1).AreaThen
'Thefirstregionistheroom
SetRoundRoomObj=regions(0)
SetPillarObj=regions(1)
Else
'Thefirstregionisthepillar
SetPillarObj=regions(0)
SetRoundRoomObj=regions(1)
EndIf
'Subtractthepillarspacefromthefloorspaceto
'getaregionthatrepresentsthetotalcarpetarea.
RoundRoomObj.BooleanacSubtraction,PillarObj
'UsetheAreapropertytodeterminethetotalcarpetarea
MsgBox"Thecarpetareais:"&RoundRoomObj.Area
EndSub
FindtheareaoftheresultingregionwiththeAreaproperty.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>CreateObjects>WorkwithRegions>
UniteRegions
Touniteregions,calltheBooleanmethodandentertheconstantacUnionfortheoperationinsteadofacSubtraction.Youcancombineregionsinanyordertounitethem.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>CreateObjects>WorkwithRegions>
FindtheIntersectionofTwoRegions
Tofindtheintersectionoftworegions,usetheconstantacIntersection.Youcancombineregionsinanyordertointersectthem.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>CreateObjects>
CreateHatches
Hatchingfillsaspecifiedareainadrawingwithapattern.
Whencreatingahatch,youdonotinitiallyspecifytheareatobefilled.FirstyoumustcreatetheHatchobject.Oncethisisdone,youcanspecifytheouterloop,whichistheoutermostboundaryforthehatch.Youcanthencontinuetospecifyanyinnerloopsthatmayexistinthehatch.
Formoreinformationaboutworkingwithhatches,see“OverviewofHatchPatternsandFills”intheUser'sGuide.
Topicsinthissection
CreatetheHatchObjectAssociateaHatchAssigntheHatchPatternTypeandNameDefinetheHatchBoundaries
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>CreateObjects>CreateHatches>
CreatetheHatchObject
WhencreatingtheHatchobject,youspecifythehatchpatterntype,thehatchpatternname,andtheassociativity.OncetheHatchobjecthasbeencreated,youwillnotbeabletochangethehatchassociativity.
TocreateaHatchobject,usetheAddHatchmethod.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>CreateObjects>CreateHatches>
AssociateaHatch
Youcancreateassociativeornonassociativehatches.Associativehatchesarelinkedtotheirboundariesandupdatedwhentheboundariesaremodified.Nonassociativehatchesareindependentoftheirboundaries.
Associativitycanonlybesetwhenahatchiscreated.Onceahatchhasbeencreated,youcanunassociateit,butyoucannotassociateitagain.
Tomakeahatchassociative,settheAssociativityparameteroftheAddHatchmethodtoTRUE.Tomakeahatchnonassociative,settheAssociativityparameteroftheAddHatchmethodtoFALSE.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>CreateObjects>CreateHatches>
AssigntheHatchPatternTypeandName
AutoCADsuppliesasolid-fillandmorethanfiftyindustry-standardhatchpatterns.Hatchpatternshighlightaparticularfeatureorareaofadrawing.Forexample,patternscanhelpdifferentiatethecomponentsofa3Dobjectorrepresentthematerialsthatmakeupanobject.
YoucanuseapatternsuppliedwithAutoCADoronefromanexternalpatternlibrary.ForatableofthehatchpatternssuppliedwithAutoCAD,seetheAutoCADCommandReference.
Tospecifyauniquepattern,youmustenterbothapatterntypeandapatternnamewhencreatingtheHatchobject.Thepatterntypespecifieswheretolookupthepatternname.Whenenteringthepatterntype,useoneofthefollowingconstants:
acHatchPatternTypePredefined
Selectsthepatternnamefromthosedefinedintheacad.patfile.
acHatchPatternTypeUserDefined
Definesapatternoflinesusingthecurrentlinetype.
acHatchPatternTypeCustomDefined
SelectsthepatternnamefromaPATotherthantheacad.patfile.
Whenenteringthepatternname,useanamethatisvalidforthefilespecifiedbythepatterntype.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>CreateObjects>CreateHatches>
DefinetheHatchBoundaries
OncetheHatchobjectiscreated,thehatchboundariescanbeadded.Boundariescanbeanycombinationoflines,arcs,circles,2Dpolylines,ellipses,splines,andregions.
Thefirstboundaryaddedmustbetheouterboundary,whichdefinestheoutermostlimitstobefilledbythehatch.Toaddtheouterboundary,usetheAppendOuterLoopmethod.
Oncetheouterboundaryisdefined,youcancontinueaddinginnerboundaries.AddinnerboundarieswiththeAppendInnerLoopmethod.
Innerboundariesdefineislandswithinthehatch.HowtheseislandsarehandledbytheHatchobjectdependsonthesettingoftheHatchStyleproperty.TheHatchStylepropertycanbesettooneofthefollowingconditions:
Hatchstyledefinitions
HatchStyle Condition Description
Normal Specifiesstandardstyle,ornormal.Thisoptionhatchesinwardfromtheoutermostareaboundary.IfAutoCADencountersaninternalboundary,itturnsoffhatchinguntilitencountersanotherboundary.ThisisthedefaultsettingfortheHatchStyleproperty.
Outer Fillstheoutermostareasonly.Thisstylealsohatchesinwardfromtheareaboundary,butitturnsoffhatchingifitencountersaninternalboundaryanddoesnotturnitbackonagain.
Ignore Ignoresinternalstructure.Thisoptionhatchesthroughallinternalobjects.
Whenyouhavefinisheddefiningthehatchitmustbeevaluatedbeforeitcanbedisplayed.UsetheEvaluatemethodtodothis.
CreateaHatchobject
Thisexamplecreatesanassociatehatchinmodelspace.Oncethehatchhasbeencreated,youcanchangethesizeofthecirclethatthehatchisassociatedwith.Thehatchwillchangetomatchthecurrentcirclesize.
SubCh4_CreateHatch()
DimhatchObjAsAcadHatch
DimpatternNameAsString
DimPatternTypeAsLong
DimbAssociativityAsBoolean
'Definethehatch
patternName="ANSI31"
PatternType=0
bAssociativity=True
'CreatetheassociativeHatchobject
SethatchObj=ThisDrawing.ModelSpace.AddHatch_
(PatternType,patternName,bAssociativity)
'Createtheouterboundaryforthehatch.(acircle)
DimouterLoop(0To0)AsAcadEntity
Dimcenter(0To2)AsDouble
DimradiusAsDouble
center(0)=3:center(1)=3:center(2)=0
radius=1
SetouterLoop(0)=ThisDrawing.ModelSpace._
AddCircle(center,radius)
'Appendtheouterboundarytothehatch
'object,anddisplaythehatch
hatchObj.AppendOuterLoop(outerLoop)
hatchObj.Evaluate
ThisDrawing.RegenTrue
EndSub
Pleasesendusyourcommentaboutthispage
<$startrange>selectionsets:filterlists,<$startrange>filterlists,<$startrange>filtering:selectionsets,DXFcodes,andfiltertypes(table),filtertypes,andDXFcodes(table),<$startrange>filterlists:examplecode,SelectionSetobject:examplecode,filtering:examplecode,<$endrange>selectionsets:filterlists,<$endrange>filterlists,<$endrange>filtering:selectionsets,<$endrange>filterlists:examplecode,selectionsets:removingobjects,objects:removingfromselectionsets,RemoveItemsmethod:inselectionsets,Clearmethod:inselectionsets,Erasemethod:inselectionsets,Deletemethod:inselectionsets,">
CreateandEditAutoCADEntities>
WorkwithSelectionSets
Aselectionsetcanconsistofasingleobject,oritcanbeamorecomplexgrouping:forexample,thesetofobjectsofacertainlayer.
Definingaselectionsetisatwo-stepprocess.First,youmustcreateanewselectionsetandaddittotheSelectionSetscollection.Oncecreated,youthenpopulatetheselectionsetwiththeobjectsyouwanttoprocess.
Topicsinthissection
CreateaSelectionSetAddObjectstoaSelectionSetDefineRulesforSelectionSetsDisplayInformationAboutaSelectionSetRemoveObjectsfromaSelectionSet
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>WorkwithSelectionSets>
CreateaSelectionSet
Tocreateanamedselectionset,usetheAddmethod.Thismethodrequiresonlyasingleparameter—thenameoftheselectionset.
Ifaselectionsetofthesamenamealreadyexists,AutoCADreturnsanerrormessage.Itisagoodprogrammingpracticetodeleteaselectionsetwhenyounolongerneedit.UsetheDeletemethodtodeleteaselectionset,asinthefollowingexample:
ThisDrawing.SelectionSets.Item("NewSelectionSet").Delete
Createanemptyselectionset
Thisexamplecreatesanewselectionset.
SubCh4_CreateSelectionSet()
DimselectionSet1AsAcadSelectionSet
SetselectionSet1=ThisDrawing.SelectionSets._
Add("NewSelectionSet")
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>WorkwithSelectionSets>
AddObjectstoaSelectionSet
Youcanaddobjectstotheactiveselectionsetbyusinganyofthefollowingmethods:
AddItems
Addsoneormoreobjectstothespecifiedselectionset.
Select
Selectsobjectsandplacesthemintotheactiveselectionset.Youcanselectallobjects,objectswithinandcrossingarectangulararea,objectswithinandcrossingapolygonarea,allobjectscrossingafence,themostrecentlycreatedobject,theobjectsinthemostrecentselectionset,objectswithinawindow,orobjectswithinawindowpolygon.
SelectAtPoint
Selectsobjectspassingthroughagivenpointandplacesthemintotheactiveselectionset.
SelectByPolygon
Selectsobjectswithinafenceandaddsthemtotheactiveselectionset.
SelectOnScreen
Promptstheusertopickobjectsfromthescreenandaddsthemintotheactiveselectionset.
Addselectedobjectstoaselectionset
Thisexamplepromptstheusertoselectobjects,thenaddsthoseobjectstotheselectionset.
SubCh4_AddToASelectionSet()
'Createanewselectionset
DimssetAsAcadSelectionSet
Setsset=ThisDrawing.SelectionSets.Add("SS1")
'Prompttheusertoselectobjects
'andaddthemtotheselectionset.
'Tofinishselecting,pressENTER.
sset.SelectOnScreen
EndSub
Pleasesendusyourcommentaboutthispage
<$startrange>selectionsets:filterlists,<$startrange>filterlists,<$startrange>filtering:selectionsets,DXFcodes,andfiltertypes(table),filtertypes,andDXFcodes(table),<$startrange>filterlists:examplecode,SelectionSetobject:examplecode,filtering:examplecode,<$endrange>selectionsets:filterlists,<$endrange>filterlists,<$endrange>filtering:selectionsets,<$endrange>filterlists:examplecode,">
CreateandEditAutoCADEntities>WorkwithSelectionSets>
DefineRulesforSelectionSets
Youcanlimitselectionsetsbypropertyorbyobjecttypeusingfilterlists.Forexample,youcancopyonlytheblueobjectsinacircuitboarddrawing,oronlyobjectsonacertainlayer.Youcanalsocombineselectioncriteriainyourfilterlist.Forexample,youcantellAutoCADtoincludeanobjectinaselectionsetonlyifitisabluecircleonaspecificlayer.FilterlistscanbespecifiedfortheSelect,SelectAtPoint,SelectByPolygon,andSelectOnScreenmethods.
Note Filteringrecognizesonlylinetypesexplicitlyassignedtoobjects,notthoseinheritedbythelayer.
Topicsinthissection
UseFilterListstoDefineSelectionSetRulesSpecifyMultipleCriteriainaSelectionSetFilterListAddComplexitytoYourFilterListConditionsUseWild-CardPatternsinSelectionSetFilterCriteriaFilterforExtendedData
Pleasesendusyourcommentaboutthispage
<$startrange>filterlists:examplecode,SelectionSetobject:examplecode,filtering:examplecode,">
CreateandEditAutoCADEntities>WorkwithSelectionSets>DefineRulesforSelectionSets>
UseFilterListstoDefineSelectionSetRules
Filterlistsarecomposedofpairsofarguments.Thefirstargumentidentifiesthetypeoffilter(forexample,anobject),andthesecondargumentspecifiesthevalueyouarefilteringon(forexample,circles).ThefiltertypeisaDXFgroupcodethatspecifieswhichfiltertouse.Afewofthemostcommonfiltertypesarelistedhere.
DXFcodesforcommonfilters
DXFcode Filtertype
0 ObjectType(String)Suchas“Line,”“Circle,”“Arc,”andsoforth.
2 ObjectName(String)Thetable(given)nameofanamedobject.
8 LayerName(String)Suchas“Layer0.”
60 ObjectVisibility(Integer)Use0=visible,1=invisible.
62 ColorNumber(Integer)Numericindexvaluesrangingfrom0to256.ZeroindicatesBYBLOCK.256indicatesBYLAYER.Anegativevalueindicatesthatthelayeristurnedoff.
67 Model/paperspaceindicator(Integer)Use0oromitted=modelspace,1=paperspace.
ForacompletelistofDXFgroupcodes,seeGroupCodeValueTypesintheDXFReference.
Thefilterargumentsaredeclaredasarrays.Thefiltertypeisdeclaredasanintegerandthefiltervalueasavariant.Eachfiltertypemustbepairedwithafiltervalue.Forexample:
FilterType(0)=0'Indicatesfilterreferstoanobjecttype
FilterData(0)="Circle"'Indicatestheobjecttypeis"Circle"
Specifyasingleselectioncriterionforaselectionset
Thefollowingcodepromptsuserstoselectobjectstobeincludedinaselectionset,butonlyaddstheselectedobjectifitisacircle:
SubCh4_FilterMtext()
DimsstextAsAcadSelectionSet
DimFilterType(0)AsInteger
DimFilterData(0)AsVariant
Setsstext=ThisDrawing.SelectionSets.Add("SS2")
FilterType(0)=0
FilterData(0)="Circle"
sstext.SelectOnScreenFilterType,FilterData
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>WorkwithSelectionSets>DefineRulesforSelectionSets>
SpecifyMultipleCriteriainaSelectionSetFilterList
Tospecifymultipleselectioncriteria,declareanarraycontainingenoughelementstorepresenteachcriterion,andassigneachcriteriontoanelement.
Selectobjectsthatmeetthreecriteria
Thefollowingcodespecifiestwocriteria:theobjectmustbeacircleanditmustresideonlayer0.ThecodedeclaresFilterTypeandFilterDataasarraysoftwoelements,andassignseachcriteriontoanelement:
SubCh4_FilterBlueCircleOnLayer0()
DimsstextAsAcadSelectionSet
DimFilterType(1)AsInteger
DimFilterData(1)AsVariant
Setsstext=ThisDrawing.SelectionSets.Add("SS4")
FilterType(0)=0
FilterData(0)="Circle"
FilterType(1)=8
FilterData(1)="0"
sstext.SelectOnScreenFilterType,FilterData
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>WorkwithSelectionSets>DefineRulesforSelectionSets>
AddComplexitytoYourFilterListConditions
Whenyouspecifymultipleselectioncriteria,AutoCADassumestheselectedobjectmustmeeteachcriterion.Butyoucanqualifyyourcriteriainotherways.Fornumericitems,youcanspecifyrelationaloperations(forexample,theradiusofacirclemustbegreaterthanorequalto5.0).Andforallitems,youcanspecifylogicaloperations(forexample,TextorMtext).
Usea-4DXFcodetoindicatearelationaloperatorinyourfilterspecification.Specifytheoperatorasastring.Theallowablerelationaloperatorsareshowninthefollowingtable.
Relationaloperatorsforselectionsetfilterlists
Operator Description
"*" Anythinggoes(alwaystrue)
"=" Equals
"!=" Notequalto
"/=" Notequalto
"<>" Notequalto
"<" Lessthan
"<=" Lessthanorequalto
">" Greaterthan
">=" Greaterthanorequalto
"&" BitwiseAND(integergroupsonly)
"&=" Bitwisemaskedequals(integergroupsonly)
Logicaloperatorsinfilterlistsarealsoindicatedbya-4groupcode,andtheoperatorisastring,buttheoperatorsmustbepaired.Theopeningoperatorisprecededbyaless-thansymbol(<),andtheclosingoperatorisfollowedbyagreater-thansymbol(>).Thefollowingtableliststhelogicaloperatorsallowedinselectionsetfiltering.
Logicalgroupingoperatorsforselectionsetfilterlists
Starting
operatorEncloses
Ending
operator
"<AND" Oneormoreoperands
"AND>"
"<OR" Oneormoreoperands
"OR>"
"<XOR" Twooperands "XOR>"
"<NOT" Oneoperand "NOT>"
Selectacirclewhoseradiusisgreaterthanorequalto5.0
Thefollowingcodespecifiesthattheselectedobjectmustbeacirclewhose
radiusisgreaterthanorequalto5.0:
SubCh4_FilterRelational()
DimsstextAsAcadSelectionSet
DimFilterType(2)AsInteger
DimFilterData(2)AsVariant
Setsstext=ThisDrawing.SelectionSets.Add("SS5")
FilterType(0)=0
FilterData(0)="Circle"
FilterType(1)=-4
FilterData(1)=">="
FilterType(2)=40
FilterData(2)=5#
sstext.SelectOnScreenFilterType,FilterData
EndSub
SelecteitherTextorMtext
ThefollowingexamplespecifiesthateitherTextorMtextobjectscanbeselected:
SubCh4_FilterOrTest()
DimsstextAsAcadSelectionSet
DimFilterType(3)AsInteger
DimFilterData(3)AsVariant
Setsstext=ThisDrawing.SelectionSets.Add("SS6")
FilterType(0)=-4
FilterData(0)="<or"
FilterType(1)=0
FilterData(1)="TEXT"
FilterType(2)=0
FilterData(2)="MTEXT"
FilterType(3)=-4
FilterData(3)="or>"
sstext.SelectOnScreenFilterType,FilterData
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>WorkwithSelectionSets>DefineRulesforSelectionSets>
UseWild-CardPatternsinSelectionSetFilterCriteria
Symbolnamesandstringsinfilterlistscanincludewild-cardpatterns.
Thefollowingtableidentifiesthewild-cardcharactersrecognizedbyAutoCAD,andwhateachmeansinthecontextofastring:
Wild-cardcharacters
Character Definition
# (pound) Matchesanysinglenumericdigit
@ (at) Matchesanysinglealphabeticcharacter
. (period) Matchesanysinglenonalphanumericcharacter
* (asterisk)
Matchesanycharactersequence,includinganemptyone,anditcanbeusedanywhereinthesearchpattern:atthebeginning,middle,orend
? (questionmark)
Matchesanysinglecharacter
~ (tilde) Ifitisthefirstcharacterinthe
pattern,itmatchesanythingexceptthepattern
[...] Matchesanyoneofthecharactersenclosed
[~...] Matchesanysinglecharacternotenclosed
- (hyphen) Usedinsidebracketstospecifyarangeforasinglecharacter
, (comma)
Separatestwopatterns
` (reversequote)
Escapesspecialcharacters(readsnextcharacterliterally)
Useasinglequote(`)toindicatethatacharacterisnotawildcard,butistobetakenliterally.Forexample,tospecifythatonlyananonymousblocknamed“*U2”beincludedintheselectionset,usethefollowingfilterarguments:
FilterType(0)=2
FilterData(0)="`*U2"
SelectMtextwhereaspecificwordappearsinthetext
ThefollowingcodedefinestheselectioncriteriaasanyMtextinwhich“The”appearsinthetextstring.ThisexamplealsodemonstratesuseoftheSelectByPolygonselectionmethod:
SubCh4_FilterPolygonWildcard()
DimsstextAsAcadSelectionSet
DimFilterType(1)AsInteger
DimFilterData(1)AsVariant
DimpointsArray(0To11)AsDouble
DimmodeAsInteger
mode=acSelectionSetWindowPolygon
pointsArray(0)=-12#:pointsArray(1)=-7#:pointsArray(2)=0
pointsArray(3)=-12#:pointsArray(4)=10#:pointsArray(5)=0
pointsArray(6)=10#:pointsArray(7)=10#:pointsArray(8)=0
pointsArray(9)=10#:pointsArray(10)=-7#:pointsArray(11)=0
Setsstext=ThisDrawing.SelectionSets.Add("SS10")
FilterType(0)=0
FilterData(0)="MTEXT"
FilterType(1)=1
FilterData(1)="*The*"
sstext.SelectByPolygonmode,pointsArray,FilterType,FilterData
EndSub
Pleasesendusyourcommentaboutthispage
<$endrange>selectionsets:filterlists,<$endrange>filterlists,<$endrange>filtering:selectionsets,<$endrange>filterlists:examplecode,">
CreateandEditAutoCADEntities>WorkwithSelectionSets>DefineRulesforSelectionSets>
FilterforExtendedData
Externalapplicationscanattachdatasuchastextstrings,numericvalues,3Dpoints,distances,andlayernamestoAutoCADobjects.Thisdataisreferredtoasextendeddata,orxdata.Youcanfilterentitiescontainingextendeddataforaspecifiedapplication.
SeeFilterforExtendedDataformoreinformationaboutextendeddata.
Selectcirclesthatcontainxdata
Thefollowingexamplefiltersforcirclescontainingxdataaddedbythe“MY_APP”application:
SubCh4_FilterXdata()
DimsstextAsAcadSelectionSet
DimmodeAsInteger
DimpointsArray(0To11)AsDouble
mode=acSelectionSetWindowPolygon
pointsArray(0)=-12#:pointsArray(1)=-7#:pointsArray(2)=0
pointsArray(3)=-12#:pointsArray(4)=10#:pointsArray(5)=0
pointsArray(6)=10#:pointsArray(7)=10#:pointsArray(8)=0
pointsArray(9)=10#:pointsArray(10)=-7#:pointsArray(11)=0
DimFilterType(1)AsInteger
DimFilterData(1)AsVariant
Setsstext=ThisDrawing.SelectionSets.Add("SS9")
FilterType(0)=0
FilterData(0)="Circle"
FilterType(1)=1001
FilterData(1)="MY_APP"
sstext.SelectByPolygonmode,pointsArray,FilterType,FilterData
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>WorkwithSelectionSets>
DisplayInformationAboutaSelectionSet
Torefertoanexistingselectionsetwhosenameyouknow,refertoitbyname.Thefollowingexamplereferstoaselectionsetnamed“SS10:”
SubGetObjInSet()
DimselsetAsAcadSelectionSet
Setselset=ThisDrawing.SelectionSets("SS10")
MsgBox("Selectionset"&selset.Name&"contains"&_
selset.Count&"items")
EndSub
EachselectionsetinadrawingisamemberoftheSelectionSetscollection.YoucanusetheForEachstatementtoiteratethroughadrawing'sSelectionSetscollectionandcollectinformationabouteachselectionset.
Displaythenameofeachselectionsetinadrawing
Thefollowingcodedisplaysthenameofeachselectionsetinadrawing,andliststhetypesofobjectsincludedineachselectionset:
SubListSelectionSets()
DimselsetCollectionAsAcadSelectionSets
DimselsetAsAcadSelectionSet
DimentAsObject
Dimi,jAsInteger
SetselsetCollection=ThisDrawing.SelectionSets
'Findeachselectionsetinthedrawing
i=0
ForEachselsetInselsetCollection
MsgBox"Selectionset"&CStr(i)&"is:"&selset.Name
'Nowfindeachobjectintheselectionset,andsaywhatitis
j=0
ForEachentInselset
MsgBox"Item"&CStr(j+1)&"in"&selset.Name_
&"is:"&ent.EntityName
j=j+1
Next
i=i+1
Next
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>WorkwithSelectionSets>
RemoveObjectsfromaSelectionSet
Afteryoucreateaselectionset,youcanchoosetoremoveindividualobjects,oralltheobjectsfromthatset.Forexample,youcanselectanentiregroupofdenselygroupedobjectsandremovespecificobjectswithinthegroup,leavingonlytheobjectsyouwanttobeintheset.
Usethefollowingmethodstoremoveitemsfromtheselectionset:
RemoveItems
TheRemoveItemsmethodremovesoneormoreitemsfromaselectionset.Theremoveditemsstillexist,buttheynolongerresideintheselectionset.
Clear
TheClearmethodwillemptytheselectionset.Theselectionsetwillstillexist,butcontainsnoitems.Theitemsthatpreviouslyresidedintheselectionstillexist,buttheynolongerresideintheselectionset.
Erase
TheErasemethoddeletesallitemsinaselectionset.Theselectionsetstillexists,butwillcontainnoitems.Theitemsthatpreviouslyresidedintheselectionsetnolongerexist.
Delete
TheDeletemethoddeletesaselectionsetandallitemsintheselectionset.NeithertheselectionsetnortheitemspreviouslyintheselectionsetwillexistafteracalltotheDeletemethod.
Pleasesendusyourcommentaboutthispage
<$nopage>matrix:
CreateandEditAutoCADEntities>
EditObjects
Tomodifyanexistingobject,usethemethodsandpropertiesassociatedwiththatobject.Ifyoumodifyavisiblepropertyofagraphicobject,usetheUpdatemethodtoredrawtheobjectonscreen.
Thissectiondescribeshowtoedit2Dobjects.
Topicsinthissection
WorkwithNamedObjectsCopyObjectsOffsetObjectsMirrorObjectsArrayObjectsMoveObjectsRotateObjectsDeleteObjectsScaleObjectsTransformObjectsExtendandTrimObjectsExplodeObjectsEditPolylinesEditSplinesEditHatches
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>
WorkwithNamedObjects
InadditiontothegraphicobjectsusedbyAutoCAD,thereareseveraltypesofnongraphicobjectsstoredindrawingfiles.Theseobjectshavedescriptivedesignationsassociatedwiththem,forexample,blocks,layers,groups,anddimensionstyles.Inmostcases,younameobjectsasyoucreatethem,andrenamethemlater.Namesarestoredinsymboltables.Whenyouspecifyanamedobject,youarereferencingthenameandassociateddataoftheobjectinthesymboltable.
Topicsinthissection
PurgeNamedObjectsRenameObjects
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>WorkwithNamedObjects>
PurgeNamedObjects
Youcanpurgeunused,unreferencednamedobjectsfromadrawingatanytimeduringaneditingsession.Purgingreducesdrawingsize.Youcannotpurgeobjectsthatarereferencedbyotherobjects.Forexample,afontfilemightbereferencedbyatextstyle.Alayerisreferencedbytheobjectsonthelayer.
Topurgeadrawing,usethePurgeAllmethod,asfollows:
ThisDrawing.PurgeAll
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>WorkwithNamedObjects>
RenameObjects
Asyourdrawingsbecomemorecomplex,youcanrenameobjectstokeepthenamesmeaningfulortoavoidconflictswithnamesinotherdrawingsyouhaveinsertedinthemaindrawings.
YoucanrenameanynamedobjectexceptthosethatAutoCADnamesbydefault,forexample,layer0ortheCONTINUOUSlinetype.
Namescanbeupto255characterslong.Inadditiontolettersandnumbers,namescancontainspaces(althoughAutoCADremovesspacesthatappeardirectlybeforeandafteraname)andanyspecialcharacternotusedbyMicrosoftWindowsorAutoCADforotherpurposes.Specialcharactersthatyoucannotuseincludeless-thanandgreater-thansymbols(<>),forwardslashesandbackslashes(/\),quotationmarks("),colons(:),semicolons(;),questionmarks(?),commas(,),asterisks(*),verticalbars(|),equalsigns(=),andsinglequotes(').YoualsocannotusespecialcharacterscreatedwithUnicodefonts.
Torenameanobject,usetheNamepropertyforthatobject.
Renamealayer
Thisexamplecreatesalayercalled“NewLayer”andthenrenamesthelayerto“MyLayer”.
SubCh4_RenamingLayer()
'Createalayer
DimlayerObjAsAcadLayer
SetlayerObj=ThisDrawing.Layers.Add("NewLayer")
'Changethenameofthelayer
layerObj.Name="MyLayer"
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>
CopyObjects
Youcancopysingleormultipleobjectswithinthecurrentdrawing.Offsettingcreatesnewobjectsataspecifieddistancefromselectedobjects,orthroughaspecifiedpoint.Mirroringcreatesamirrorimageofobjectsinaspecifiedmirrorline.Arrayingcreatessetsofcopiedobjectsinarectangularorcircularpattern.
Formoreinformationaboutcopyingobjects,see“Copy,Offset,orMirrorObjects”intheUser'sGuide.
Note Youcannotperformanyofthecopymethodswhilesimultaneouslyiteratingthroughacollection.Aniterationwillopentheworkspaceforaread-onlyoperationwhilethesemethodsattempttoperformaread-writeoperation.Completeanyiterationofacollectionbeforeyoucallthesemethods.
Topicsinthissection
CopyanObjecttotheSameLocationCopyMultipleObjects
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>CopyObjects>
CopyanObjecttotheSameLocation
Tocopyasingleobject,usetheCopymethodprovidedforthatobject.Thismethodcreatesanewobjectthatisaduplicateoftheoriginalobject.Thenewobjectislocatedatthesamepositionastheoriginal,andisreturnedbythemethod.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>CopyObjects>
CopyMultipleObjects
Tocopymultipleobjects,usetheCopyObjectsmethodorcreateanarrayofobjectstousewiththeCopymethod.(Tocopytheobjectsinaselectionset,iteratethroughtheselectionsetandsavetheobjectsintoanarray.)Iteratethroughthearray,copyingeachobjectindividually,andcollectthenewlycreatedobjectsinasecondarray.
Tocopymultipleobjectstoadifferentdrawing,usetheCopyObjectsmethodandsettheOwnerparametertothedrawing'smodelspace.
CopytwoCircleobjects
ThisexamplecreatestwoCircleobjectsandusestheCopyObjectsmethodtomakeacopyofthecircles.
SubCh4_CopyCircleObjects()
DimDOC1AsAcadDocument
DimcircleObj1AsAcadCircle
DimcircleObj2AsAcadCircle
DimcircleObj1CopyAsAcadCircle
DimcircleObj2CopyAsAcadCircle
DimcenterPoint(0To2)AsDouble
Dimradius1AsDouble
Dimradius2AsDouble
Dimradius1CopyAsDouble
Dimradius2CopyAsDouble
DimobjCollection(0To1)AsObject
DimretObjectsAsVariant
'DefinetheCircleobject
centerPoint(0)=0:centerPoint(1)=0:centerPoint(2)=0
radius1=5#:radius2=7#
radius1Copy=1#:radius2Copy=2#
'Createanewdrawing
SetDOC1=ThisDrawing.Application.Documents.Add
'Addtwocirclestothedrawing
SetcircleObj1=DOC1.ModelSpace.AddCircle_
(centerPoint,radius1)
SetcircleObj2=DOC1.ModelSpace.AddCircle_
(centerPoint,radius2)
ZoomAll
'Puttheobjectstobecopiedintoaform
'compatiblewithCopyObjects
SetobjCollection(0)=circleObj1
SetobjCollection(1)=circleObj2
'Copyobjectandgetbackacollectionof
'thenewobjects(copies)
retObjects=DOC1.CopyObjects(objCollection)
'Getnewlycreatedobjectandapply
'newpropertiestothecopies
SetcircleObj1Copy=retObjects(0)
SetcircleObj2Copy=retObjects(1)
circleObj1Copy.radius=radius1Copy
circleObj1Copy.Color=acRed
circleObj2Copy.radius=radius2Copy
circleObj2Copy.Color=acRed
ZoomAll
EndSub
Copyobjectstoanotherdrawing
ThisexamplecreatesCircleobjects,thenusestheCopyObjectsmethodtocopythecirclesintoanewdrawing.
SubCh4_Copy_to_New_Drawing()
DimDOC0AsAcadDocument
DimcircleObj1AsAcadCircle,circleObj2AsAcadCircle
DimcenterPoint(0To2)AsDouble
Dimradius1AsDouble,radius2AsDouble
Dimradius1CopyAsDouble,radius2CopyAsDouble
DimobjCollection(0To1)AsObject
DimretObjectsAsVariant
'DefinetheCircleobject
centerPoint(0)=0:centerPoint(1)=0:centerPoint(2)=0
radius1=5#:radius2=7#
radius1Copy=1#:radius2Copy=2#
'Addtwocirclestothecurrentdrawing
SetcircleObj1=ThisDrawing.ModelSpace.AddCircle_
(centerPoint,radius1)
SetcircleObj2=ThisDrawing.ModelSpace.AddCircle_
(centerPoint,radius2)
ThisDrawing.Application.ZoomAll
'Savepointertothecurrentdrawing
SetDOC0=ThisDrawing.Application.ActiveDocument
'Copyobjects
'
'Firstputtheobjectstobecopiedintoaformcompatible
'withCopyObjects
SetobjCollection(0)=circleObj1
SetobjCollection(1)=circleObj2
'Createanewdrawingandpointtoitsmodelspace
DimDoc1MSpaceAsAcadModelSpace
DimDOC1AsAcadDocument
SetDOC1=Documents.Add
SetDoc1MSpace=DOC1.ModelSpace
'Copytheobjectsintothemodelspaceofthenewdrawing.A
'collectionofthenew(copied)objectsisreturned.
retObjects=DOC0.CopyObjects(objCollection,Doc1MSpace)
DimcircleObj1CopyAsAcadCircle,circleObj2CopyAsAcadCircle
'Getthenewlycreatedobjectcollectionandapplynew
'propertiestothecopies.
SetcircleObj1Copy=retObjects(0)
SetcircleObj2Copy=retObjects(1)
circleObj1Copy.radius=radius1Copy
circleObj1Copy.Color=acRed
circleObj2Copy.radius=radius2Copy
circleObj2Copy.Color=acRed
ThisDrawing.Application.ZoomAll
MsgBox"Circlescopied."
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>
OffsetObjects
Offsettinganobjectcreatesanewobjectataspecifiedoffsetdistancefromtheoriginalobject.Youcanoffsetarcs,circles,ellipses,lines,lightweightpolylines,polylines,splines,andxlines.
Tooffsetanobject,usetheOffsetmethodprovidedforthatobject.Theonlyinputtothismethodisthedistancetooffsettheobject.Ifthisdistanceisnegative,itisinterpretedbyAutoCADasbeinganoffsettomakea“smaller”curve(thatis,foranarcitwouldoffsettoaradiusthatisthegivendistancelessthanthestartingcurve'sradius).If“smaller”hasnomeaning,thenAutoCADwouldoffsetinthedirectionofsmallerX,Y,ZWCScoordinates.Iftheoffsetdistanceisinvalid,thenanerrorisreturned.
Formanyobjects,theresultofthisoperationwillbeasinglenewcurve(whichmaynotbeofthesametypeastheoriginalcurve).Forexample,offsettinganellipsewillresultinasplinebecausetheresultdoesfittheequationofanellipse.Insomecasesitmaybenecessaryfortheoffsetresulttobeseveralcurves.Becauseofthis,themethodreturnsthenewobject,orarrayofobjects,asavariant.
Formoreinformationaboutoffsettingobjects,see“Copy,Offset,orMirrorObjects”intheUser'sGuide.
Offsetapolyline
Thisexamplecreatesalightweightpolylineandthenoffsetsthepolyline.
SubCh4_OffsetPolyline()
'Createthepolyline
DimplineObjAsAcadLWPolyline
Dimpoints(0To11)AsDouble
points(0)=1:points(1)=1
points(2)=1:points(3)=2
points(4)=2:points(5)=2
points(6)=3:points(7)=2
points(8)=4:points(9)=4
points(10)=4:points(11)=1
SetplineObj=ThisDrawing.ModelSpace._
AddLightWeightPolyline(points)
plineObj.Closed=True
ZoomAll
'Offsetthepolyline
DimoffsetObjAsVariant
offsetObj=plineObj.Offset(0.25)
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>
MirrorObjects
Mirroringcreatesamirrorimagecopyofanobjectaroundanaxisormirrorline.Youcanmirroralldrawingobjects.
Tomirroranobject,usetheMirrormethodprovidedforthatobject.Thismethodrequirestwocoordinatesasinput.Thetwocoordinatesspecifiedbecometheendpointsofthemirrorlinearoundwhichthebaseobjectisreflected.In3D,thislineorientsamirroringplaneperpendiculartotheXYplaneoftheUCScontainingthemirrorline.
UnlikethemirrorcommandinAutoCAD,thismethodplacesthereflectedimageintothedrawingandretainstheoriginalobject.(Toremovetheoriginalobject,usetheErasemethod.)
TomanagethereflectionpropertiesofTextobjects,usetheMIRRTEXTsystemvariable.ThedefaultsettingofMIRRTEXTisOn(1),whichcausesTextobjectstobemirroredjustasanyotherobject.WhenMIRRTEXTisOff(0),textisnotmirrored.UsetheGetVariableandSetVariablemethodstoqueryandsettheMIRRTEXTsetting.
YoucanmirroraViewportobjectinpaperspace,althoughdoingsohasnoeffectonitsmodelspacevieworonmodelspaceobjects.
Formoreinformationaboutmirroringobjects,see“Copy,Offset,orMirrorObjects”intheUser'sGuide.
Mirrorapolylineaboutanaxis
Thisexamplecreatesalightweightpolylineandmirrorsthatpolylineaboutanaxis.Thenewlycreatedpolylineiscoloredblue.
SubCh4_MirrorPolyline()
'Createthepolyline
DimplineObjAsAcadLWPolyline
Dimpoints(0To11)AsDouble
points(0)=1:points(1)=1
points(2)=1:points(3)=2
points(4)=2:points(5)=2
points(6)=3:points(7)=2
points(8)=4:points(9)=4
points(10)=4:points(11)=1
SetplineObj=ThisDrawing.ModelSpace._
AddLightWeightPolyline(points)
plineObj.Closed=True
ZoomAll
'Definethemirroraxis
Dimpoint1(0To2)AsDouble
Dimpoint2(0To2)AsDouble
point1(0)=0:point1(1)=4.25:point1(2)=0
point2(0)=4:point2(1)=4.25:point2(2)=0
'Mirrorthepolyline
DimmirrorObjAsAcadLWPolyline
SetmirrorObj=plineObj.Mirror(point1,point2)
DimcolAsNewAcadAcCmColor
Callcol.SetRGB(125,175,235)
mirrorObj.TrueColor=col
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>
ArrayObjects
Youcancopyanobjectinpolarorrectangulararrays.Forpolararrays,youcontrolthenumberofcopiesoftheobjectandtheangletofillthearrayto.Forrectangulararrays,youcontrolthenumberofrowsandcolumnsandthedistancebetweenthem.
Formoreinformationaboutarrays,see“CreateanArrayofObjects”intheUser'sGuide.
Topicsinthissection
CreatePolarArraysCreateRectangularArrays
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>ArrayObjects>
CreatePolarArrays
Youcanarrayalldrawingobjects.Tocreateapolararray,usetheArrayPolarmethodprovidedforthatobject.Thismethodrequiresyoutoprovidethenumberofobjectstocreate,theangle-to-fill,andthecenterpointforthearray.Thenumberofobjectsmustbeapositiveintegergreaterthan1.Theangle-to-fillmustbeinradians.Apositivevaluespecifiescounterclockwiserotation.Anegativevaluespecifiesclockwiserotation.Anerrorisreturnedforananglethatequals0.Thecenterpointisavariantarraycontainingthreedoubles.Thesedoublesrepresentthe3DWCScoordinatespecifyingthecenterpointforthepolararray.
AutoCADdeterminesthedistancefromthearray'scenterpointtoareferencepointontheoriginalobject.Thereferencepointuseddependsonthetypeofobject.AutoCADusesthecenterpointofacircleorarc,theinsertionpointofablockorshape,thestartpointoftext,andoneendpointofalineortrace.
ThismethoddoesnotsupporttheRotateWhileCopyingoptionoftheAutoCADARRAYcommand.
Createapolararray
Thisexamplecreatesacircle,andthenperformsapolararrayofthecircle.Thiscreatesfourcirclesfilling180degreesaroundabasepointof(4,4,0).
SubCh4_ArrayingACircle()
'Createthecircle
DimcircleObjAsAcadCircle
Dimcenter(0To2)AsDouble
DimradiusAsDouble
center(0)=2#:center(1)=2#:center(2)=0#
radius=1
SetcircleObj=ThisDrawing.ModelSpace._
AddCircle(center,radius)
ZoomAll
'Definethepolararray
DimnoOfObjectsAsInteger
DimangleToFillAsDouble
DimbasePnt(0To2)AsDouble
noOfObjects=4
angleToFill=3.14'180degrees
basePnt(0)=4#:basePnt(1)=4#:basePnt(2)=0#
'Thefollowingexamplewillcreate4copies
'ofanobjectbyrotatingandcopyingitabout
'thepoint(3,3,0).
DimretObjAsVariant
retObj=circleObj.ArrayPolar_
(noOfObjects,angleToFill,basePnt)
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>ArrayObjects>
CreateRectangularArrays
Tocreatea2Dor3Drectangulararray,usetheArrayRectangularmethodprovidedforthatobject.Thismethodrequiresyoutoprovidethenumberofrows,numberofcolumns,distancebetweenrows,anddistancebetweencolumns.Whencreatinga3Darray,youmustalsospecifythenumberoflevelsanddistancebetweenlevelsaswell.
Arectangulararrayisconstructedbyreplicatingtheobjectintheselectionsettheappropriatenumberoftimes.Ifyoudefineonerow,youmustspecifymorethanonecolumnandviceversa.
Theoriginalobjectisassumedtobeinthelower-leftcorner,andthearrayisgeneratedupandtotheright.Ifthedistancebetweenrowsisanegativenumber,rowsareaddeddownward.Ifthedistancebetweencolumnsisanegativenumber,thecolumnsareaddedtotheleft.
AutoCADbuildstherectangulararrayalongabaselinedefinedbythecurrentsnaprotationangle.Thisangleis0bydefault,sotherowsandcolumnsofarectangulararrayareorthogonalwithrespecttotheXandYdrawingaxes.Youcanchangethisangleandcreatearotatedarraybysettingthesnaprotationangletoanonzerovalue.Todothis,usetheSnapRotationAngleproperty.
Createarectangulararray
Thisexamplecreatesacircleandthenperformsarectangulararrayofthecircle,creatingfiverowsandfivecolumnsofcircles.
SubCh4_ArrayRectangularExample()
'Createthecircle
DimcircleObjAsAcadCircle
Dimcenter(0To2)AsDouble
DimradiusAsDouble
center(0)=2#:center(1)=2#:center(2)=0#
radius=0.5
SetcircleObj=ThisDrawing.ModelSpace._
AddCircle(center,radius)
ZoomAll
'Definetherectangulararray
DimnumberOfRowsAsLong
DimnumberOfColumnsAsLong
DimnumberOfLevelsAsLong
DimdistanceBwtnRowsAsDouble
DimdistanceBwtnColumnsAsDouble
DimdistanceBwtnLevelsAsDouble
numberOfRows=5
numberOfColumns=5
numberOfLevels=2
distanceBwtnRows=1
distanceBwtnColumns=1
distanceBwtnLevels=1
'Createthearrayofobjects
DimretObjAsVariant
retObj=circleObj.ArrayRectangular_
(numberOfRows,numberOfColumns,numberOfLevels,_
distanceBwtnRows,distanceBwtnColumns,distanceBwtnLevels)
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>
MoveObjects
Youcanmoveobjectsalongavectorwithoutchangingtheirorientationorsize.Youcanalsorotateobjectsaroundabasepoint.
Formoreinformationaboutmovingobjects,see“MoveObjects”intheUser'sGuide.
Topicsinthissection
MoveObjectsAlongaVector
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>MoveObjects>
MoveObjectsAlongaVector
Youcanmovealldrawingobjectsandattributereferenceobjectsalongaspecifiedvector.
Tomoveanobject,usetheMovemethodprovidedforthatobject.Thismethodrequirestwocoordinatesasinput.Thesecoordinatesdefineadisplacementvectorindicatinghowfarthegivenobjectistobemovedandinwhatdirection.
Moveacirclealongavector
ThisexamplecreatesacircleandthenmovesthatcircletwounitsalongtheXaxis.
SubCh4_MoveCircle()
'Createthecircle
DimcircleObjAsAcadCircle
Dimcenter(0To2)AsDouble
DimradiusAsDouble
center(0)=2#:center(1)=2#:center(2)=0#
radius=0.5
SetcircleObj=ThisDrawing.ModelSpace._
AddCircle(center,radius)
ZoomAll
'Definethepointsthatmakeupthemovevector.
'Themovevectorwillmovethecircle2units
'alongthexaxis.
Dimpoint1(0To2)AsDouble
Dimpoint2(0To2)AsDouble
point1(0)=0:point1(1)=0:point1(2)=0
point2(0)=2:point2(1)=0:point2(2)=0
'Movethecircle
circleObj.Movepoint1,point2
circleObj.Update
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>
RotateObjects
Youcanrotatealldrawingobjectsandattributereferenceobjects.
Torotateanobject,usetheRotatemethodprovidedforthatobject.Thismethodrequiresasinputabasepointandarotationangle.Thebasepointisavariantarraywiththreedoubles.Thesedoublesrepresenta3DWCScoordinatespecifyingthepointthroughwhichtheaxisofrotationisdefined.Theangleofrotationisspecifiedinradians.Thisangledetermineshowfaranobjectrotatesaroundthebasepointrelativetoitscurrentlocation.
Formoreinformationaboutrotatingobjects,see“RotateObjects”intheUser'sGuide.
Rotateapolylineaboutabasepoint
Thisexamplecreatesaclosedlightweightpolyline,andthenrotatesthepolyline45degreesaboutthebasepoint(4,4.25,0).
SubCh4_RotatePolyline()
'Createthepolyline
DimplineObjAsAcadLWPolyline
Dimpoints(0To11)AsDouble
points(0)=1:points(1)=2
points(2)=1:points(3)=3
points(4)=2:points(5)=3
points(6)=3:points(7)=3
points(8)=4:points(9)=4
points(10)=4:points(11)=2
SetplineObj=ThisDrawing.ModelSpace._
AddLightWeightPolyline(points)
plineObj.Closed=True
ZoomAll
'Definetherotationof45degreesabouta
'basepointof(4,4.25,0)
DimbasePoint(0To2)AsDouble
DimrotationAngleAsDouble
basePoint(0)=4:basePoint(1)=4.25:basePoint(2)=0
rotationAngle=0.7853981'45degrees
'Rotatethepolyline
plineObj.RotatebasePoint,rotationAngle
plineObj.Update
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>
DeleteObjects
YoucandeleteindividualobjectsbyusingtheDeletemethod.
Note TheCollectionobjectsinActiveXAutomationhaveaDeletemethodduetothemannerinwhichtheseobjectshavebeendefinedinthetypelibrary.However,theCollectionobjects,suchasModelSpacecollection,Layerscollection,andDictionariescollection,shouldneverbedeleted.Anerrorwillresultifyouattempttodeleteacollection.
Createanddeleteapolyline
Thisexamplecreatesalightweightpolyline,thendeletesit.
SubCh4_DeletePolyline()
'Createthepolyline
DimlwpolyObjAsAcadLWPolyline
Dimvertices(0To5)AsDouble
vertices(0)=2:vertices(1)=4
vertices(2)=4:vertices(3)=2
vertices(4)=6:vertices(5)=4
SetlwpolyObj=ThisDrawing.ModelSpace._
AddLightWeightPolyline(vertices)
ZoomAll
'Erasethepolyline
lwpolyObj.Delete
ThisDrawing.RegenacActiveViewport
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>
ScaleObjects
Youscaleanobjectbyspecifyingabasepointandalength,whichisusedasascalefactorbasedonthecurrentdrawingunits.Youcanscaleallthedrawingobjects,aswellasattributereferenceobjects.
Toscaleanobject,usetheScaleEntitymethodprovidedforthatobject.ThismethodscalestheobjectequallyintheX,Y,andZdirections.Ittakesasinputthebasepointforthescaleandascalefactor.Thebasepointisavariantarraywiththreedoubles.Thesedoublesrepresenta3DWCScoordinatespecifyingthepointfromwhichthescalebegins.Thescalefactoristhefactorbywhichtoscaletheobject.Thedimensionsoftheobjectaremultipliedbythescalefactor.Ascalefactorgreaterthan1enlargestheobject.Ascalefactorbetween0and1reducestheobject.
Formoreinformationaboutscaling,see“ResizeorReshapeObjects”intheUser'sGuide.
Scaleapolyline
Thisexamplecreatesaclosedlightweightpolylineandthenscalesthepolylineby0.5.
SubCh4_ScalePolyline()
'Createthepolyline
DimplineObjAsAcadLWPolyline
Dimpoints(0To11)AsDouble
points(0)=1:points(1)=2
points(2)=1:points(3)=3
points(4)=2:points(5)=3
points(6)=3:points(7)=3
points(8)=4:points(9)=4
points(10)=4:points(11)=2
SetplineObj=ThisDrawing.ModelSpace._
AddLightWeightPolyline(points)
plineObj.Closed=True
ZoomAll
'Definethescale
DimbasePoint(0To2)AsDouble
DimscalefactorAsDouble
basePoint(0)=4:basePoint(1)=4.25:basePoint(2)=0
scalefactor=0.5
'Scalethepolyline
plineObj.ScaleEntitybasePoint,scalefactor
plineObj.Update
EndSub
Pleasesendusyourcommentaboutthispage
<$nopage>matrix:
CreateandEditAutoCADEntities>EditObjects>
TransformObjects
Youmove,scale,orrotateanobjectgivena4by4transformationmatrixusingtheTransformBymethod.
Thefollowingtabledemonstratesthetransformationmatrixconfiguration,whereR=RotationandT=Translation:
Transformationmatrixconfiguration
R00 R01 R02 T0
R10 R11 R12 T1
R20 R21 R22 T2
0 0 0 1
Totransformanobject,firstinitializethetransformationmatrix.Thefollowingexampleshowsatransformationmatrix,assignedtothevariabletMatrix,whichwillrotateanentityby90degreesaboutthepoint(0,0,0):
tMatrix(0,0)=0.0
tMatrix(0,1)=-1.0
tMatrix(0,2)=0.0
tMatrix(0,3)=0.0
tMatrix(1,0)=1.0
tMatrix(1,1)=0.0
tMatrix(1,2)=0.0
tMatrix(1,3)=0.0
tMatrix(2,0)=0.0
tMatrix(2,1)=0.0
tMatrix(2,2)=1.0
tMatrix(2,3)=0.0
tMatrix(3,0)=0.0
tMatrix(3,1)=0.0
tMatrix(3,2)=0.0
tMatrix(3,3)=1.0
Afterthetransformationmatrixiscomplete,applythematrixtotheobjectusingtheTransformBymethod.Thefollowinglineofcodedemonstratesapplyingamatrix(tMatrix)toanobject(anObj):
anObj.TransformBytMatrix
Rotatealinewithatransformationmatrix
Thisexamplecreatesalineandrotatesit90degreesusingatransformationmatrix.
SubCh4_TransformBy()
'Createaline
DimlineObjAsAcadLine
DimstartPt(0To2)AsDouble
DimendPt(0To2)AsDouble
startPt(0)=2
startPt(1)=1
startPt(2)=0
endPt(0)=5
endPt(1)=1
endPt(2)=0
SetlineObj=ThisDrawing.ModelSpace._
AddLine(startPt,endPt)
ZoomAll
'InitializethetransMatvariablewitha
'transformationmatrixthatwillrotate
'anobjectby90degreesaboutthepoint(0,0,0)
DimtransMat(0To3,0To3)AsDouble
transMat(0,0)=0#:transMat(0,1)=-1#
transMat(0,2)=0#:transMat(0,3)=0#
transMat(1,0)=1#:transMat(1,1)=0#
transMat(1,2)=0#:transMat(1,3)=0#
transMat(2,0)=0#:transMat(2,1)=0#
transMat(2,2)=1#:transMat(2,3)=0#
transMat(3,0)=0#:transMat(3,1)=0#
transMat(3,2)=0#:transMat(3,3)=1#
'Transformthelineusingthedefinedtransformationmatrix
lineObj.TransformBytransMat
lineObj.Update
EndSub
Thefollowingaremoreexamplesoftransformationmatrices:
RotationMatrix:90degreesaboutpoint(0,0,0)
0.0 -1.0 0.0 0.0
1.0 0.0 0.0 0.0
0.0 0.0 1.0 0.0
0.0 0.0 0.0 1.0
RotationMatrix:45degreesaboutpoint(5,5,0)
0.707107 -0.707107 0.0 5.0
0.707107 0.707107 0.0 -2.071068
0.0 0.0 1.0 0.0
0.0 0.0 0.0 1.0
TranslationMatrix:moveanentityby(10,10,0)
1.0 0.0 0.0 10.0
0.0 1.0 0.0 10.0
0.0 0.0 1.0 0.0
0.0 0.0 0.0 1.0
ScalingMatrix:scaleby10,10atpoint(0,0,0)
10.0 0.0 0.0 0.0
0.0 10.0 0.0 0.0
0.0 0.0 10.0 0.0
0.0 0.0 0.0 1.0
ScalingMatrix:scaleby10,10atpoint(2,2,0)
10.0 0.0 0.0 -18.0
0.0 10.0 0.0 -18.0
0.0 0.0 10.0 0.0
0.0 0.0 0.0 1.0
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>
ExtendandTrimObjects
Youcanchangetheangleofarcsandyoucanchangethelengthofopenlines,arcs,openpolylines,ellipticalarcs,andopensplines.Theresultsaresimilartobothextendingandtrimmingobjects.
Youcanextendortrimanobjectbyeditingitsproperties.Forexample,tolengthenaline,simplychangethecoordinatesoftheStartPointorEndPointproperties.Tochangetheangleofanarc,changetheStartAngleorEndAnglepropertyofthearc.Onceyouhavealteredanobject'spropertyorproperties,usetheUpdatemethodtoseeyourchangesinthedrawing.
Formoreinformationaboutextendingandtrimmingobjects,see“ResizeorReshapeObjects”intheUser'sGuide.
Lengthenaline
Thisexamplecreatesalineandthenchangestheendpointofthatline,resultinginalongerline.
SubCh4_LengthenLine()
'Defineandcreatetheline
DimlineObjAsAcadLine
DimstartPoint(0To2)AsDouble
DimendPoint(0To2)AsDouble
startPoint(0)=0
startPoint(1)=0
startPoint(2)=0
endPoint(0)=1
endPoint(1)=1
endPoint(2)=1
SetlineObj=ThisDrawing.ModelSpace._
AddLine(startPoint,endPoint)
lineObj.Update
'Lengthenthelinebychangingthe
'endpointto4,4,4
endPoint(0)=4
endPoint(1)=4
endPoint(2)=4
lineObj.endPoint=endPoint
lineObj.Update
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>
ExplodeObjects
Explodingobjectsconvertstheobjectsfromsingleobjectstotheirconstituentpartsbuthasnovisibleeffect.Forexample,explodingformssimplelinesandarcsfrom3Dpolygons,polylines,polygonmeshes,andregions.Itreplacesablockreferencewithcopiesofthesimpleobjectsthatcomposetheblock.
Formoreinformationaboutexplodingobjects,see“DisassociateCompoundObjects(Explode)”intheUser'sGuide.
Explodeapolyline
Thisexamplecreatesalightweightpolylineobject.Itthenexplodesthepolylineintoseparateobjects.Theexamplethenloopsthroughtheresultingobjectsanddisplaysamessageboxcontainingthenameofeachobjectanditsindexinthelistofexplodedobjects.
SubCh4_ExplodePolyline()
DimplineObjAsAcadLWPolyline
Dimpoints(0To11)AsDouble
'Definethe2Dpolylinepoints
points(0)=1:points(1)=1
points(2)=1:points(3)=2
points(4)=2:points(5)=2
points(6)=3:points(7)=2
points(8)=4:points(9)=4
points(10)=4:points(11)=1
'CreatealightweightPolylineobject
SetplineObj=ThisDrawing.ModelSpace._
AddLightWeightPolyline(points)
'Setthebulgeononesegmenttovarythe
'typeofobjectsinthepolyline
plineObj.SetBulge3,-0.5
plineObj.Update
'Explodethepolyline
DimexplodedObjectsAsVariant
explodedObjects=plineObj.Explode
'Loopthroughtheexplodedobjects
'anddisplayamessageboxwith
'thetypeofeachobject
DimIAsInteger
ForI=0ToUBound(explodedObjects)
explodedObjects(I).Update
MsgBox"ExplodedObject"&I&":"&_
explodedObjects(I).ObjectName
explodedObjects(I).Update
Next
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>
EditPolylines
2Dand3Dpolylines,rectangles,polygons,and3Dpolygonmeshesareallpolylinevariantsandareeditedinthesameway.
AutoCADrecognizesbothfitpolylinesandspline-fitpolylines.Aspline-fitpolylineusesacurvefit,similartoaB-spline.Therearetwokindsofspline-fitpolylines:quadraticandcubic.BothpolylinesarecontrolledbytheSPLINETYPEsystemvariable.Afitpolylineusesstandardcurvesforcurvefitandutilizesanytangentdirectionssetonanygivenvertex.
Toeditapolyline,usethepropertiesandmethodsoftheLightweightPolylineorPolylineobject.Usethefollowingpropertiesandmethodstoopenorcloseapolyline,changethecoordinatesofapolylinevertex,oraddavertex:
Closedproperty
Opensorclosesthepolyline.
Coordinatesproperty
Specifiesthecoordinatesforeachvertexinthepolyline.
AddVertexmethod
Addsavertextoalightweightpolyline.
Usethefollowingmethodstoupdatethebulgeorwidthofapolyline:
SetBulge
Setsthebulgeofapolyline,giventhesegmentindex.
SetWidth
Setsthestartandendwidthofapolyline,giventhesegmentindex.
Formoreinformationabouteditingpolylines,see“ModifyorJoinPolyline”in
theUser'sGuide.
Editapolyline
Thisexamplecreatesalightweightpolyline.Itthenaddsabulgetothethirdsegmentofthepolyline,appendsavertextothepolyline,changesthewidthofthelastsegment,andfinallyclosesthepolyline.
SubCh4_EditPolyline()
DimplineObjAsAcadLWPolyline
Dimpoints(0To9)AsDouble
'Definethe2Dpolylinepoints
points(0)=1:points(1)=1
points(2)=1:points(3)=2
points(4)=2:points(5)=2
points(6)=3:points(7)=2
points(8)=4:points(9)=4
'CreatealightweightPolylineobject
SetplineObj=ThisDrawing.ModelSpace._
AddLightWeightPolyline(points)
'Addabulgetosegment3
plineObj.SetBulge3,-0.5
'Definethenewvertex
DimnewVertex(0To1)AsDouble
newVertex(0)=4:newVertex(1)=1
'Addthevertextothepolyline
plineObj.AddVertex5,newVertex
'Setthewidthofthenewsegment
plineObj.SetWidth4,0.1,0.5
'Closethepolyline
plineObj.Closed=True
plineObj.Update
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>
EditSplines
Usethefollowingeditablepropertiestochangesplines:
ControlPoints
Specifiesthecontrolpointsofaspline.
EndTangent
Specifiestheendtangentofthesplineasadirectionalvector.
FitPoints
Specifiesallthefitpointsofaspline.
FitTolerance
Refitsthesplinetotheexistingpointswithnewtolerancevalues.
Knots
Specifiestheknotsvectorforthespline.
StartTangent
Specifiesthestarttangentforthespline.
Inaddition,youcanusethefollowingmethodstoeditsplines:
AddFitPoint
Addsasinglefitpointtothesplineatagivenindex.
DeleteFitPoint
Deletesthefitpointofasplineatagivenindex.
ElevateOrder
Elevatestheorderofthesplinetothegivenorder.
GetFitPoint
Getsthefitpointofthesplineatagivenindex.(Getsonefitpointonly.Toqueryallthefitpointsofthespline,usetheFitPointsproperty.)
Reverse
Reversesthedirectionofaspline.
SetControlPoint
Setsthecontrolpointofthesplineatagivenindex.
SetFitPoint
Setsthefitpointofthesplineatagivenindex.(Setsonefitpointonly.Tochangeallthefitpointsofthespline,usetheFitPointsproperty.)
SetWeight
Setstheweightofthecontrolpointatagivenindex.
Usethefollowingread-onlypropertiestoquerysplines:
Area
Getstheenclosedareaofaspline.
Closed
Indicateswhetherthesplineisopenorclosed.
Degree
Getsthedegreeofthespline'spolynomialrepresentation.
IsPeriodic
Specifiesifthegivensplineisperiodic.
IsPlanar
Specifiesifthegivensplineisplanar.
IsRational
Specifiesifthegivensplineisrational.
NumberOfControlPoints
Getsthenumberofcontrolpointsofthespline.
NumberOfFitPoints
Getsthenumberoffitpointsofthespline.
Formoreinformationabouteditingsplines,see“ModifySplines”intheUser'sGuide.
Changeacontrolpointonaspline
Thisexamplecreatesasplineandthenchangesthefirstcontrolpointforthespline.
SubCh4_ChangeSplineControlPoint()
'Createthespline
DimsplineObjAsAcadSpline
DimstartTan(0To2)AsDouble
DimendTan(0To2)AsDouble
DimfitPoints(0To8)AsDouble
startTan(0)=0.5:startTan(1)=0.5:startTan(2)=0
endTan(0)=0.5:endTan(1)=0.5:endTan(2)=0
fitPoints(0)=1:fitPoints(1)=1:fitPoints(2)=0
fitPoints(3)=5:fitPoints(4)=5:fitPoints(5)=0
fitPoints(6)=10:fitPoints(7)=0:fitPoints(8)=0
SetsplineObj=ThisDrawing.ModelSpace._
AddSpline(fitPoints,startTan,endTan)
splineObj.Update
'Changethecoordinateofthefirstfitpoint
DimcontrolPoint(0To2)AsDouble
controlPoint(0)=0
controlPoint(1)=3
controlPoint(2)=0
splineObj.SetControlPoint0,controlPoint
splineObj.Update
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>
EditHatches
Youcaneditbothhatchboundariesandhatchpatterns.Ifyouedittheboundaryofanassociativehatch,thepatternisupdatedaslongastheeditingresultsinavalidboundary.Associativehatchesareupdatedevenifthey'reonlayersthatareturnedoff.Youcanmodifyhatchpatternsorchooseanewpatternforanexistinghatch,butassociativitycanonlybesetwhenahatchiscreated.YoucanchecktoseeifaHatchobjectisassociativebyusingtheAssociativeHatchproperty.(SeetheAddHatchmethodformoreinformationoncreatingahatch.)
Youmustre-evaluateahatchusingtheEvaluatemethodtoseeanyeditstothehatch.
Formoreinformationabouteditinghatches,see“ModifyHatchesandSolid-FilledAreas”intheUser'sGuide.
Topicsinthissection
EditHatchBoundariesEditHatchPatterns
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>EditHatches>
EditHatchBoundaries
Youcanappendorinsertloopsintothehatchboundaries.Associativehatchesareupdatedtomatchanychangesmadetotheirboundaries.Non-associativehatchesarenotupdated.
Toeditahatchboundary,useoneofthefollowingmethods:
AppendInnerLoop
Appendsaninnerlooptothehatch.
AppendOuterLoop
Appendsanouterlooptothehatch.
InsertLoopAt
Insertsaloopatagivenindexofahatch.
Appendaninnerlooptoahatch
Thisexamplecreatesanassociativehatch.Itthencreatesacircleandappendsthecircleasaninnerlooptothehatch.
SubCh4_AppendInnerLoopToHatch()
DimhatchObjAsAcadHatch
DimpatternNameAsString
DimPatternTypeAsLong
DimbAssociativityAsBoolean
'Defineandcreatethehatch
patternName="ANSI31"
PatternType=0
bAssociativity=True
SethatchObj=ThisDrawing.ModelSpace._
AddHatch(PatternType,patternName,bAssociativity)
'Createtheouterloopforthehatch.
DimouterLoop(0To1)AsAcadEntity
Dimcenter(0To2)AsDouble
DimradiusAsDouble
DimstartAngleAsDouble
DimendAngleAsDouble
center(0)=5:center(1)=3:center(2)=0
radius=3
startAngle=0
endAngle=3.141592
SetouterLoop(0)=ThisDrawing.ModelSpace._
AddArc(center,radius,startAngle,endAngle)
SetouterLoop(1)=ThisDrawing.ModelSpace._
AddLine(outerLoop(0).startPoint,outerLoop(0).endPoint)
'Appendtheouterlooptothehatchobject
hatchObj.AppendOuterLoop(outerLoop)
'Createacircleastheinnerloopforthehatch.
DiminnerLoop(0)AsAcadEntity
center(0)=5:center(1)=4.5:center(2)=0
radius=1
SetinnerLoop(0)=ThisDrawing.ModelSpace._
AddCircle(center,radius)
'Appendthecircleasaninnerlooptothehatch
hatchObj.AppendInnerLoop(innerLoop)
'Evaluateanddisplaythehatch
hatchObj.Evaluate
ThisDrawing.RegenTrue
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>EditObjects>EditHatches>
EditHatchPatterns
Youcanchangetheangleorspacingofanexistinghatchpatternorreplaceitwithasolid-filloroneofthepredefinedpatternsthatAutoCADoffers.ThePatternoptionintheBoundaryHatchdialogboxdisplaysalistofthesepatterns.Toreducefilesize,thehatchisdefinedinthedrawingasasinglegraphicobject.
Usethefollowingpropertiesandmethodstoeditthehatchpatterns:
PatternAngle
Specifiestheangleofthehatchpattern.
PatternDouble
Specifiesiftheuser-definedhatchisdouble-hatched.
PatternName
Specifiesthehatchpatternname(doesnotchangethepatterntype).
PatternScale
Specifiesthehatchpatternscale.
PatternSpace
Specifiestheuser-definedhatchpatternspacing.
SetPattern
Setsthepatternnameandpatterntypeforthehatch.
Changethepatternspacingofahatch
Thisexamplecreatesahatch.Itthenaddstwotothecurrentpatternspacingforthehatch.
SubCh4_ChangeHatchPatternSpace()
DimhatchObjAsAcadHatch
DimpatternNameAsString
DimPatternTypeAsLong
DimbAssociativityAsBoolean
'Definethehatch
patternName="ANSI31"
PatternType=0
bAssociativity=True
'CreatetheassociativeHatchobject
SethatchObj=ThisDrawing.ModelSpace._
AddHatch(PatternType,patternName,bAssociativity)
'Createtheouterloopforthehatch.
DimouterLoop(0To0)AsAcadEntity
Dimcenter(0To2)AsDouble
DimradiusAsDouble
center(0)=5
center(1)=3
center(2)=0
radius=3
SetouterLoop(0)=ThisDrawing.ModelSpace._
AddCircle(center,radius)
hatchObj.AppendOuterLoop(outerLoop)
hatchObj.Evaluate
'Changethespacingofthehatchpatternby
'adding2tothecurrentspacing
hatchObj.patternSpace=hatchObj.patternSpace+2
hatchObj.Evaluate
ThisDrawing.RegenTrue
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>
UseLayers,Colors,andLinetypes
Layersareliketransparentoverlaysonwhichyouorganizeandgroupdifferentkindsofdrawinginformation.Theobjectsyoucreatehavepropertiesincludinglayers,colors,andlinetypes.Colorhelpsyoudistinguishsimilarelementsinyourdrawings,andlinetypeshelpyoudifferentiateeasilybetweendifferentdraftingelements,suchascenterlinesorhiddenlines.Organizinglayersandobjectsonlayersmakesiteasiertomanagetheinformationinyourdrawings.
Formoreinformationaboutthistopic,see“ControlthePropertiesofObjects”intheUser'sGuide.
Topicsinthissection
WorkwithLayersWorkwithColorsWorkwithLinetypesAssignLayers,Colors,andLinetypestoObjects
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>
WorkwithLayers
Youarealwaysdrawingonalayer.Itmaybethedefaultlayeroralayeryoucreateandnameyourself.Eachlayerhasanassociatedcolorandlinetype.Forexample,youcancreatealayeronwhichyoudrawonlycenterlinesandassignthecolorblueandthelinetypeCENTERtothatlayer.Then,wheneveryouwanttodrawcenterlinesyoucanswitchtothatlayerandstartdrawing.
AlllayersandlinetypesarekeptwithintheirparentCollectionobjects.LayersarekeptwithintheLayerscollection,andlinetypesarekeptwithintheLinetypescollection.
Formoreinformationaboutworkingwithlayers,see“WorkwithLayers”intheUser'sGuide.
Topicsinthissection
SortLayersandLinetypesCreateandNameLayersMakeaLayerActiveTurnLayersOnandOffFreezeandThawLayersLockandUnlockLayersAssignColortoaLayerAssignaLinetypetoaLayerDeleteLayers
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>WorkwithLayers>
SortLayersandLinetypes
YoucaniteratethroughtheLayersandLinetypescollectionstofindallthelayersandlinetypesinadrawing.
IteratethroughtheLayerscollection
ThefollowingcodeiteratesthroughtheLayerscollectiontogatherthenamesofallthelayersinthedrawing.Thenamesarethendisplayedinamessagebox.
SubCh4_IteratingLayers()
DimlayerNamesAsString
DimentryAsAcadLayer
layerNames=""
ForEachentryInThisDrawing.Layers
layerNames=layerNames+entry.Name+vbCrLf
Next
MsgBox"Thelayersinthisdrawingare:"+_
vbCrLf+layerNames
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>WorkwithLayers>
CreateandNameLayers
Youcancreatenewlayersandassigncolorandlinetypepropertiestothoselayers.EachindividuallayerispartoftheLayerscollection.UsetheAddmethodtocreateanewlayerandaddittotheLayerscollection.
Youcanassignanametoalayerwhenitiscreated.Tochangethenameofalayerafterithasbeencreated,usetheNameproperty.Layernamescanincludeuptothirty-onecharactersandcontainletters,digits,andthespecialcharactersdollarsign($),hyphen(-),andunderscore(_)butcannotincludeblankspaces.
Formoreinformationaboutcreatinglayers,see“CreateandNameLayers”intheUser'sGuide.
Createanewlayer,assignitthecolorred,andaddanobjecttothelayer
Thefollowingcodecreatesacircleandanewlayer.Thenewlayerisassignedthecolorred.Thecircleisassignedtothelayer,andthecolorofthecirclechangesaccordingly.
SubCh4_NewLayer()
'Createacircle
DimcircleObjAsAcadCircle
Dimcenter(0To2)AsDouble
DimradiusAsDouble
center(0)=2:center(1)=2:center(2)=0
radius=1
SetcircleObj=ThisDrawing.ModelSpace._
AddCircle(center,radius)
'Createacolorobject
DimcolAsNewAcadAcCmColor
col.ColorMethod=AutoCAD.acColorMethodForeground
'Setthelayertothecolor
DimlayColorAsAcadAcCmColor
SetlayColor=
AcadApplication.GetInterfaceObject("AutoCAD.AcCmColor.17")
CalllayColor.SetRGB(122,199,25)
ThisDrawing.ActiveLayer.TrueColor=layColor
col.ColorMethod=AutoCAD.acColorMethodByLayer
'Assignthecirclethecolor"ByLayer"so
'thatthecirclewillautomaticallypick
'upthecolorofthelayeronwhichitresides
circleObj.Color=acByLayer
circleObj.Update
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>WorkwithLayers>
MakeaLayerActive
Youarealwaysdrawingontheactivelayer.Whenyoumakealayeractive,youcancreatenewobjectsonthatlayer.Ifyoumakeadifferentlayeractive,anynewobjectsyoucreatearecreatedonthatnewactivelayeranduseitscolorandlinetype.Youcannotmakealayeractiveifitisfrozen.
Tomakealayeractive,usetheActiveLayerproperty.Thispropertyissetonthecurrentdrawing.Forexample:
DimnewlayerAsAcadLayer
Setnewlayer=ThisDrawing.Layers.Add("LAYER1")
ThisDrawing.ActiveLayer=newlayer
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>WorkwithLayers>
TurnLayersOnandOff
Turned-offlayersareregeneratedwiththedrawingbutarenotdisplayedorplotted.Byturninglayersoff,youavoidregeneratingthedrawingeverytimeyouthawalayer.Whenyouturnalayeronthathasbeenturnedoff,AutoCADredrawstheobjectsonthatlayer.
Toturnlayersonandoff,usetheLayerOnproperty.IfyouinputavalueofTRUEtothisproperty,thelayeristurnedon.IfyouinputavalueofFALSE,thelayeristurnedoff.
Turnoffalayer
Thisexamplecreatesanewlayer,addsacircletothelayer,thenturnsoffthelayersothatthecircleisnolongervisible.
SubCh4_LayerInvisible()
'Createacircle
DimcircleObjAsAcadCircle
Dimcenter(0To2)AsDouble
DimradiusAsDouble
center(0)=2:center(1)=2:center(2)=0
radius=1
SetcircleObj=ThisDrawing.ModelSpace._
AddCircle(center,radius)
'Createanewlayercalled"ABC"
DimlayerObjAsAcadLayer
SetlayerObj=ThisDrawing.Layers.Add("ABC")
'Assignthecircletothe"ABC"layer
circleObj.Layer="ABC"
circleObj.Update
'Turnofflayer"ABC"
layerObj.LayerOn=False
ThisDrawing.RegenacActiveViewport
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>WorkwithLayers>
FreezeandThawLayers
Youcanfreezelayerstospeedupdisplaychanges,improveobjectselectionperformance,andreduceregenerationtimeforcomplexdrawings.AutoCADdoesnotdisplay,plot,orregenerateobjectsonfrozenlayers.Freezelayersthatyouwanttobeinvisibleforlongperiods.Whenyou“thaw”afrozenlayer,AutoCADregeneratesanddisplaystheobjectsonthatlayer.
Tofreezeorthawalayer,usetheFreezeproperty.IfyouinputavalueofTRUEtothisproperty,thelayerisfrozen.IfyouinputavalueofFALSE,thelayeristhawed.
Freezealayer
Thisexamplecreatesanewlayercalled“ABC”andthenfreezesthelayer.
SubCh4_LayerFreeze()
'Createanewlayercalled"ABC"
DimlayerObjAsAcadLayer
SetlayerObj=ThisDrawing.Layers.Add("ABC")
'Freezelayer"ABC"
layerObj.Freeze=True
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>WorkwithLayers>
LockandUnlockLayers
Youcannotedittheobjectsonalockedlayer;however,theyarestillvisibleifthelayerisonandthawed.Youcanmakealockedlayercurrentandyoucanaddobjectstoit.Youcanfreezeandturnofflockedlayersandchangetheirassociatedcolorsandlinetypes.
Tolockorunlockalayer,usetheLockproperty.IfyouinputavalueofTRUEtothisproperty,thelayerislocked.IfyouinputavalueofFALSE,thelayerisunlocked.
Lockalayer
Thisexamplecreatesanewlayercalled“ABC”andthenlocksthelayer.
SubCh4_LayerLock()
'Createanewlayercalled"ABC"
DimlayerObjAsAcadLayer
SetlayerObj=ThisDrawing.Layers.Add("ABC")
'Locklayer"ABC"
layerObj.Lock=True
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>WorkwithLayers>
AssignColortoaLayer
Youcanassigncolortoalayer.ColorsareidentifiedbytheAcCmColorobject.ThisobjectcanholdanRGBvalue,anACInumber(anintegerfrom1to255),oranamedcolor.
Toassigncolortoalayer,usetheTrueColorproperty.
ConstantshavebeenprovidedforthestandardsevencolorsandtheBYBLOCKandBYLAYERdesignations.
IfyouuseacByBlock,AutoCADdrawsnewobjectsinthedefaultcolor(whiteorblack,dependingonyourconfiguration)untiltheyaregroupedintotheblock.Whentheblockisinsertedinthedrawing,theobjectsintheblockinheritthecurrentsetting.
IfyouuseacByLayer,newobjectsassumethecolorofthelayeruponwhichtheyaredrawn.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>WorkwithLayers>
AssignaLinetypetoaLayer
Whenyou'redefininglayers,linetypesprovideanotherwaytoconveyvisualinformation.Alinetypeisarepeatingpatternofdashes,dots,andblankspacesyoucanusetodistinguishthepurposeofonelinefromanother.
Thelinetypenameanddefinitiondescribetheparticulardash-dotsequence,therelativelengthsofdashesandblankspaces,andthecharacteristicsofanyincludedtextorshapes.
Toassignalinetypetoalayer,usetheLinetypeproperty.Thispropertytakesthenameofthelinetypeasinput.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>WorkwithLayers>
DeleteLayers
Todeletealayer,usetheDeletemethod.
Youcandeletealayeratanytimeduringadrawingsession.Youcannotdeletethecurrentlayer,layer0,anxref-dependentlayer,oralayerthatcontainsobjects.
Note Layersreferencedbyblockdefinitions,alongwiththespeciallayernamedDEFPOINTS,cannotbedeletedeveniftheydonotcontainvisibleobjects.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>
WorkwithColors
YoucanassigntruecolorstoindividualobjectsinadrawingusingtheAcCmColorobject.UsinganRGBvalueintheAcCmColorobject,youcanchoosefrommillionsofcolorswhenyousetthecoloroflines,circles,andotherindividualobjects.TheAcCmColorobjectalsocontainsmethodsandpropertiesforspecifyingcolornames,colorbooks,colorindexes,colorvalues,andcolormethods.
Youcanalsoassigncolorstolayers.EachcolorcanbeidentifiedbyanameoranAutoCADColorIndex(ACI)number,anintegerfrom1through255.Anynumberofobjectsandlayerscanhavethesamecolornumber.Youcanassigneachcolornumbertoadifferentpenonapenplotterorusethecolornumberstoidentifycertainobjectsinthedrawing,eventhoughyoucannotseethecolorsonyourscreen.
Whenspecifyingacolor,youcanenterthenameofthecolororitsACInumber.TheACIprovides255colornumbers.Standardcolornamesareavailableonlyforcolors1through7.
Colors1through7
Colornumber Colorname
1 Red
2 Yellow
3 Green
4 Cyan
5 Blue
6 Magenta
7 Black/White
Colors8through255mustbeassignedbyanumberorbyselectingthecolorinadialogbox.Thedefaultcolor(7)iseitherwhiteorblack,dependingonyourbackgroundcolor.
Formoreinformationaboutworkingwithcolors,see“WorkwithColors”intheUser'sGuide.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>
WorkwithLinetypes
Alinetypeisarepeatingpatternofdashes,dots,andblankspaces.Acomplexlinetypeisarepeatingpatternofsymbols.Tousealinetypeyoumustfirstloaditintoyourdrawing.AlinetypedefinitionmustexistinaLINlibraryfilebeforealinetypecanbeloadedintoadrawing.Toloadalinetypeintoyourdrawing,usetheLoadmethod.
Formoreinformationaboutworkingwithlinetypes,see“OverviewofLinetypes”intheUser'sGuide.
Note ThelinetypesusedinternallybyAutoCADshouldnotbeconfusedwiththehardwarelinetypesprovidedbysomeplotters.Thetwotypesofdashedlinesproducesimilarresults.Donotusebothtypesatthesametime,however,becausetheresultscanbeunpredictable.
LoadalinetypeintoAutoCAD
Thisexampleattemptstoloadthelinetype“CENTER”fromtheacad.linfile.Ifthelinetypealreadyexists,orthefiledoesnotexist,thenamessageisdisplayed.
SubCh4_LoadLinetype()
OnErrorGoToERRORHANDLER
DimlinetypeNameAsString
linetypeName="CENTER"
'Load"CENTER"linetypefromacad.linfile
ThisDrawing.Linetypes.LoadlinetypeName,"acad.lin"
ExitSub
ERRORHANDLER:
MsgBoxErr.Description
EndSub
Topicsinthissection
MakeaLinetypeActive
RenameLinetypesDeleteLinetypesChangeLinetypeDescriptionsSpecifyLinetypeScale
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>WorkwithLinetypes>
MakeaLinetypeActive
Tousealinetypetodrawonthecurrentlayer,youmustmakeitactive.Allnewlycreatedobjectsaredrawnusingtheactivelinetype.
Note Xref-dependentlinetypescannotbemadeactive.
Tomakealinetypeactive,usetheActiveLinetypeproperty.Thispropertyissetonthecurrentdrawing.Forexample:
ThisDrawing.ActiveLinetype=ThisDrawing._
Linetypes.Item("CONTINUOUS")
Formoreinformationaboutactivatingalinetype,see“SettheCurrentLinetype”intheUser'sGuide.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>WorkwithLinetypes>
RenameLinetypes
Torenamealinetype,usetheNameproperty.Whenyourenamealinetype,youarerenamingonlythelinetypedefinitioninyourdrawing.ThenameintheLINlibraryfileisnotbeingupdatedtoreflectthenewname.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>WorkwithLinetypes>
DeleteLinetypes
Todeletealinetype,usetheDeletemethod.Youcandeletealinetypeatanytimeduringadrawingsession;however,linetypesthatcannotbedeletedincludeBYLAYER,BYBLOCK,CONTINUOUS,thecurrentlinetype,andxref-dependentlinetypes.Also,linetypesreferencedbyblockdefinitionscannotbedeleted,eveniftheyarenotusedbyanyobjects.
Formoreinformationaboutdeletinglinetypes,see“SettheCurrentLinetype”intheUser'sGuide.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>WorkwithLinetypes>
ChangeLinetypeDescriptions
Linetypescanhaveadescriptionassociatedwiththem.ThedescriptionprovidesanASCIIrepresentationofthelinetype.YoucanassignorchangealinetypedescriptionbyusingtheDescriptionproperty.
Alinetypedescriptioncanhaveupto47characters.Thedescriptioncanbeacommentoraseriesofunderscores,dots,dashes,andspacestoshowasimplerepresentationofthelinetypepattern.Forexample:
ThisDrawing.ActiveLinetype.Description="ExteriorWall"
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>WorkwithLinetypes>
SpecifyLinetypeScale
Youcanspecifythelinetypescaleforobjectsyoucreate.Thesmallerthescale,themorerepetitionsofthepatternaregeneratedperdrawingunit.Bydefault,AutoCADusesagloballinetypescaleof1.0,whichisequaltoonedrawingunit.Youcanchangethelinetypescaleforalldrawingobjects,attributereferences,andgroups.
Tochangethelinetypescale,usetheLinetypeScaleproperty.
TheCELTSCALEsystemvariablesetsthelinetypescalefornewlycreatedobjects.LTSCALEgloballychangesthelinetypescaleofexistingobjectsaswellasnewobjects.TochangethevaluesofsystemvariablesusingAutoCADActiveXAutomation,usetheSetVariablemethod.
Formoreinformationaboutlinetypescales,see“ControlLinetypeScale”intheUser'sGuide.
Changethelinetypescaleforacircle
SubCh4_ChangeLinetypeScale()
'Savethecurrentlinetype
SetcurrLineType=ThisDrawing.ActiveLinetype
'ChangetheactivelinetypetoBorder,sothescalechangewill
'bevisible.
'FirstseeiftheBorderlinetypeisalreadyloaded
OnErrorResumeNext'Turnonerrortrapping
ThisDrawing.ActiveLinetype=ThisDrawing.Linetypes.Item("BORDER")
IfErr.Number=-2145386476Then
'Errorindicateslinetypeisnotcurrentlyloaded,soloadit.
ThisDrawing.Linetypes.Load"BORDER","acad.lin"
ThisDrawing.ActiveLinetype=_
ThisDrawing.Linetypes.Item("BORDER")
EndIf
OnErrorGoTo0'Turnofferrortrapping
'Createacircleobjectinmodelspace
Dimcenter(0To2)AsDouble
DimradiusAsDouble
DimcircleObjAsAcadCircle
center(0)=2
center(1)=2
center(2)=0
radius=4
SetcircleObj=ThisDrawing.ModelSpace.AddCircle(center,radius)
circleObj.Update
MsgBox("Hereisthecirclewiththeoriginallinetype")
'Setthelinetypescaleofacircleto3
circleObj.LinetypeScale=3#
circleObj.Update
MsgBox("Hereisthecirclewiththenewlinetype")
'Restoreoriginalactivelinetype
ThisDrawing.ActiveLinetype=currLineType
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>
AssignLayers,Colors,andLinetypestoObjects
Onceyou'vedefinedlayers,colors,andlinetypes,youcanassignthemtoobjectsinyourdrawing.Youcangroupassociatedcomponentsofadrawingbyassigningobjectstolayers.Youcancontrollayervisibility,color,andlinetypeandspecifywhetherobjectsonalayercanbeedited.Youcanmoveobjectsfromonelayertoanotherandchangethenameofalayer.
Thenumberoflayersinadrawingandthenumberofobjectsperlayerarevirtuallyunlimited.Youcanassignanametoeachlayerandselectanycombinationoflayersfordisplay.
Youcandefineblocksfromobjectsthatwereoriginallydrawnondifferentlayerswithdifferentcolorsandlinetypes.Youcanpreservethelayer,color,andlinetypeinformationofobjectsinablock.Then,eachtimeyouinserttheblock,youhaveeachobjectdrawnonitsoriginallayerwithitsoriginalcolorandlinetype.
Topicsinthissection
ChangeanObject'sLayerChangeanObject'sColorChangeanObject'sLinetype
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>AssignLayers,Colors,andLinetypestoObjects>
ChangeanObject'sLayer
Onceyouhavecreatedanobjectandassignedlayer,color,andlinetypepropertiestoit,youmaywishtochangetheobject'slayer.Changinganobject'slayerisusefulifyouaccidentallycreateanobjectonthewronglayerordecidetochangeyourlayerorganizationlater.
Tochangeanobject'slayer,usetheLayerpropertyprovidedforthatobject.TheLayerpropertytakesthenameofthelayerasinput.
Moveanobjecttoadifferentlayer
Thisexamplecreatesacircleontheactivelayerandthencreatesanewlayercalled“ABC”.Itthenmovesthecircletothenewlayer.
SubCh4_MoveObjectNewLayer()
'Createacircle
DimcircleObjAsAcadCircle
Dimcenter(0To2)AsDouble
DimradiusAsDouble
center(0)=2:center(1)=2:center(2)=0
radius=1
SetcircleObj=ThisDrawing.ModelSpace._
AddCircle(center,radius)
'Createanewlayercalled"ABC"
DimlayerObjAsAcadLayer
SetlayerObj=ThisDrawing.Layers.Add("ABC")
'Assignthecircletothe"ABC"layer
circleObj.Layer="ABC"
circleObj.Update
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>AssignLayers,Colors,andLinetypestoObjects>
ChangeanObject'sColor
Tochangeanobject'scolor,usetheTrueColorpropertyprovidedforthatobject.Youcanassigncolorstoindividualobjectsinadrawing.EachcolorisidentifiedbyanAcCmColorobject.ThisobjectcanholdanRGBvalue,anACInumber(anintegerfrom1to255),oranamedcolor.UsinganRGBvalue,youcanchoosefrommillionsofcolors.
Settingacolorfortheobjectoverridesthecolorsettingforthelayeronwhichtheobjectresides.Ifyouwanttoretainanobjectonaspecificlayerbutyoudon'twantittokeepthecolorofthatlayer,youcanchangetheobject'scolor.
Changethecolorofacircle
Thisexamplecreatesacircleandthencolorsthecircleblue.
SubCh4_ColorCircle()
DimcolorAsAcadAcCmColor
Setcolor=_
AcadApplication.GetInterfaceObject("AutoCAD.AcCmColor.17")
Callcolor.SetRGB(80,100,244)
DimcircleObjAsAcadCircle
DimcenterPoint(0To2)AsDouble
DimradiusAsDouble
centerPoint(0)=0#:centerPoint(1)=0#:centerPoint(2)=0#
radius=5#
SetcircleObj=_
ThisDrawing.ModelSpace.AddCircle(centerPoint,radius)
circleObj.TrueColor=color
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>UseLayers,Colors,andLinetypes>AssignLayers,Colors,andLinetypestoObjects>
ChangeanObject'sLinetype
Bydefault,objectsinheritthelinetypeofthelayeronwhichtheyarecreated.Tochangeanobject'slinetype,usetheLinetypepropertyprovidedforthatobject.TheLinetypepropertytakesthenameofthelinetypetoassigntotheobjectasinput.
Note Beforeyoucanassignalinetypetoanobject,thelinetypemustbeloadedintothecurrentdrawing.Toloadalinetypeintothedrawing,usetheLoadmethod.
Formoreinformationaboutlinetypes,see“OverviewofLinetypes”intheUser'sGuide.
Changethelinetypeofacircle
Thisexamplecreatesacircle.Itthenattemptstoloadthelinetype“CENTER”fromtheacad.linfile.Ifthelinetypealreadyexists,orthefiledoesnotexist,thenamessageisdisplayed.Finally,itsetsthelinetypeforthecircletobe“CENTER.”
SubCh4_ChangeCircleLinetype()
OnErrorResumeNext
'Createacircle
DimcircleObjAsAcadCircle
Dimcenter(0To2)AsDouble
DimradiusAsDouble
center(0)=2:center(1)=2:center(2)=0
radius=1
SetcircleObj=ThisDrawing.ModelSpace._
AddCircle(center,radius)
DimlinetypeNameAsString
linetypeName="CENTER"
'Load"CENTER"linetypefromacad.linfile
ThisDrawing.Linetypes.LoadlinetypeName,"acad.lin"
IfErr.Description<>""ThenMsgBoxErr.Description
'Assignthecirclethelinetype"CENTER"
circleObj.Linetype="CENTER"
circleObj.Update
EndSub
Pleasesendusyourcommentaboutthispage
<$nopage>layerproperties,saving.<$endrange>layersettings:storing,layersettings:saving:examplecode,layersettings:renamingsavedsettings:examplecode,layersettings:deletingsavedsettings:examplecode,layersettings:restoringsavedsettings,layersettings:restoringsavedsettings:examplecode,layersettings:exportingsavedsettings,layersettings:importingsavedsettings,Exportmethod:forsavedlayersettings,Importmethod:forsavedlayersettings,layersettings:exportingsavedsettings:examplecode,layersettings:importingsavedsettings:examplecode,">
CreateandEditAutoCADEntities>
SaveandRestoreLayerSettings
Youcansavelayersettingsinadrawingandrestorethemlater.Thismakesiteasytoreturntospecifiedsettingsforalllayersduringdifferentstageswhencompletingadrawingorwhenplottingadrawing.
Layersettingsincludewhetherornotalayeristurnedon,frozen,locked,plotted,andautomaticallyfrozeninnewviewports,andthelayer'scolor,linetype,lineweight,andplotstyle.Youcanspecifywhichsettingsyouwanttosave,andyoucansavedifferentgroupsofsettingsforadrawing.
Aspecialobject,theLayerStateManager,providesfunctionsforworkingwithlayersettingsusingActiveX.
Formoreinformationaboutsavinglayersettings,see“SaveandRestoreLayerSettings”intheUser'sGuide.
Topicsinthissection
UnderstandHowAutoCADSavesLayerSettingsUsetheLayerStateManagertoManageLayerSettings
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>SaveandRestoreLayerSettings>
UnderstandHowAutoCADSavesLayerSettings
AutoCADsaveslayersettinginformationinanextensiondictionaryinadrawing'sLayerscollection.Whenyoufirstsavelayersettingsinadrawing,AutoCADdoesthefollowing:
CreatesanextensiondictionaryintheLayerscollection.
CreatesaDictionaryobjectnamedACAD_LAYERSTATEintheextensiondictionary.
StoresthepropertiesofeachlayerinthedrawinginanXRecordobjectintheACAD_LAYERSTATEdictionary.AutoCADstoresalllayersettingsintheXRecord,butidentifiesthespecificsettingsyouchosetosave.Whenyourestorethelayersettings,AutoCADrestoresonlythesettingsyouchosetosave.
Eachtimeyousaveanotherlayersettinginthedrawing,AutoCADcreatesanotherXRecordobjectdescribingthesavedsettingsandstorestheXRecordintheACAD_LAYERSTATEdictionary.Thefollowingdiagramillustratestheprocess.
Youdonotneed(andshouldnottry)tointerpretXRecordswhenworkingwithlayersettingsusingActiveX.UsethefunctionsoftheLayerStateManagerobjecttoaccesssavedlayersettings.
Listthesavedlayersettingsinadrawing
Iflayersettingshavebeensavedinthecurrentdrawing,thefollowingcodeliststhenamesofallsavedlayersettings:
SubCh4_ListStates()
OnErrorResumeNext
DimoLSMDictAsAcadDictionary
DimXRecAsObject
DimlayerstateNamesAsString
layerstateNames=""
'GettheACAD_LAYERSTATESdictionary,whichisinthe
'extensiondictionaryintheLayersobject.
SetoLSMDict=ThisDrawing.Layers._
GetExtensionDictionary.Item("ACAD_LAYERSTATES")
'Listthenameofeachsavedlayersetting.Settingsare
'storedasXRecordsinthedictionary.
ForEachXRecInoLSMDict
layerstateNames=layerstateNames+XRec.Name+vbCrLf
NextXRec
MsgBox"Thesavedlayersettingsinthisdrawingare:"+_
vbCrLf+layerstateNames
EndSub
Pleasesendusyourcommentaboutthispage
<$endrange>layersettings:storing,layersettings:saving:examplecode,layersettings:renamingsavedsettings:examplecode,layersettings:deletingsavedsettings:examplecode,layersettings:restoringsavedsettings,layersettings:restoringsavedsettings:examplecode,layersettings:exportingsavedsettings,layersettings:importingsavedsettings,Exportmethod:forsavedlayersettings,Importmethod:forsavedlayersettings,layersettings:exportingsavedsettings:examplecode,layersettings:importingsavedsettings:examplecode,">
CreateandEditAutoCADEntities>SaveandRestoreLayerSettings>
UsetheLayerStateManagertoManageLayerSettings
TheLayerStateManagerobjectissimilartotheAutoCADUtilityobjectinthatitprovidesasetoffunctionsformanipulatingdata.Thesefunctionsaremethodsforworkingwithsavedlayersettings.UsethefollowingLayerStateManagermethodstoworkwithsavedlayersettings:
Delete
Deletesasavedlayersetting.
Export
Exportsthespecifiedsavedlayersettingtoafile.
Import
Importsasavedlayersettingfromthespecifiedfile.
Rename
Renamesasavedlayersetting.
Restore
Restoresthespecifiedlayersettinginthecurrentdrawing.
Save
Savesthespecifiedlayerstatesandproperties.
SetDataBase
AssociatesanAutoCADdatabasewiththeLayerStateManager.
ToaccesstheLayerStateManagerobject,usetheGetInterfaceObjectmethod.
DimoLSMAsAcadLayerStateManager
SetoLSM=ThisDrawing.Application._
GetInterfaceObject("AutoCAD.AcadLayerStateManager.17")
AfteryouretrievetheLayerStateManagerobject,youmustassociateadatabasewithitbeforeyoucanaccesstheobject'smethods.UsetheSetDatabasemethodtoassociateadatabasewiththeLayerStateManager.
oLSM.SetDatabaseThisDrawing.Database
Topicsinthissection
SaveLayerSettingsRestoreLayerSettingsExportandImportSavedLayerSettings
Pleasesendusyourcommentaboutthispage
<$endrange>layersettings:storing,layersettings:saving:examplecode,layersettings:renamingsavedsettings:examplecode,layersettings:deletingsavedsettings:examplecode,">
CreateandEditAutoCADEntities>SaveandRestoreLayerSettings>UsetheLayerStateManagertoManageLayerSettings>
SaveLayerSettings
UsetheSavemethodtosaveasetoflayersettingsinadrawing.TheSavemethodacceptstwoparameters.Thefirstparameterisastringnamingthelayersettingsyouaresaving.Thesecondparameteridentifiesthelayerpropertiesyouwanttosave.Usetheconstantsinthefollowingtabletoidentifylayerproperties.
Constantsforlayerproperties
Constantname Layerproperty
acLsAll Alllayersettings
acLsColor Color
acLsFrozen Frozenorthawed
acLsLineType Linetype
acLsLineWeight Lineweight
acLsLocked Lockedorunlocked
acLsNewViewport Newviewportlayersfrozenorthawed
acLsNone None
acLsOn Onoroff
acLsPlot Plottingonoroff
acLsPlotStyle Plotstyle
Addtheconstantstogethertospecifymultipleproperties.
Ifyoutrytosavelayersettingsunderanamethatalreadyexists,anerrorisreturned.Youmustrenameordeletetheexistingsavedlayersettingsbeforeyoucanreusethename.
Savealayer'scolorandlinetypesettings
ThefollowingcodesavesthecolorandlinetypesettingsofthecurrentlayerunderthenameColorLinetype.
SubCh4_SaveLayerColorAndLinetype()
DimoLSMAsAcadLayerStateManager
'AccesstheLayerStateManagerobject
SetoLSM=ThisDrawing.Application._
GetInterfaceObject("AutoCAD.AcadLayerStateManager.17")
'AssociatethecurrentdrawingdatabasewithLayerStateManager
oLSM.SetDatabaseThisDrawing.Database
oLSM.Save"ColorLinetype",acLsColor+acLsLineType
EndSub
Renameasavedlayersetting
ThefollowingcoderenamestheColorLinetypelayersettingstoOldColorLinetype.
SubCh4_RenameLayerSettings()
DimoLSMAsAcadLayerStateManager
SetoLSM=ThisDrawing.Application._
GetInterfaceObject("AutoCAD.AcadLayerStateManager.17")
oLSM.SetDatabaseThisDrawing.Database
oLSM.Rename"ColorLinetype","OldColorLinetype"
EndSub
Deleteasavedlayersetting
ThefollowingcodedeleteslayersettingsthatweresavedunderthenameColorLinetype.
SubCh4_DeleteColorAndLinetype()
DimoLSMAsAcadLayerStateManager
SetoLSM=ThisDrawing.Application._
GetInterfaceObject("AutoCAD.AcadLayerStateManager.17")
oLSM.SetDatabaseThisDrawing.Database
oLSM.Delete"ColorLinetype"
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>SaveandRestoreLayerSettings>UsetheLayerStateManagertoManageLayerSettings>
RestoreLayerSettings
TheRestoremethodresetsalllayersettingsinthecurrentdrawingtovaluesthatweresavedearlier.Forexample,ifyousavethedrawing'scolorandlinetypesettingsunderthename“ColorLinetype”andsubsequentlychangethosesettings,restoring“ColorLinetype”resetsthelayerstothecolorsandlinetypestheyhadwhen“ColorLinetype”wassaved.Ifyouaddnewlayerstothedrawingaftersaving“ColorLinetype,”thosenewlayersarenotaffectedwhenyourestore“ColorLinetype.”
Restorethecolorandlinetypesettingsofadrawing'slayers
Assumingthatthecolorandlinetypesettingsofthelayersinthecurrentdrawingwerepreviouslysavedunderthename“ColorLinetype,”thefollowingcoderesetsthecolorandlinetypesettingsofeachlayerinthedrawingtothevaluetheyhadwhen“ColorLinetype”wassaved.
SubCh4_RestoreLayerSettings()
DimoLSMAsAcadLayerStateManager
SetoLSM=ThisDrawing.Application._
GetInterfaceObject("AutoCAD.AcadLayerStateManager.17")
oLSM.SetDatabaseThisDrawing.Database
oLSM.Restore"ColorLinetype"
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>SaveandRestoreLayerSettings>UsetheLayerStateManagertoManageLayerSettings>
ExportandImportSavedLayerSettings
Youcanexportandimportsavedlayersettingstousethosesettingsinotherdrawings.UsetheLayerStateManager'sExportmethodtosavelayersettingstoafile;usetheImportmethodtoimportsavedlayersettingsintoadrawing.
Note Importinglayersettingsdoesnotrestorethem;youmustusetheRestoremethodtosetthelayersinyourdrawingtotheimportedsettings.
TheExportmethodacceptstwoparameters.Thefirstparameterisastringidentifyingthesavedlayersettingsyouareexporting.Thesecondparameteristhenameofthefileyouareexportingthesettingsto.Ifyoudonotspecifyapathforthefile,itissavedintheAutoCADinstallationdirectory.Ifthefilenameyouspecifiedalreadyexists,theexistingfileisoverwritten.Usea.lasextensionwhennamingfiles;thisistheextensionAutoCADrecognizesforexportedlayersettingfiles.
TheImportmethodacceptsoneparameter:astringnamingthefilethatcontainsthelayersettingsyouareimporting.
Whenyouareimportinglayersettings,anerrorconditionisraisedifanypropertiesreferencedinthesavedsettingsarenotavailableinthedrawingyou'reimportingto.Theimportiscompleted,however,anddefaultpropertiesareused.Forexample,ifanexportedlayerissettoalinetypethatisnotloadedinthedrawingitisbeingimportedinto,anerrorconditionisraisedandthedrawing'sdefaultlinetypeissubstituted.Yourcodeshouldaccountforthiserrorconditionandcontinueprocessingifitisraised.
Iftheimportedfiledefinessettingsforlayersthatdonotexistinthecurrentdrawing,thoselayersarecreatedinthecurrentdrawing.WhenyouusetheRestoremethod,thepropertiesspecifiedwhenthesettingsweresavedareassignedtothenewlayers;allotherpropertiesofthenewlayersareassigneddefaultsettings.
Exportsavedlayersettings
ThefollowingcodeexportssavedlayersettingstoafilenamedColortype.las.
SubCh4_ExportLayerSettings()
DimoLSMAsAcadLayerStateManager
SetoLSM=ThisDrawing.Application._
GetInterfaceObject("AutoCAD.AcadLayerStateManager.17")
oLSM.SetDatabaseThisDrawing.Database
oLSM.Export"ColorLinetype","c:\mydocuments\ColorLType.las"
EndSub
Importsavedlayersettings
ThefollowingcodeimportslayersettingsfromafilenamedColortype.las.
SubCh4_ImportLayerSettings()
DimoLSMAsAcadLayerStateManager
SetoLSM=ThisDrawing.Application._
GetInterfaceObject("AutoCAD.AcadLayerStateManager.17")
oLSM.SetDatabaseThisDrawing.Database
'Ifthedrawingyou'reimportingtodoesnotcontain
'allthelinetypesreferencedinthesavedsettings,
'anerrorisreturned.Theimportiscompleted,though,
'andthedefaultlinetypeisused.
OnErrorResumeNext
oLSM.Import"c:\mydocuments\ColorLType.las"
IfErr.Number=-2145386359Then
'Errorindicatesalinetypeisnotdefined
MsgBox("Oneormorelinetypesspecifiedintheimported"+_
"settingsisnotdefinedinyourdrawing")
EndIf
OnErrorGoTo0
EndSub
Pleasesendusyourcommentaboutthispage
<$nopage>multilinetext.
CreateandEditAutoCADEntities>
AddTexttoDrawings
Textconveysimportantinformationinyourdrawing.Usetextfortitleblocks,tolabelpartsofthedrawing,togivespecifications,ortomakeannotations.
AutoCADprovidesvariouswaystocreatetext.Forshort,simpleentries,uselinetext.Forlongerentrieswithinternalformatting,usemultilinetext(mtext).Althoughallenteredtextusesthecurrenttextstyle,whichestablishesthedefaultfontandformatsettings,youcanuseseveralmethodstocustomizethetextappearance.
Formoreinformationaboutworkingwithtext,see“CreateText”intheUser'sGuide.
Topicsinthissection
WorkwithTextStylesUseLineText(Text)UseMultilineText(Mtext)UseUnicodeCharacters,ControlCodes,andSpecialCharactersSubstituteFontsCheckSpelling
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>
WorkwithTextStyles
AlltextinanAutoCADdrawinghasastyleassociatedwithit.Whenyouentertext,AutoCADusesthecurrenttextstyle,whichsetsthefont,size,angle,orientation,andothertextcharacteristics.Youcanuseormodifythedefaultstyleorcreateandloadanewstyle.Onceyou'vecreatedastyle,youcanmodifyitsattributesordeleteitwhenyounolongerneedit.
Topicsinthissection
CreateandModifyTextStylesAssignFontsUseTrueTypeFontsUseUnicodeandBigFontsSetTextHeightSetObliquingAngleSetTextGenerationFlag
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>WorkwithTextStyles>
CreateandModifyTextStyles
Newtextinheritsheight,widthfactor,obliquingangle,andtextgenerationpropertiesfromthecurrenttextstyle.Tocreateatextstyle,usetheAddmethodtocreateanewTextStyleobjectandaddittotheTextStylescollection.TheAddmethodtakesaTextStylenameasinput.Oncecreated,youcannotchangethenameofatextstylethroughAutoCADActiveXAutomation.
Stylenamescancontainletters,numbers,andthespecialcharactersdollarsign($),underscore(_),andhyphen(-).AutoCADconvertsthecharacterstouppercase.Ifyoudon'tenterastylename,AutoCADautomaticallynamesthestyleStylen,wherenisanumberthatstartsat1.Eachnewstyleisshowninincrementsof1.
YoucanmodifyanexistingstylebychangingthepropertiesoftheTextStyleobject.Youcanalsoupdateexistingtextofthatstyletypetoreflectthechanges.UsethefollowingpropertiestomodifyaTextStyleobject:
FontFile
Specifiesthefileassociatedwithafont(characterstyle).
BigFontFile
Specifiesthespecialshapedefinitionfileusedforanon-ASCIIcharacterset.
Height
Specifiesthecharacterheight.
Width
Specifiestheexpansionorcompressionofthecharacters.
ObliqueAngle
Specifiestheslantofthecharacters.
TextGenerationFlag
Specifiesbackwardtext,upside-downtext,orboth.
Ifyouchangeanexistingstyle'sfontororientation,alltextusingthatstyleischangedtousethenewfontororientation.Changingtextheight,widthfactor,andobliqueangledoesnotchangeexistingtextbutdoeschangesubsequentlycreatedtextobjects.
Note YoumustcalltheRegenorUpdatemethodtoseeanychangestotheaboveproperties.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>WorkwithTextStyles>
AssignFonts
Fontsdefinetheshapesofthetextcharactersthatmakeupeachcharacterset.Asinglefontcanbeusedbymorethanonestyle.Toassignafonttoatextstyle,usetheFontFilepropertyoftheTextStyleobject.ByenteringthefontfilecontaininganAutoCAD-compiledSHXfont,youassignthatfonttothetextstyle.
Settextfonts
Thisexamplegetsthecurrentfontvaluesfortheactivetextstyleandthenchangesthetypefaceforthefontto“PlayBill.”ThenewfontisthensetusingtheSetFontmethod.Toseetheeffectsofchangingthetypeface,addsomeMtextorTexttoyourcurrentdrawingbeforerunningtheexample.Notethat,ifyoudon'thavethePlayBillfontonyoursystem,youneedtosubstituteafontyoudohaveinorderforthisexampletowork.
SubCh4_UpdateTextFont()
MsgBox("Lookatthetextnow...")
DimtypeFaceAsString
DimSavetypeFaceAsString
DimBoldAsBoolean
DimItalicAsBoolean
DimcharSetAsLong
DimPitchandFamilyAsLong
'Getthecurrentsettingstofillinthe
'defaultvaluesfortheSetFontmethod
ThisDrawing.ActiveTextStyle.GetFonttypeFace,_
Bold,Italic,charSet,PitchandFamily
'Changethetypefaceforthefont
SavetypeFace=typeFace
typeFace="PlayBill"
ThisDrawing.ActiveTextStyle.SetFonttypeFace,_
Bold,Italic,charSet,PitchandFamily
ThisDrawing.RegenacActiveViewport
MsgBox("Nowseehowitlooksafterchangingthefont...")
'Restoretheoriginaltypeface
ThisDrawing.ActiveTextStyle.SetFontSavetypeFace,_
Bold,Italic,charSet,PitchandFamily
ThisDrawing.RegenacActiveViewport
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>WorkwithTextStyles>
UseTrueTypeFonts
TrueTypefontsalwaysappearfilledinyourdrawing;however,whenyouplot,theTEXTFILLsystemvariablecontrolswhetherthefontsarefilled.BydefaultTEXTFILLissetto1toplotthefilled-infonts.WhenyouexportthedrawingtoPostScript® formatwiththeExportmethodandprintitonaPostScriptdevice,thefontisplottedasdesigned.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>WorkwithTextStyles>
UseUnicodeandBigFonts
AutoCADsupportstheUnicodecharacter-encodingstandard.AUnicodefontcancontain65,535characters,withshapesformanylanguages.AllAutoCADSHXshapefontsarenowUnicodefonts.
Thetextfilesforsomealphabetscontainthousandsofnon-ASCIIcharacters.Toaccommodatesuchtext,AutoCADsupportsaspecialtypeofshapedefinitionknownasaBigFontfile.YoucansetastyletousebothregularandBigFontfiles.SpecifynormalfontsusingtheFontFileproperty.SpecifyBigFontsusingtheBigFontFileproperty.
Note Fontfilenamescannotcontaincommas.
AutoCADprovideswaystosubstituteonefontforanotherortospecifyadefaultfont.FormoreinformationseeSubstituteFonts.
Changefontfiles
ThisexamplechangestheFontFileandBigFontFileproperties.Youneedtoreplacethepathinformationlistedinthisexamplewithpathandfilenamesappropriateforyoursystem.
SubCh4_ChangeFontFiles()
ThisDrawing.ActiveTextStyle.BigFontFile=_
"C:/AutoCAD/Fonts/bigfont.shx"
ThisDrawing.ActiveTextStyle.fontFile=_
"C:/AutoCAD/Fonts/italic.shx"
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>WorkwithTextStyles>
SetTextHeight
Textheightdeterminesthesizeindrawingunitsofthelettersinthefontyouareusing.Thevalueusuallyrepresentsthesizeoftheuppercaseletters,withtheexceptionofTrueTypefonts.
ForTrueTypefonts,thevaluespecifiedfortextheightmightnotrepresenttheheightofuppercaseletters.Theheightspecifiedrepresentstheheightofacapitalletterplusanaccentareareservedforaccentmarksandothermarksusedinnon-Englishlanguages.Therelativeportionofareasassignedtocapitallettersandaccentcharactersisdeterminedbythefontdesigneratthetimethefontisdesigned,and,consequently,willvaryfromfonttofont.
Inadditiontotheheightofacapitalletterandtheascentareathatmakeuptheheightspecifiedbytheuser,TrueTypefontshaveadescentareaforportionsofcharactersthatextendbelowthetextinsertionline.Examplesofsuchcharactersarey,j,p,g,andq.
YouspecifythetextheightusingtheHeightproperty.Thispropertyacceptspositivenumbersonly.
ChangetheheightofaTextobject
Thisexamplecreatesalineoftextandthenchangestheheightofthetext.
SubCh4_ChangeTextHeight()
DimtextObjAsAcadText
DimtextStringAsString
DiminsertionPoint(0To2)AsDouble
DimheightAsDouble
'Definethetextobject
textString="Hello,World."
insertionPoint(0)=3
insertionPoint(1)=3
insertionPoint(2)=0
height=0.5
'Createthetextobjectinmodelspace
SettextObj=ThisDrawing.ModelSpace._
AddText(textString,insertionPoint,height)
'ChangethevalueoftheHeightto1
textObj.height=1
textObj.Update
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>WorkwithTextStyles>
SetObliquingAngle
Theobliquingangledeterminestheforwardorbackwardslantofthetext.Theanglerepresentstheoffsetfromitsverticalaxis(90degrees).Tosettheobliquingangle,usetheObliqueAngleproperty.Theobliquinganglemustbeprovidedinradians.Apositiveangledenotesaleantotheright,anegativevaluewillhave2*PIaddedtoittoconvertittoitspositiveequivalent.
Createobliquetext
ThisexamplecreatesaTextobjectthenslantsthetext45degrees.
SubCh4_ObliqueText()
DimtextObjAsAcadText
DimtextStringAsString
DiminsertionPoint(0To2)AsDouble
DimheightAsDouble
'Definethetextobject
textString="Hello,World."
insertionPoint(0)=3
insertionPoint(1)=3
insertionPoint(2)=0
height=0.5
'Createthetextobjectinmodelspace
SettextObj=ThisDrawing.ModelSpace._
AddText(textString,insertionPoint,height)
'ChangethevalueoftheObliqueAngle
'to45degrees(.707radians)
textObj.ObliqueAngle=0.707
textObj.Update
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>WorkwithTextStyles>
SetTextGenerationFlag
Thetextgenerationflagspecifiesifthetextisdisplayedbackwardorupside-down.Tosetthetextgenerationflag,usetheTextGenerationFlagproperty.Todisplaythetextbackward,enteracTextFlagBackwardforthisproperty.Todisplaythetextupside-down,enteracTextFlagUpsideDownforthisproperty.Todisplaythetextbothbackwardandupside-down,addthetwoconstantstogetherbyenteringacTextFlagBackward+acTextFlagUpsidedownforthisproperty.
Displaytextbackward
Thisexamplecreatesalineoftext,thensetsittobedisplayedbackwardusingtheTextGenerationFlagproperty.
SubCh4_ChangingTextGenerationFlag()
DimtextObjAsAcadText
DimtextStringAsString
DiminsertionPoint(0To2)AsDouble
DimheightAsDouble
'Createthetextobject
textString="Hello,World."
insertionPoint(0)=3
insertionPoint(1)=3
insertionPoint(2)=0
height=0.5
SettextObj=ThisDrawing.ModelSpace._
AddText(textString,insertionPoint,height)
'ChangethevalueoftheTextGenerationFlag
textObj.TextGenerationFlag=acTextFlagBackward
textObj.Update
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>
UseLineText(Text)
Thetextyouaddtoyourdrawingsconveysavarietyofinformation.Itmaybeacomplexspecification,titleblockinformation,alabel,orevenpartofthedrawing.Forshorterentriesthatdonotrequiremultiplefontsorlines,createlineTextusingtheTextobject.Linetextismoreconvenientforlabels.
Topicsinthissection
CreateLineTextFormatLineTextAlignLineTextChangeLineText
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>UseLineText(Text)>
CreateLineText
Eachindividuallineoftextisadistinctobjectwhenusinglinetext.Tocreatealinetextobject,usetheAddTextmethod.Thismethodrequiresthreevaluesasinput:thetextstring,theinsertionpoint,andtheheightofthetext.
Thetextstringistheactualtexttobedisplayed.Unicode,controlcode,andspecialcharactersareaccepted.Theinsertionpointisavariantarraycontainingthreedoublesrepresentingthe3DWCScoordinateinthedrawingtoplacethetext.Theheightofthetextisapositivenumberrepresentingtheheightoftheuppercasetext.Heightismeasuredinthecurrentunits.
ToCreateLineText
Thisexamplecreatesalineoftextinmodelspace,atthecoordinate(2,2,0).
SubCh4_CreateText()
DimtextObjAsAcadText
DimtextStringAsString
DiminsertionPoint(0To2)AsDouble
DimheightAsDouble
'Createthetextobject
textString="Hello,World."
insertionPoint(0)=2
insertionPoint(1)=2
insertionPoint(2)=0
height=0.5
SettextObj=ThisDrawing.ModelSpace._
AddText(textString,insertionPoint,height)
textObj.Update
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>UseLineText(Text)>
FormatLineText
ATextobjectiscreatedusingtheactivetextstyle.YoucanchangetheformattingoftheTextobjectbychangingthetextstyleassociatedwithit,orbyeditingthepropertiesoftheTextobject.Youcannotapplyformatstoindividualwordsandcharacters.
TochangeatextstyleassociatedwithanindividualTextobject,settheStyleNamepropertytoanewtextstyle.Onceyouhavechangedthetextstyle,usetheUpdatemethodfortheTextobjecttoseethechangesinyourdrawing.
Inadditiontothestandardeditablepropertiesforentities(color,layer,linetype,andsoforth),otherpropertiesthatyoucanchangeonaTextobjectincludethefollowing:
Alignment
Specifiesthehorizontalandverticalalignmentforthetext.
InsertionPoint
Specifiestheinsertionpointforthetext.
ObliqueAngle
Specifiestheobliqueangleoftheindividualtextobject.
Rotation
Specifiestherotationangleinradiansforthetext.
ScaleFactor
Specifiesthescalefactorforthetext.
TextAlignmentPoint
Specifiesthealignmentpointforthetext.
TextGenerationFlag
Specifieswhetherthetextisdisplayedbackward,upside-down,orbothsimultaneously.
TextString
Specifiestheactualtextstringdisplayed.
Onceyouhavechangedaproperty,usetheUpdatemethodtoseethechangesinyourdrawing.
Note Foracompletelistofmethodsandproperties,seetheTextobjectdocumentationintheAutoCADActiveXandVBAReference.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>UseLineText(Text)>
AlignLineText
Youcanjustifylinetexthorizontallyandvertically.Leftalignmentisthedefault.Tosetthehorizontalandverticalalignmentoptions,usetheAlignmentproperty.
Realigntext
ThisexamplecreatesaTextobjectandaPointobject.ThePointobjectissettothetextalignmentpoint,andischangedtoaredcrosshairsothatitisvisible.Thetextalignmentischangedandamessageboxisdisplayedsothatthemacroexecutionishalted.Thisallowsyoutoseetheimpactofchangingthetextalignment.
SubCh4_TextAlignment()
DimtextObjAsAcadText
DimtextStringAsString
DiminsertionPoint(0To2)AsDouble
DimheightAsDouble
'DefinethenewTextobject
textString="Hello,World."
insertionPoint(0)=3
insertionPoint(1)=3
insertionPoint(2)=0
height=0.5
'CreatetheTextobjectinmodelspace
SettextObj=ThisDrawing.ModelSpace._
AddText(textString,insertionPoint,height)
'Createapointoverthetextalignmentpoint,
'sowecanbettervisualizethealignmentprocess
DimpointObjAsAcadPoint
DimalignmentPoint(0To2)AsDouble
alignmentPoint(0)=3
alignmentPoint(1)=3
alignmentPoint(2)=0
SetpointObj=ThisDrawing.ModelSpace._
AddPoint(alignmentPoint)
pointObj.Color=acRed
'Setthepointstyletocrosshair
ThisDrawing.SetVariable"PDMODE",2
'AlignthetexttotheLeft
textObj.Alignment=acAlignmentLeft
ThisDrawing.RegenacActiveViewport
MsgBox"TheTextobjectisnowalignedleft"
'AlignthetexttotheCenter
textObj.Alignment=acAlignmentCenter
'Alignthetexttothepoint(necessaryfor
'allbutleftalignedtext.)
textObj.TextAlignmentPoint=alignmentPoint
ThisDrawing.RegenacActiveViewport
MsgBox"TheTextobjectisnowcentered"
'AlignthetexttotheRight
textObj.Alignment=acAlignmentRight
ThisDrawing.RegenacActiveViewport
MsgBox"TheTextobjectisnowalignedright"
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>UseLineText(Text)>
ChangeLineText
Likeanyotherobject,Textobjectscanbemoved,rotated,erased,andcopied.Youalsocanmirrortext.Ifyoudonotwantthetexttobereversedwhenyoumirrorit,youcansettheMIRRTEXTsystemvariableto0.
ThefollowinglistrepresentsafewofthemethodsaTextobjecthasforuseinediting.Foracompletelist,seetheTextobjectdocumentationintheAutoCADActiveXandVBAReference.
ArrayPolar
Createsapolararray.
ArrayRectangular
Createsarectangulararray.
Copy
CopiestheTextobject.
Erase
ErasestheTextobject.
Mirror
MirrorstheTextobject.
Move
MovestheTextobject.
Rotate
RotatestheTextobject.
Pleasesendusyourcommentaboutthispage
<$nopage>multilinetext.
CreateandEditAutoCADEntities>AddTexttoDrawings>
UseMultilineText(Mtext)
Forlong,complexentries,createmultilinetext(mtext).Multilinetextfitsaspecifiedwidthbutcanextendverticallytoanindefinitelength.Youcanformatindividualwordsorcharacterswithinthemtext.
Topicsinthissection
CreateMultilineTextFormatMultilineText
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>UseMultilineText(Mtext)>
CreateMultilineText
Youcancreateamultilinetextobject(MTextobject)byusingtheAddMTextmethod.Thismethodrequiresthreevaluesasinput:thetextstring,theinsertionpointinthedrawingtoplacethetext,andthewidthofthetextboundingbox.
Thetextstringistheactualtexttobedisplayed.Unicode,controlcode,andspecialcharactersareaccepted.Theinsertionpointisavariantarraycontainingthreedoublesrepresentingthe3DWCScoordinateinthedrawingtoplacethetext.Thewidthofthetextisapositivenumberrepresentingthewidthoftheboundingboxforthetext.Widthismeasuredinthecurrentunits.
AftertheMTextobjectiscreated,youcanapplythetextheight,justification,rotationangle,andstyletotheMTextobject,orapplycharacterformattingtoselectedcharacters.
RefertotheentryonMTextintheActiveXandVBAReferenceforalistofmethodsandpropertiesthatapplytotheMTextobject.
ToCreateMultilineText
ThefollowingcodecreatesanMTextobjectinmodelspace,atthecoordinate(2,2,0).
SubCh4_CreateMText()
DimmtextObjAsAcadMText
DiminsertPoint(0To2)AsDouble
DimwidthAsDouble
DimtextStringAsString
insertPoint(0)=2
insertPoint(1)=2
insertPoint(2)=0
width=4
textString="Thisisatextstringforthemtextobject."
'CreateatextObjectinmodelspace
SetmtextObj=ThisDrawing.ModelSpace._
AddMText(insertPoint,width,textString)
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>UseMultilineText(Mtext)>
FormatMultilineText
Newtextautomaticallyassumesthecharacteristicsofthecurrenttextstyle.TheSTANDARDtextstyleisthedefault.YoucanoverridethedefaulttextstylebyapplyingformattingtoindividualcharactersandapplyingpropertiestotheTextobject.Youalsocanindicateformattingorspecialcharactersusingthemethodsdescribedinthissection.
Orientationoptionssuchasstyle,justification,width,androtationaffectalltextwithinthemtexttextboundary,notspecificwordsorcharacters.UsetheAttachmentPointpropertytochangethejustificationofmtext,andtheRotationpropertytocontroltheangleofrotationofthetextboundary.
TheStyleNamepropertysetsthedefaultfontsandformattingcharacteristicsfornewtext.Asyoucreatetext,youcanselectwhichstyleyouwanttousefromalistofexistingstyles.WhenyouchangethestyleofanMTextobjectthathascharacterformattingappliedtoanyportionofthetext,thestyleisappliedtotheentireobject,andsomeformattingofcharactersmightnotberetained.Forinstance,changingfromaTrueTypestyletoastyleusinganSHXfontortoanotherTrueTypefontcausesthetexttousethenewfontfortheentireobject,andanycharacterformattingislost.
Formattingoptionssuchasunderlining,stackedtext,orfontscanbeappliedtoindividualwordsorcharacterswithinaparagraph.Youalsocanchangecolor,font,andtextheight.Youcanchangethespacesbetweentextcharactersorincreasethewidthofthecharacters.
Usecurlybraces({})toapplyaformatchangeonlytothetextwithinthebraces.Youcannestbracesuptoeightlevelsdeep.
YoualsocanentertheASCIIequivalentforcontrolcodeswithinlinesorparagraphstoindicateformattingorspecialcharacters,suchastoleranceordimensioningsymbols.
Thefollowingcontrolcharacterscanbeusedtocreatethetextintheillustration.(FortheASCIIequivalentofthisstringseetheexamplefollowingtheillustration.)
{{\H1.5x;Bigtext}\A2;overtext\A1;/\A0;undertext}
Formoreinformationaboutformattingmultilinetext,see“FormatCharactersWithinMultilineText”intheUser'sGuide.
Usecontrolcharacterstoformattext
ThisexamplecreatesandformatsanMTextobject.
SubCh4_FormatMText()
DimmtextObjAsAcadMText
DiminsertPoint(0To2)AsDouble
DimwidthAsDouble
DimtextStringAsString
insertPoint(0)=2
insertPoint(1)=2
insertPoint(2)=0
width=4
'DefinetheASCIIcharactersforthecontrolcharacters
DimOBAsLong'OpenBracket{
DimCBAsLong'CloseBracket}
DimBSAsLong'BackSlash\
DimFSAsLong'ForwardSlash/
DimSCAsLong'Semicolon;
OB=Asc("{")
CB=Asc("}")
BS=Asc("\")
FS=Asc("/")
SC=Asc(";")
'Assignthetextstringthefollowinglineofcontrol
'charactersandtextcharacters:
'{{\H1.5x;Bigtext}\A2;overtext\A1;/\A0;undertext}
textString=Chr(OB)+Chr(OB)+Chr(BS)+"H1.5x"_
+Chr(SC)+"Bigtext"+Chr(CB)+Chr(BS)+"A2"_
+Chr(SC)+"overtext"+Chr(BS)+"A1"+Chr(SC)_
+Chr(FS)+Chr(BS)+"A0"+Chr(SC)+"undertext"_
+Chr(CB)
'CreateatextObjectinmodelspace
SetmtextObj=ThisDrawing.ModelSpace._
AddMText(insertPoint,width,textString)
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>
UseUnicodeCharacters,ControlCodes,andSpecialCharacters
YoucanuseUnicodecharacters,controlcodes,andspecialcharactersinyourtextstringtorepresentsymbols.(AllnontextcharactersmustbeenteredastheirASCIIequivalent.)
YoucancreatespecialcharactersbyenteringthefollowingUnicodecharacterstrings:
Unicodecharacterdescriptions
Unicodecharacter Description
\U+00B0 Degreesymbol
\U+00B1 Plus/minustolerancesymbol
\U+2205 Diameterdimensioningsymbol
InadditiontousingUnicodecharactersforspecialcharacters,youcanspecifyaspecialcharacterbyincludingcontrolinformationinthetextstring.Useapairofpercentsigns(%%)tointroduceeachcontrolsequence.Forexample,thefollowingcontrolcodeworkswithstandardAutoCADtextandPostScriptfontstodrawcharacternumbernnn:
%%nnn
InaVBorVBAtextstring,thisexamplewouldbeenteredas
DimpercentasLong
percent=ASC("%")
TextString=chr(percent)+chr(percent)+"nnn"
ThesecontrolcodesworkwithstandardAutoCADtextfontsonly:
Controlcodedescriptions
Controlcode Description
%%o Togglesoverscoremodeonandoff
%%u Togglesunderscoremodeonandoff
%%d Drawsdegreesymbol
%%p Drawsplusandminustolerancesymbol
%%c Drawsdiameterdimensioningsymbol
%%% Drawssinglepercentsign
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>
SubstituteFonts
YoucandesignatefontstobesubstitutedforotherfontsorasdefaultswhenAutoCADcannotfindafontspecifiedinadrawing.
Thefontsusedforthetextinyourdrawingaredeterminedbythetextstyleand,formtext,byindividualfontformatsappliedtosectionsoftext.
Youcanusefontmappingtablestoensurethatyourdrawingusesonlycertainfonts,ortoconvertthefontsyouusedtootherfonts.Youcanusethesefontmappingtablestoenforcecorporatefontstandards,ortofacilitateofflineprinting.AutoCADcomeswithadefaultfontmappingtable.YoucaneditthisfileusinganyASCIItexteditor.YoualsocanspecifyadifferentfontmappingtablefilebyusingtheFontFileMappropertyonthePreferencesobject.
Formoreinformationaboutfontmappingtablesandsubstitutingfonts,see“SubstituteFonts”intheUser'sGuide.
Topicsinthissection
SpecifyanAlternativeDefaultFont
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>SubstituteFonts>
SpecifyanAlternativeDefaultFont
Ifyourdrawingspecifiesafontthatisnotcurrentlyonyoursystem,AutoCADautomaticallysubstitutesthefontdesignatedasyouralternatefont.Bydefault,AutoCADusesthesimplex.shxfile.However,youcanspecifyadifferentfontifnecessary.UsetheAltFontFilepropertyonthePreferencesobjecttosetthealternativefontfilename.
IfyouuseatextstylethatusesaBigFont,youcanmapittoanotherfontusingtheAltFontFileproperty.Thissystemvariableusesadefaultfontfilepairoftxt.shx,bigfont.shx.
IfAutoCADcannotfindafontfilewhenadrawingisopened,itappliesadefaultsetoffontsubstitutionrules.
Pleasesendusyourcommentaboutthispage
CreateandEditAutoCADEntities>AddTexttoDrawings>
CheckSpelling
Duringaspellingcheck,AutoCADmatchesthewordsinthedrawingtothewordsinthecurrentmaindictionary.Anywordsyouaddarestoredinthecustomdictionarythatiscurrentatthetimeofthespellingcheck.Forexample,youcanaddpropernamessothatAutoCADnolongeridentifiesthemasmisspelledwords.
Tocheckspellinginanotherlanguage,youcanchangetoadifferentmaindictionary.
ThereisnomethodforcheckingspellingprovidedinAutoCADActiveXAutomation.However,youcanspecifyadifferentmaindictionaryusingtheMainDictionaryproperty,oradifferentcustomdictionaryusingtheCustomDictionarypropertyonthePreferencesobject.
Formoreinformationaboutspellingschecks,see“CheckSpelling”intheUser'sGuide.
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances
Dimensionsaddmeasurementstoadrawing.Tolerancesspecifybyhowmuchadimensioncanvary.WithActiveXAutomation,dimensionscanbemanagedwithdimensionstylesandoverrides.
Topicsinthissection
DimensioningConceptsCreateDimensionsEditDimensionsWorkwithDimensionStylesDimensioninModelSpaceandPaperSpaceCreateLeadersandAnnotationUseGeometricTolerances
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>
DimensioningConcepts
Dimensionsshowthegeometricmeasurementsofobjects,thedistancesoranglesbetweenobjects,ortheXandYcoordinatesofafeature.AutoCAD®
providesthreebasictypesofdimensioning:linear,radial,andangular.Lineardimensionsincludealigned,rotated,andordinatedimensions.
Youcancreatedimensionsforlines,multilines,arcs,circles,andpolylinesegments,oryoucancreatedimensionsthatstandalone.
AutoCADdrawsdimensionsonthecurrentlayer.Everydimensionhasadimensionstyleassociatedwithit,whetherit'sthedefaultoroneyoudefine.Thestylecontrolscharacteristicssuchascolor,textstyle,andlinetypescale.Thicknessinformationisnotsupported.Stylefamiliesallowforsubtlemodificationstoabasestylefordifferenttypesofdimensions.Overridesallowforstylemodificationstoaspecificdimension.
Formoreinformationaboutdimensions,see“ChangeExistingObjects”intheUser'sGuide.
Topicsinthissection
PartsofaDimension
DefinetheDimensionSystemVariablesSetDimensionTextStylesUnderstandLeaderLinesUnderstandAssociativeDimensions
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>DimensioningConcepts>
PartsofaDimension
Thissectionbrieflydefinesthepartsofadimension.
Adimensionlineisalinethatindicatesthedirectionandextentofadimension.Foranangulardimension,thedimensionlineisanarc.Extensionlines,alsocalledprojectionlinesorwitnesslines,extendfromthefeaturebeingdimensionedtothedimensionline.Arrowheads,alsocalledsymbolsofterminationorjusttermination,areaddedtoeachendofthedimensionline.Dimensiontextisatextstringthatusuallyindicatestheactualmeasurement.Thetextmayalsoincludeprefixes,suffixes,andtolerances.Aleaderisasolidlineleadingfromsomeannotationtothereferencedfeature.Acentermarkisasmallcrossthatmarksthecenterofacircleorarc.Centerlinesarebrokenlinesthatmarkthecenterofacircleorarc.
See“PartsofaDimension”intheUser'sGuideformoreinformationaboutthepartsofadimension.
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>DimensioningConcepts>
DefinetheDimensionSystemVariables
Thedimensioningsystemvariablescontroltheappearanceofdimensions.ThedimensionsystemvariablesincludeDIMAUNIT,DIMUPT,DIMTOFL,DIMFIT,DIMTIH,DIMTOH,DIMJUST,andDIMTAD.YoucansetthesevariablesbyusingtheSetVariablemethod.Forexample,thefollowinglineofcodesetstheDIMAUNITsystemvariable(theunitsformatforangulardimensions)toradians(3):
ThisDrawing.SetVariable"DIMAUNIT",3
See“UseDimensionStyles”intheUser'sGuideformoreinformationaboutthedimensioningsystemvariables.
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>DimensioningConcepts>
SetDimensionTextStyles
Dimensiontextreferstoanykindoftextassociatedwithdimensions,includingmeasurements,tolerances(bothlateralandgeometric),prefixes,suffixes,andtextualnotesinsingle-lineorparagraphform.YoucanusethedefaultmeasurementcomputedbyAutoCADasthetext,supplyyourowntext,orsuppressthetextentirely.Youcanusedimensiontexttoaddinformation,suchasspecialmanufacturingproceduresorassemblyinstructions.
Single-linedimensiontextusestheactivetextstyleasspecifiedbytheActiveTextStyleproperty.Paragraphsoftextusetheactivetextstylewithanymodificationsyoumakeinyourtextstring.
Formoreinformationaboutdimensiontext,see“ControlDimensionText”intheUser'sGuide.
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>DimensioningConcepts>
UnderstandLeaderLines
Adefaultleaderlineisastraightlinewithanarrowheadthatreferstoafeatureinadrawing.Usually,aleader'sfunctionistoconnectannotationwiththefeature.Annotationinthiscasemeansparagraphtext,blocks,orfeaturecontrolframes.SuchleaderlinesaredifferentfromthesimpleleaderlinesAutoCADcreatesautomaticallyforradial,diameter,andlineardimensionswhosetextwon'tfitbetweenextensionlines.
Leaderobjectsareassociatedwiththeannotation,sowhentheannotationisedited,theleaderisupdatedaccordingly.Youcancopyannotationusedelsewhereinadrawingandappendittoaleader,oryoucancreateanewannotation.Youcanalsocreatealeaderwithnoannotationappended.
Formoreinformationaboutleaders,see“OverviewofCreatingTextandLeaders”intheUser'sGuide.
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>DimensioningConcepts>
UnderstandAssociativeDimensions
Associativedimensionsautomaticallyadjusttheirlocations,orientations,andmeasurementvalueswhenthegeometricobjectsassociatedwiththemaremodified.TheDIMASSOCsystemvariablecontrolsassociativedimensioning.SetDIMASSOCto2toturnonassociativedimensioning.
Formoreinformationaboutassociativedimensions,see“AssociativeDimensions”intheUser'sGuide.
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>
CreateDimensions
Youcancreatelinear,radial,angular,andordinatedimensions.
Whencreatingdimensions,theactivedimensionstyleisused.Oncecreated,youcanmodifytheextensionlineorigins,thedimensiontextlocation,andthedimensiontextcontentanditsanglerelativetothedimensionline.Youcanalsochangethedimensionstyleusedbythedimension.
Formoreinformationaboutcreatingdimensions,see“ChangeExistingObjects”intheUser'sGuide.
Topicsinthissection
CreateLinearDimensionsCreateRadialDimensionsCreateAngularDimensionsCreateOrdinateDimensions
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>CreateDimensions>
CreateLinearDimensions
Lineardimensionscanbealignedorrotated.Aligneddimensionshavethedimensionlineparalleltothelinealongwhichtheextensionlineoriginslie.Rotateddimensionshavethedimensionlineplacedatanangletotheextensionlineorigins.
Tocreatealineardimension,usetheAddDimAlignedorAddDimRotatedmethod.Afteryoucreatelineardimensions,youcanmodifythetext,theangleofthetext,ortheangleofthedimensionline.Inthefollowingillustrations,theextensionlineoriginsaredesignatedexplicitly.Theresultingdimensionlinelocationisalsoshown:
Tocreateanaligneddimension,usetheAddDimAlignedmethod.Thismethodrequiresthreecoordinatesasinput:theoriginofbothextensionlinesandthetextposition.
Tocreatearotateddimension,usetheAddDimRotatedmethod.Thismethodrequiresthreecoordinatesandtheangleofthedimensionlineasinput.Thethreecoordinatesaretheoriginofbothextensionlinesandthetextposition.Theanglemustbeprovidedinradiansandrepresentstheangleofrotationforthedimensionline.
Foradditionalinformationaboutcreatinglineardimensions,see“CreateLinear
Dimensions”intheUser'sGuide.
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>CreateDimensions>
CreateRadialDimensions
Radialdimensionsmeasuretheradiianddiametersofarcsandcircles.Tocreatearadialdimension,usetheAddDimRadialmethod.
Differenttypesofradialdimensionsarecreateddependingonthesizeofthecircleorarc,theTextPositionproperty,andthevaluesintheDIMUPT,DIMTOFL,DIMFIT,DIMTIH,DIMTOH,DIMJUST,andDIMTADdimensionsystemvariables.(SystemvariablescanbequeriedorsetusingtheGetVariableandSetVariablemethods.)
Forhorizontaldimensiontext,iftheangleofthedimensionlineismorethan15degreesfromhorizontal,andisoutsidethecircleorarc,AutoCADdrawsahookline,alsocalledalandingordogleg.Thehooklineisonearrowheadlong,andisplacednexttothedimensiontext,asshowninthefollowingillustrations:
Tocreateradialdimensions,usetheAddDimRadialorAddDimDiametricmethod.Thesemethodsrequirethreevaluesasinput:thecoordinateofthecircleorarc'scenter,thecoordinatefortheleaderattachment,andthelengthoftheleader.
ThesemethodsusetheLeaderLengthparameterasthedistancefromtheChordPointtothepointwherethedimensionwilldoahorizontalhooklinetotheannotationtext(orstopifnohooklineisnecessary).
Foradditionalinformationaboutcreatingradialdimensions,see“CreateRadialDimensions”intheUser'sGuide.
Createaradialdimension
Thisexamplecreatesaradialdimensioninmodelspace.
SubCh5_CreateRadialDimension()
DimdimObjAsAcadDimRadial
Dimcenter(0To2)AsDouble
DimchordPoint(0To2)AsDouble
DimleaderLenAsInteger
'Definethedimension
center(0)=0
center(1)=0
center(2)=0
chordPoint(0)=5
chordPoint(1)=5
chordPoint(2)=0
leaderLen=5
'Createtheradialdimensioninmodelspace
SetdimObj=ThisDrawing.ModelSpace._
AddDimRadial(center,chordPoint,leaderLen)
ZoomAll
EndSub
Note TheLeaderLengthsettingisonlyusedduringthecreationofthedimension(andeventhenonlyifthedimensionissettousethedefaulttextpositionvalue).Afterthedimensionisclosedforthefirsttime,changingtheLeaderLengthvaluewillnotaffecthowthedimensionisdisplayed,butthenewsettingwillbestoredandwillshowupinDXF,LISP,andADSRXapplications.
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>CreateDimensions>
CreateAngularDimensions
Angulardimensionsmeasuretheanglebetweentwolinesorthreepoints.Forexample,youcanusethemtomeasuretheanglebetweentworadiiofacircle.Thedimensionlineformsanarc.
Tocreateanangulardimension,usetheAddDimAngularmethod.Thismethodrequiresthreevaluesasinput:theanglevertex,theoriginsoftheextensionlines,andthetextlocation.TheAngleVertexisthecenterofthecircleorarc,orthecommonvertexbetweenthetwolinesbeingdimensioned.Theoriginsoftheextensionlinesarethepointsthroughwhichthetwoextensionlinespass.
TheAngleVertexcanbethesameasoneoftheoriginpoints.Ifyouneedextensionlinestheywillbeaddedautomatically.
Foradditionalinformationaboutcreatingangulardimensions,see“CreateAngularDimensions”intheUser'sGuide.
Createanangulardimension
Thisexamplecreatesanangulardimensioninmodelspace.
SubCh5_CreateAngularDimension()
DimdimObjAsAcadDimAngular
DimangVert(0To2)AsDouble
DimFirstPoint(0To2)AsDouble
DimSecondPoint(0To2)AsDouble
DimTextPoint(0To2)AsDouble
'Definethedimension
angVert(0)=0
angVert(1)=5
angVert(2)=0
FirstPoint(0)=1
FirstPoint(1)=7
FirstPoint(2)=0
SecondPoint(0)=1
SecondPoint(1)=3
SecondPoint(2)=0
TextPoint(0)=3
TextPoint(1)=5
TextPoint(2)=0
'Createtheangulardimensioninmodelspace
SetdimObj=ThisDrawing.ModelSpace._
AddDimAngular(angVert,FirstPoint,SecondPoint,TextPoint)
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>CreateDimensions>
CreateOrdinateDimensions
Ordinate,ordatum,dimensionsmeasuretheperpendiculardistancefromanoriginpoint,calledthedatum,toadimensionedfeature,suchasaholeinapart.Thesedimensionspreventescalatingerrorsbymaintainingaccurateoffsetsofthefeaturesfromthedatum.
OrdinatedimensionsconsistofanXorYordinatewithaleaderline.X-datumordinatedimensionsmeasurethedistanceofafeaturefromthedatumalongtheXaxis.Y-datumordinatedimensionsmeasurethesamedistancealongtheYaxis.AutoCADusestheoriginofthecurrentusercoordinatesystem(UCS)todeterminethemeasuredcoordinates.Theabsolutevalueofthecoordinateisused.
Thetextisalignedwiththeordinateleaderlineregardlessofthetextorientationdefinedbythecurrentdimensionstyle.Youcanacceptthedefaulttextorsupplyyourown.
Tocreateanordinatedimension,usetheAddDimOrdinatemethod.Thismethodrequiresthreevaluesasinput:acoordinatespecifyingthepointtobedimensioned(A),acoordinatespecifyingtheendoftheleader(B),andaBooleanflagspecifyingwhetherthedimensionisanX-datumordinatedimensionoraY-datumordinatedimension.IfyouenterTRUEfortheBooleanflag,themethodwillcreateanX-datumordinatedimension.IfyouenterFALSE,itwillcreateaY-datumordinatedimension.
Foradditionalinformationaboutcreatingordinatedimensions,see“CreateOrdinateDimensions”intheUser'sGuide.
Createanordinatedimension
Thisexamplecreatesanordinatedimensioninmodelspace.
SubCh5_CreatingOrdinateDimension()
DimdimObjAsAcadDimOrdinate
DimdefiningPoint(0To2)AsDouble
DimleaderEndPoint(0To2)AsDouble
DimuseXAxisAsLong
'Definethedimension
definingPoint(0)=5
definingPoint(1)=5
definingPoint(2)=0
leaderEndPoint(0)=10
leaderEndPoint(1)=5
leaderEndPoint(2)=0
useXAxis=5
'Createanordinatedimensioninmodelspace
SetdimObj=ThisDrawing.ModelSpace._
AddDimOrdinate(definingPoint,_
leaderEndPoint,useXAxis)
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>
EditDimensions
AswithothergraphicalobjectsinAutoCAD,youcaneditdimensionsusingthestandardmethodsandpropertiesprovidedfortheobject.
Thefollowingpropertiesareavailableformostdimensionobjects:
Rotation
Specifiestherotationangleinradiansforthedimensionline.
StyleName
Specifiesthenameofthedimensionstyle.
TextOverride
Specifiesthetextstringforthedimension.
TextPosition
Specifiesthedimensiontextposition.
TextRotation
Specifiestherotationangleofthedimensiontext.
Measurement
Specifiestheactualmeasurementforthedimension.
Inaddition,certaindimensionobjectsprovidepropertiesforeditingtheextensionlineoriginsandleaderlength.
Thefollowingmethodsareincludedfordimensionobjectediting:
ArrayPolar
Createsapolararray.
ArrayRectangular
Createsarectangulararray.
Copy
Copiesthedimensionobject.
Erase
Erasesthedimensionobject.
Mirror
Mirrorsthedimensionobject.
Move
Movesthedimensionobject.
Rotate
Rotatesthedimensionobject.
ScaleEntity
Scalesthedimensionobject.
Formoreinformationabouteditingdimensions,see“ModifyExistingDimensions”intheUser'sGuide.
Topicsinthissection
OverrideDimensionText
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>EditDimensions>
OverrideDimensionText
ThedimensionvaluethatisdisplayedcanbereplacedusingtheTextOverrideproperty.Usingthispropertyyoucancompletelyreplacethedisplayedvalueofthedimension,oryoucanappendtexttothevalue.
Modifydimensiontext
Thisexampleappendssometexttothevaluesothatboththestringandthedimensionvaluearedisplayed.
SubCh5_OverrideDimensionText()
DimdimObjAsAcadDimAligned
Dimpoint1(0To2)AsDouble
Dimpoint2(0To2)AsDouble
Dimlocation(0To2)AsDouble
'Definethedimension
point1(0)=5#:point1(1)=3#:point1(2)=0#
point2(0)=10#:point2(1)=3#:point2(2)=0#
location(0)=7.5:location(1)=5#:location(2)=0#
'Createanaligneddimensionobjectinmodelspace
SetdimObj=ThisDrawing.ModelSpace._
AddDimAligned(point1,point2,location)
'Changethetextstringforthedimension
dimObj.TextOverride="Thevalueis<>"
dimObj.Update
EndSub
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>
WorkwithDimensionStyles
Anameddimensionstyleisagroupofsettingsthatdeterminestheappearanceofthedimension.Usingnameddimensionstyles,youcanestablishandenforcedraftingstandardsfordrawings.
Alldimensionsarecreatedusingtheactivedimensionstyle.Ifyoudon'tdefineorapplyastylebeforecreatingdimensions,AutoCADappliesthedefaultstyle,STANDARD.Tosettheactivedimensionstyle,usetheActiveDimStyleproperty.
Tosetupaparentdimensionstyle,youbeginbynamingandsavingastyle.Thenewstyleisbasedonthecurrentstyleandincludesallsubsequentchangestothelayoutofthedimensionparts,thepositioningoftext,andtheappearanceofannotation.Annotationinthiscasemeansprimaryandalternateunits,tolerances,andtext.
Formoreinformationaboutdimensionstyles,see“UseDimensionStyles”intheUser'sGuide.
Topicsinthissection
Create,Modify,andCopyDimensionStylesOverridetheDimensionStyle
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>WorkwithDimensionStyles>
Create,Modify,andCopyDimensionStyles
Tocreateanewdimensionstyle,usetheAddmethod.Thismethodrequiresasinputthenameofthenewdimensionstyle.
AutoCADActiveXAutomationallowsyoutoaddnewdimensionstyles,andtochangetheactivedimensionstyle.YoucanalsochangethedimensionstyleassociatedwithagivendimensionthroughtheStyleNameproperty.
Youcanalsocopyanexistingstyleorsetofoverrides.UsetheCopyFrommethodtocopyadimensionstylefromasourceobjecttoanewdimensionstyle.ThesourceobjectcanbeanotherDimStyleobject,adimension,Tolerance,orLeaderobject,orevenaDocumentobject.Ifyoucopythestylesettingsfromanotherdimensionstyle,thestyleisduplicatedexactly.Ifyoucopythestylesettingsfromadimension,Tolerance,orLeaderobject,thecurrentsettings,includinganyobjectoverrides,arecopiedtothenewstyle.IfyoucopythestyleofaDocumentobject,theactivedimensionstyle,plusanydrawingoverrides,iscopiedtothenewstyle.
Copydimensionstylesandoverrides
Thisexamplecreatesthreenewdimensionstylesandcopiesthecurrentsettingsforthedocument,agivendimensionstyle,andagivendimensiontoeachnewdimensionstylerespectively.Byfollowingtheappropriatesetupbeforerunningthisexample,youwillfindthatdifferentdimensionstyleshavebeencreated.
1. Createanewdrawingandmakeittheactivedrawing.
2. Createalineardimensioninthenewdrawing.Thisdimensionshouldbetheonlyobjectinthedrawing.
3. Changethecolorofthedimensionlinetoyellow.
4. ChangetheDIMCLRDsystemvariableto5(blue).
5. Runthefollowingexample:
SubCh5_CopyDimStyles()
DimnewStyle1AsAcadDimStyle
DimnewStyle2AsAcadDimStyle
DimnewStyle3AsAcadDimStyle
SetnewStyle1=ThisDrawing.DimStyles.Add_
("Style1copiedfromadim")
CallnewStyle1.CopyFrom(ThisDrawing.ModelSpace(0))
SetnewStyle2=ThisDrawing.DimStyles.Add_
("Style2copiedfromStyle1")
CallnewStyle2.CopyFrom(ThisDrawing.DimStyles.Item_
("Style1copiedfromadim"))
SetnewStyle2=ThisDrawing.DimStyles.Add_
("Style3copiedfromtherunningdrawingvalues")
CallnewStyle2.CopyFrom(ThisDrawing)
EndSub
OpentheDIMSTYLEdialogbox.Youshouldnowhavethreedimensionstyleslisted.Style1shouldhaveayellowdimensionline.Style2shouldbethesameasStyle1.Style3shouldhaveabluedimensionline.
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>WorkwithDimensionStyles>
OverridetheDimensionStyle
Eachdimensionhasthecapabilityofoverridingsettingsinthedimensionstyleforthatdimension.Thefollowingpropertiesareavailableformostdimensionobjects:
AltRoundDistance
Specifiestheroundingofalternateunits.
AngleFormat
Specifiestheunitformatforangulardimensions.
Arrowhead1Block,Arrowhead2Block
Specifiestheblocktouseasthecustomarrowheadforthedimensionline.
Arrowhead1Type,Arrowhead2Type
Specifiesthetypeofarrowheadforthedimensionline.
ArrowheadSize
Specifiesthesizeofdimensionlinearrowheads,leaderlinearrowheads,andhooklines.
CenterMarkSize
Specifiesthesizeofthecentermarkforradialanddiameterdimensions.
CenterType
Specifiesthetypeofcentermarkforradialanddiameterdimensions.
DecimalSeparator
Specifiesthecharactertobeusedasthedecimalseparatorindecimaldimensionandtolerancevalues.
DimensionLineColor
Specifiesthecolorofthedimensionlineforadimension,leader,ortoleranceobject.
DimensionLineWeight
Specifiesthelineweightforthedimensionlines.
DimLine1Suppress,DimLine2Suppress
Specifiesthesuppressionofthedimensionlines.
DimLineInside
Specifiesthedisplayofdimensionlinesinsidetheextensionlinesonly.
ExtensionLineColor
Specifiesthecolorfordimensionextensionlines.
ExtensionLineExtend
Specifiesthedistancetheextensionlineextendsbeyondthedimensionline.
ExtensionLineOffset
Specifiesthedistancetheextensionlinesareoffsetfromtheoriginpoints.
ExtensionLineWeight
Specifiesthelineweightfortheextensionlines.
ExtLine1EndPoint,ExtLine2EndPoint
Specifiestheendpointofextensionlines.
ExtLine1StartPoint,ExtLine2StartPoint
Specifiesthestartpointofextensionlines.
ExtLine1Suppress,ExtLine2Suppress
Specifiesthesuppressionofextensionlines.
Fit
Specifiestheplacementoftextandarrowheadsinsideoroutsideextensionlines.
ForceLineInside
Specifiesifadimensionlineisdrawnbetweentheextensionlinesevenwhenthetextisplacedoutsidetheextensionlines.
FractionFormat
Specifiestheformatoffractionalvaluesindimensionsandtolerances.
HorizontalTextPosition
Specifiesthehorizontaljustificationfordimensiontext.
LinearScaleFactor
Specifiesaglobalscalefactorforlineardimensioningmeasurements.
PrimaryUnitsPrecision
Specifiesthenumberofdecimalplacesdisplayedfortheprimaryunitsofadimensionortolerance.
SuppressLeadingZeros,SuppressTrailingZeros
Specifiesthesuppressionofleadingandtrailingzerosindimensionvalues.
SuppressZeroFeet,SuppressZeroInches
Specifiesthesuppressionofazerofootandzeroinchmeasurementindimensionvalues.
TextColor
Specifiesthecolorofthetextfordimensionandtoleranceobjects.
TextGap
Specifiesthedistancebetweenthedimensiontextandthedimensionlinewhenyoubreakthedimensionlinetoaccommodatedimensiontext.
TextHeight
Specifiestheheightforthedimensionortolerancetext.
TextInside
Specifiesifthedimensiontextistobedrawninsidetheextensionlines.
TextInsideAlign
Specifiesthepositionofdimensiontextinsidetheextensionlinesforall
dimensiontypesexceptordinate.
TextMovement
Specifieshowdimensiontextisdrawnwhentextismoved.
TextOutsideAlign
Specifiesthepositionofdimensiontextoutsidetheextensionlinesforalldimensiontypesexceptordinate.
TextPosition
Specifiesthedimensiontextposition.
TextPrecision
Specifiestheprecisionofangulardimensiontext.
TextPrefix
Specifiesthedimensionvalueprefix.
TextRotation
Specifiestherotationangleofthedimensiontext.
TextSuffix
Specifiesthedimensionvaluesuffix.
ToleranceDisplay
Specifiesiftolerancesaredisplayedwiththedimensiontext.
ToleranceHeightScale
Specifiesascalefactorforthetextheightoftolerancevaluesrelativetothedimensiontextheight.
ToleranceJustification
Specifiestheverticaljustificationoftolerancevaluesrelativetothenominaldimensiontext.
ToleranceLowerLimit
Specifiestheminimumtolerancelimitfordimensiontext.
TolerancePrecision
Specifiestheprecisionoftolerancevaluesinprimarydimensions.
ToleranceSuppressLeadingZeros
Specifiesthesuppressionofleadingzerosintolerancevalues.
ToleranceSuppressTrailingZeros
Specifiesthesuppressionoftrailingzerosindimensionvalues.
ToleranceUpperLimit
Specifiesthemaximumtolerancelimitfordimensiontext.
UnitsFormat
Specifiestheunitformatforalldimensionsexceptangular.
VerticalTextPosition
Specifiestheverticalpositionoftextinrelationtothedimensionline.
Enterauser-definedsuffixforanaligneddimension
ThisexamplecreatesanaligneddimensioninmodelspaceandusestheTextSuffixpropertytoallowtheusertochangethetextsuffixforthedimension.
SubCh5_AddTextSuffix()
DimdimObjAsAcadDimAligned
Dimpoint1(0To2)AsDouble
Dimpoint2(0To2)AsDouble
Dimlocation(0To2)AsDouble
DimsuffixAsString
'Definethedimension
point1(0)=0:point1(1)=5:point1(2)=0
point2(0)=5:point2(1)=5:point2(2)=0
location(0)=5:location(1)=7:location(2)=0
'Createanaligneddimensionobjectinmodelspace
SetdimObj=ThisDrawing.ModelSpace._
AddDimAligned(point1,point2,location)
ThisDrawing.Application.ZoomAll
'Allowtheusertochangethetextsuffixforthedimension
suffix=InputBox("Enteranewtextsuffixforthedimension"_
,"SetDimensionSuffix",":SUFFIX")
'Applythechangetothedimension
dimObj.TextSuffix=suffix
ThisDrawing.RegenacAllViewports
EndSub
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>
DimensioninModelSpaceandPaperSpace
Youcandrawdimensionsinbothpaperspaceandmodelspace.However,ifthegeometryyou'redimensioningisinmodelspace,it'sbettertodrawdimensionsinmodelspace,becauseAutoCADplacesthedefinitionpointsinthespacewherethegeometryisdrawn.
Ifyoudrawadimensioninpaperspacethatdescribesgeometryinyourmodel,thepaperspacedimensiondoesnotchangewhenyouuseeditingcommandsorchangethemagnificationofthedisplayinthemodelspaceviewport.Thelocationofthepaperspacedimensionsalsostaysthesamewhenyouchangeaviewfrompaperspacetomodelspace.
Ifyou'redimensioninginpaperspaceandtheglobalscalefactorforlineardimensioning(theDIMLFACsystemvariable)issetatlessthan0,thedistancemeasuredismultipliedbytheabsolutevalueofDIMLFAC.Ifyou'redimensioninginmodelspace,thevalueof1.0isusedevenifDIMLFACislessthan0.AutoCADcomputesavalueforDIMLFACifyouchangethevariableattheDimpromptandselecttheViewportoption.AutoCADcalculatesthescalingofmodelspacetopaperspaceandassignsthenegativeofthisvaluetoDIMLFAC.
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>
CreateLeadersandAnnotation
Aleaderisalinethatconnectssomeannotationtoafeatureinadrawing.Leadersandtheirannotationareassociative,whichmeansifyoumodifytheannotation,theleaderupdatesaccordingly.Don'tconfusetheLeaderobjectwiththeleaderlineAutoCADautomaticallygeneratesaspartofadimensionline.
Formoreinformationaboutleaders,see“CreateTextwithLeaders”intheUser'sGuide.
Topicsinthissection
CreateLeaderLinesAddtheAnnotationtoaLeaderLineLeaderAssociativityEditLeaderAssociativityEditLeaders
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>CreateLeadersandAnnotation>
CreateLeaderLines
Youcancreatealeaderlinefromanypointorfeatureinadrawingandcontrolitsappearanceasyoudrawit.Leaderscanbestraightlinesegmentsorsmoothsplinecurves.Leadercoloriscontrolledbythecurrentdimensionlinecolor.Leaderscaleiscontrolledbytheoveralldimensionscalesetintheactivedimensionstyle.Thetypeandsizeofthearrowhead,ifoneispresent,iscontrolledbythefirstarrowheaddefinedintheactivestyle.
Asmalllineknownasahooklineusuallyconnectstheannotationtotheleader.Hooklinesappearwithmtextandfeaturecontrolframesifthelastleaderlinesegmentisatananglegreaterthan15degreesfromhorizontal.Thehooklineisthelengthofasinglearrowhead.Iftheleaderhasnoannotation,ithasnohookline.
Tocreatealeaderline,usetheAddLeadermethod.Thismethodrequiresthreevaluesasinput:thearrayofcoordinatesspecifyingwheretocreatetheleader,theannotationobject(orNULLiftheleaderistohavenoannotation),andthetypeofleadertocreate.Thetypeofleaderspecifieswhethertheleaderistobeastraightlineorasmoothsplinecurve.Italsodetermineswhetherornottheleaderistohavearrows.Useoneofthefollowingconstantstospecifythetypeofleader:acLineNoArrow,acLineWithArrow,acSplineNoArrow,oracSplineWithArrow.Theseconstantsaremutuallyexclusive.
Createaleaderline
Thisexamplecreatesaleaderlineinmodelspace.Thereisnoannotationassociatedwiththeleaderline.
SubCh5_CreateLeader()
DimleaderObjAsAcadLeader
Dimpoints(0To8)AsDouble
DimleaderTypeAsInteger
DimannotationObjectAsAcadObject
points(0)=0:points(1)=0:points(2)=0
points(3)=4:points(4)=4:points(5)=0
points(6)=4:points(7)=5:points(8)=0
leaderType=acLineWithArrow
SetannotationObject=Nothing
'Createtheleaderobjectinmodelspace
SetleaderObj=ThisDrawing.ModelSpace._
AddLeader(points,annotationObject,leaderType)
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>CreateLeadersandAnnotation>
AddtheAnnotationtoaLeaderLine
AleaderannotationcanbeaTolerance,MText,orBlockRefobject.Youcancreateanewannotation,oryoucanappendacopyofanexistingannotation.Annotationisaddedtotheleaderonlywhenitiscreated.
Toaddanannotationwhenaleaderisbeingcreated,inputtheannotationtotheAddLeadermethod.
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>CreateLeadersandAnnotation>
LeaderAssociativity
Leadersareassociatedwiththeirannotationsothatwhentheannotationmoves,theendpointoftheleadermoveswithit.Asyoumovetextandfeaturecontrolframeannotation,thefinalleaderlinesegmentalternatesbetweenattachingtotheleftsideandtotherightsideoftheannotationaccordingtotherelationoftheannotationtothepenultimate(secondtolast)pointoftheleader.Ifthemidpointoftheannotationistotherightofthepenultimateleaderpoint,thentheleaderattachestotheright;otherwise,itattachestotheleft.
RemovingeitherobjectfromthedrawingusingeithertheErase,Add(toaddablock),orWBlockmethodwillbreakassociativity.Iftheleaderanditsannotationarecopiedtogetherinasingleoperation,thenewcopyisassociative.Iftheyarecopiedseparately,theywillnotbeassociative.Ifassociativityisbrokenforanyreason,forexample,bycopyingonlytheLeaderobjectorbyerasingtheannotation,thehooklinewillberemovedfromtheleader.
Associatealeadertotheannotation
ThisexamplecreatesanMTextobject.AleaderlineisthencreatedusingtheMTextobjectasitsannotation.
SubCh5_AddAnnotation()
DimleaderObjAsAcadLeader
DimmtextObjAsAcadMText
Dimpoints(0To8)AsDouble
DiminsertionPoint(0To2)AsDouble
DimwidthAsDouble
DimleaderTypeAsInteger
DimannotationObjectAsObject
DimtextStringAsString,msgAsString
'CreatetheMTextobjectinmodelspace
textString="Hello,World."
insertionPoint(0)=5
insertionPoint(1)=5
insertionPoint(2)=0
width=2
SetmtextObj=ThisDrawing.ModelSpace._
AddMText(insertionPoint,width,textString)
'DataforLeader
points(0)=0:points(1)=0:points(2)=0
points(3)=4:points(4)=4:points(5)=0
points(6)=4:points(7)=5:points(8)=0
leaderType=acLineWithArrow
'CreatetheLeaderobjectinmodelspaceandassociate
'theMTextobjectwiththeleader
SetannotationObject=mtextObj
SetleaderObj=ThisDrawing.ModelSpace._
AddLeader(points,annotationObject,leaderType)
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>CreateLeadersandAnnotation>
EditLeaderAssociativity
Exceptfortheassociativityrelationbetweentheleaderandannotation,theleaderanditsannotationareentirelyseparateobjectsinyourdrawing.Editingoftheleaderdoesnotaffecttheannotation,andeditingoftheannotationdoesnotaffecttheleader.
AlthoughtextannotationiscreatedusingtheDIMCLRT,DIMTXT,andDIMTXSTYsystemvariablestodefineitscolor,height,andstyle,itcannotbechangedbythesesystemvariablesbecauseitisnotatruedimensionobject.TextannotationmustbeeditedthesamewayasanyotherMtextobject.
UsetheEvaluatemethodtoevaluatetherelationoftheleadertoitsassociatedannotation.Thismethodwillupdatetheleadergeometryifnecessary.
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>CreateLeadersandAnnotation>
EditLeaders
Anymodificationstoleaderannotationthatchangeitspositionaffectthepositionoftheendpointoftheassociatedleader.Also,rotatingtheannotationcausestheleaderhookline(ifany)torotate.
Toresizealeader,youcanscaleit.Scalingupdatesonlythescaleoftheselectedobject.Forexample,ifyouscaletheleader,theannotationstaysinthesamepositionrelativetotheleaderendpointbutisn'tscaled.
Inadditiontoscaling,youcanalsomove,mirror,androtatealeader.UsetheScaleEntity,Move,Mirror,andRotatemethodstoedittheleader.YoucanalsochangethetextstyleassociatedwiththeannotationbyusingtheStyleNameproperty.
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>
UseGeometricTolerances
Geometrictolerancingshowsdeviationsofform,profile,orientation,location,andrunoutofafeature.Youaddgeometrictolerancesinfeaturecontrolframes.Theseframescontainallthetoleranceinformationforasingledimension.
Formoreinformationaboutusingfeaturecontrolframesandworkingwithgeometrictolerances,see“AddGeometricTolerances”intheUser'sGuide.
Topicsinthissection
CreateGeometricTolerancesEditTolerances
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>UseGeometricTolerances>
CreateGeometricTolerances
Tocreateageometrictolerance,usetheAddTolerancemethod.Thismethodrequiresthreevaluesasinput:thetextstringcomprisingthetolerancesymbol,thelocationinthedrawingtoplacethetolerance,andadirectionalvectorspecifyingthedirectionofthetolerance.Youcanalsocopy,move,erase,scale,androtatetolerances.
Createageometrictolerance
Thisexamplecreatesasimplegeometrictoleranceinmodelspace.
SubCh5_CreateTolerance()
DimtoleranceObjAsAcadTolerance
DimtextStringAsString
DiminsertionPoint(0To2)AsDouble
Dimdirection(0To2)AsDouble
'Definethetoleranceobject
textString="HereistheFeatureControlFrame"
insertionPoint(0)=5
insertionPoint(1)=5
insertionPoint(2)=0
direction(0)=1
direction(1)=1
direction(2)=0
'Createthetoleranceobjectinmodelspace
SettoleranceObj=ThisDrawing.ModelSpace._
AddTolerance(textString,insertionPoint,direction)
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
DimensionsandTolerances>UseGeometricTolerances>
EditTolerances
Tolerancesareinfluencedbyseveralsystemvariables:DIMCLRDcontrolsthecolorofthefeaturecontrolframe;DIMCLRTcontrolsthecolorofthetolerancetext;DIMGAPcontrolsthegapbetweenthefeaturecontrolframeandthetext;DIMTXTcontrolsthesizeofthetolerancetext;andDIMTXTSTYcontrolsthestyleofthetolerancetext.UsetheSetVariablemethodtosetthevaluesofsystemvariables.
Pleasesendusyourcommentaboutthispage
<$nopage>MenuGroupscollection:<$nopage>menuobjects:<$startrange>InsertInMenuBarmethod:examplecode,separators:addingtomenus,PopupMenuItemobject:AddSeparatormethod,AddSeparatormethod,usingTypeproperty,Labelproperty:acceleratorkey,PopupMenuItemobject:acceleratorkeys,assigning,submenus:adding,submenus:positioning,PopupMenuobject:creatingsubmenus,menus:creatingsubmenus,<$nopage>cascadingmenus.<$endrange>InsertInMenuBarmethod:examplecode,menus:deleting,PopupMenuobject:deletingmenuitems,PopupMenuItemobject:deletingmenuitems,Deletemethod:examplecode,PopupMenuItemobject:Tagproperty,PopupMenuItemobject:Labelproperty,PopupMenuItemobject:Captionproperty,PopupMenuItemobject:Macroproperty,PopupMenuItemobject:HelpStringproperty,PopupMenuItemobject:Enableproperty,PopupMenuItemobject:Checkproperty,menus:enabling,menus:disabling,menus:checking,menus:positioning,PopupMenuItemobject:Indexproperty,PopupMenuItemobject:Typeproperty,PopupMenuItemobject:Submenuproperty,PopupMenuItemobject:Parentproperty,PopupMenuItemobject:Parentproperty,menus:typeofmenuitem,menus:returningsubmenus,menus:assigningmenuitems,menus:menumacros,specialcharacters,InsertInMenuBarmethod:examplecode,Toolbarscollection:Addmethod,Toolbarscollection:Nameproperty,Nameproperty:toolbars,Toolbarobject:naming,Addmethod:toolbars,examplecode,Toolbarobject:examplecode,AddToolbarButtonmethod,Toolbarobject:AddToolbarButtonmethod,ToolbarItemobject,ToolbarItemobject:positioningtoolbarbuttons,ToolbarItemobject:Nameproperty,Nameproperty:ToolbarItemobject,ToolbarItemobject:HelpStringproperty,HelpStringproperty:ToolbarItemobject,ToolbarItemobject:Macroproperty,Macroproperty:ToolbarItemobject,ToolbarItemobject:creatingflyoutbutton,flyoutbutton,Toolbarobject:examplecode,AddToolbarButtonmethod:examplecode,ToolbarItemobject:examplecode,Toolbarobject:AddSeparatormethod,Toolbarobject:usingTypeproperty,separators:addingtotoolbars,SetBitmapsmethod,ToolbarItemobject:SetBitmapsmethod,GetBitmapsmethod,ToolbarItemobject:GetBitmaps,SetBitmapsmethod:SmallIconNameparameter,SetBitmapsmethod:LargeIconNameparameter,Typeproperty:examplecode,GetBitmapsmethod:examplecode,ToolbarItemobject:examplecode,flyouttoolbars:AddToolbarButtonmethod,AddToolbarButtonmethod:creatingflyouttoolbars,Toolbarobject:flyouttoolbars,creating,AddToolbarButtonmethod:examplecode,Toolbarobject:examplecode,ToolbarItemobject:examplecode,flyouttoolbars:examplecode,AttachToolbarToFlyoutmethod,examplecode,Visibleproperty:examplecode,Toolbarobject:Float
method,Floatmethod:floatingtoolbars,Toolbarobject:Dockmethod,Dockmethod:dockingtoolbars,Toolbarobject:Dockedproperty,Dockmethod:examplecode,Toolbarobject:examplecode,ToolbarItemobject:deleting,ToolbarItemobject:Tagproperty,Tagproperty:ToolbarItemobject,ToolbarItemobject:Nameproperty,Nameproperty:ToolbarItemobject,ToolbarItemobject:Macroproperty,Macroproperty:ToolbarItemobject,ToolbarItemobject:HelpStringproperty,HelpStringproperty:ToolbarItemobject,ToolbarItemobject:Indexproperty,Indexproperty:ToolbarItemobject,ToolbarItemobject:Typeproperty,Typeproperty:ToolbarItemobject,ToolbarItemobject:Flyoutproperty,Flyoutproperty:ToolbarItemobject,ToolbarItemobject:Parentproperty,Parentproperty:ToolbarItemobject,PopupMenuItemobject:writingmacros,ToolbarItemobject:writingmacros,macros:inmenus,macros:intoolbars,macros:guidelinesforwriting,PICKAUTOsystemvariable,PICKADDsystemvariable,macros:specialcharacters(table),menumacros:specialcharacters(table),toolbarmacros:specialcharacters(table),macros:terminating,terminatingmacros:codeexamples,macros:userinput,userinputpausingmacros,LAYERcommand:macros,macros:LAYERcommand,SELECTcommand:macros,macros:SELECTcommand,backslash(\\):inmacros,macros:backslashcharacter,macros:delays(list),pausingmacros:delays(list),macros:cancelingcommands,macros:commandhandling,macros:useofrepetition,macros:objectselection,single,Singleobjectselectioninmacros,ERASEcommand:macros,macros:ERASEcommand,ToolbarItemobject:status-lineHelpmessage,PopupMenuItemobject:status-lineHelpmessage,status-lineHelp,formenusandtoolbars,Help,statusline:formenusandtoolbars,InsertInMenuBarmethod:examplecode,cursormenus:Shortcutmenuproperty,cursormenus:addingnewitems,<$nopage>right-clickmenu.
CustomizeToolbarsandMenus
AutoCADActiveXAutomationgivesyouextensivecontroloverthecustomizationofmenusandtoolbarsinthecurrentAutoCADsession.
UsingAutoCADActiveX/VBA,youcaneditoraugmenttheexistingmenu
structure,oryoucancompletelyreplacethecurrentmenustructure.Youcanalsomanipulatetoolbarsandright-clickmenus.
Menucustomizationcanimproveproductivitybyexposingapplication-specifictasksorbycondensingtaskswithmultiplestepsintoasinglemenuselection.
Forinformationaboutcustomizingmenusandtoolbarsinadditiontotheinformationinthissection,seetheCustomizationGuide.
Topicsinthissection
UnderstandtheMenuBarandMenuGroupsCollectionsLoadMenuGroupsChangetheMenuBarCreateandEditPull-DownandShortcutMenusCreateandEditToolbarsCreateMacrosCreateStatus-LineHelpforMenuItemsandToolbarItemsAddEntriestotheRight-ClickMenu
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>
UnderstandtheMenuBarandMenuGroupsCollections
AutoCAD®ActiveX®providesseveralmenu-relatedobjects.ThetwomostimportantaretheMenuBarcollectionandtheMenuGroupscollection.TheMenuBarcollectioncontainsallthemenusthataredisplayedintheAutoCADmenubar.
TheMenuGroupscollectioncontainsthemenugroupsthatareloadedinthecurrentAutoCADsession.ThesemenugroupscontainallthemenusthatareavailabletotheAutoCADsession,someorallofwhichmaybedisplayedontheAutoCADmenubar.Inadditiontothemenus,themenugroupsalsocontainallthetoolbarsthatareavailabletothecurrentAutoCADsession.Menugroupsmayalsorepresenttilemenus,screenmenus,ortabletmenus.
EachmenugroupcontainsaPopupMenuscollectionandaToolbarscollection.ThePopupMenuscollectioncontainsallthemenuswithinthemenugroup.Likewise,theToolbarscollectioncontainsallthetoolbarswithinthemenugroup.
EachPopupMenuisactuallyacollectionthatcontainsanindividualobjectforeachmenuitemthatappearsonthatmenu.Likewise,eachToolbarisalsoacollectionthatcontainsanindividualobjectforeachtoolbaritemthatappearsonthattoolbar.
Pleasesendusyourcommentaboutthispage
<$nopage>MenuGroupscollection:
CustomizeToolbarsandMenus>
LoadMenuGroups
MenugroupsareloadedintoAutoCADusingtheLoadmethod.Forexample,thefollowingcodeloadsthecustomizationfileacad.cui:
ThisDrawing.Application.MenuGroups.Load"acad.cui"
WhenusingtheLoadmethod,settheBaseMenuparametertoTRUEtoloadanewmenugrouptothemenubar.ThiswillloadthemenugroupasabasemenuinthesamemannerastheMENUcommandinAutoCAD.
Toloadanewmenugroupasapartialmenu,omittheBaseMenuparameter.ThiswillloadthemenugroupinthesamemannerastheMENULOADcommandinAutoCAD.OnceloadedintotheMenuGroupscollection,partialmenuscanbeinsertedintothemenubarbyusingtheInsertMenuInMenuBarmethodortheInsertInMenuBarmethod.
Onceamenugrouphasbeenloaded,allthemenusandtoolbarsdefinedbythatmenugroupareavailableforuse.Youcan
Addnewmenustothemenubar
Removemenusfromthemenubar
Rearrangemenusonthemenubar
Addnewitemstoanexistingmenuortoolbar
Removeitemsfromanexistingmenuortoolbar
Createnewmenusandtoolbars
Floatordocktoolbars
Enableordisablemenuandtoolbaritems
Checkoruncheckamenuitem
Changethetag,label,orhelpstringofamenuortoolbaritem
Reassignthemacrosassociatedtoamenuortoolbaritem
Note YoucanonlyeditpopupmenusandtoolbarsusingActiveXAutomation.However,youcanuseActiveXAutomationtoloadandunloadothermenutypessuchasimagetilemenuitems,screenmenus,ortabletmenus.
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>
ChangetheMenuBar
Asyouhavealreadyseen,themenubarcanbecompletelyreplacedbyanewmenugroupifthatgroupisloadedasthebasemenu.Additionally,individualmenusonthemenubarcanbeadded,removed,orrearranged.
Topicsinthissection
InsertMenusintheMenuBarRemoveMenusfromtheMenuBarRearrangeMenuItemsontheMenuBar
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>ChangetheMenuBar>
InsertMenusintheMenuBar
Toinsertanexistingmenuinthemenubar,usetheInsertMenuInMenuBarortheInsertInMenuBarmethod.Bothmethodsaccomplishthesamegoal—theyinsertanexistingmenuintothemenubar.
Thedifferencebetweenthetwomethodsistheobjectfromwhichtheyarecalled.TheInsertMenuInMenuBarmethodiscalledfromthePopupMenuscollection.Usingthismethodyoucaninsertanymenufromthecollectionintoaspecifiedlocationonthemenubar.Thismethodrequiresasinputthenameofthemenutoinsertandthelocationonthemenubartoinsertit.
TheInsertInMenuBarmethodiscalleddirectlyfromthePopupMenuobjecttobeinserted.Theonlyinputthismethodrequiresisalocationonthemenubar.Thenameofthemenuisnotneededbecauseyouarecallingthemethoddirectlyfromtheobjecttobeinserted.
Youshouldusewhichevermethodismoreconvenientforyourapplication.
Insertamenuinthemenubar
ThisexamplecreatesanewmenucalledTestMenuandinsertsamenuitemintoit.ThemenuitemisassignedtheOPENcommand.Themenuisthendisplayedonthemenubar.
SubCh6_InsertMenu()
'Defineavariableforthecurrentmenugroup
DimcurrMenuGroupAsAcadMenuGroup
SetcurrMenuGroup=ThisDrawing.Application._
MenuGroups.Item(0)
'Createanewmenu
DimnewMenuAsAcadPopupMenu
SetnewMenu=currMenuGroup.Menus.Add("TestMenu")
'Declarethevariablesforthemenuitem
DimnewMenuItemAsAcadPopupMenuItem
DimopenMacroAsString
'AssignthemacrostringtheVBequivalentof
'"ESCESC_open"andcreatethemenuitem
openMacro=Chr(3)+Chr(3)+"_open"
SetnewMenuItem=newMenu.AddMenuItem(newMenu.Count+1,_
"Open",openMacro)
'Displaythemenuonthemenubar
currMenuGroup.Menus.InsertMenuInMenuBar"TestMenu",""
EndSub
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>ChangetheMenuBar>
RemoveMenusfromtheMenuBar
Toremoveamenufromthemenubar,usetheRemoveMenuFromMenuBarortheRemoveFromMenuBarmethod.Bothmethodsaccomplishthesamegoal—theyremoveamenufromthemenubar.
Thedifferencebetweenthetwomethodsistheobjectfromwhichtheyarecalled.TheRemoveMenuFromMenuBarmethodiscalledfromthePopupMenuscollection.Thismethodrequiresasinputthenameofthemenutoremove,orthelocationonthemenubarofthemenutoremove.Forexample,thefollowingstatementremovesthemenuaddedinInsertamenuinthemenubar:
currMenuGroup.Menus.RemoveMenuFromMenuBar("TestMenu")
TheRemoveFromMenuBarmethodiscalleddirectlyfromthePopupMenuobjecttoberemoved.Thismethoddoesnotrequireanyinput.Thenameofthemenuisnotneededbecauseyouarecallingthemethoddirectlyfromtheobjecttoberemoved.
Youshouldusewhichevermethodismoreconvenientforyourapplication.
Note Menusthathavebeenremovedfromthemenubararestillavailableintheirdesignatedmenugroup.Theyaresimplynolongervisibletotheuser.
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>ChangetheMenuBar>
RearrangeMenuItemsontheMenuBar
Torearrangemenusonthemenubar,insertandremovemenusuntilthedesiredconfigurationisachieved.
Movethefirstmenutotheendofthemenubar
Thisexampleremovesthefirstmenuonthemenubarandinsertsitasthelastmenuonthemenubar.
SubCh6_MoveMenu()
'Defineavariabletoholdthemenutobemoved
DimmoveMenuAsAcadPopupMenu
DimMyMenuBarAsAcadMenuBar
SetMyMenuBar=ThisDrawing.Application.menuBar
'SetmoveMenuequaltothefirstmenudisplayed
'onthemenubar
SetmoveMenu=MyMenuBar.Item(0)
'Removethefirstmenufromthemenubar
MyMenuBar.Item(0).RemoveFromMenuBar
'Addthemenubackintothemenubar
'inthelastpositiononthebar
moveMenu.InsertInMenuBar(MyMenuBar.count)
EndSub
Pleasesendusyourcommentaboutthispage
<$nopage>menuobjects:<$startrange>InsertInMenuBarmethod:examplecode,separators:addingtomenus,PopupMenuItemobject:AddSeparatormethod,AddSeparatormethod,usingTypeproperty,Labelproperty:acceleratorkey,PopupMenuItemobject:acceleratorkeys,assigning,submenus:adding,submenus:positioning,PopupMenuobject:creatingsubmenus,menus:creatingsubmenus,<$nopage>cascadingmenus.<$endrange>InsertInMenuBarmethod:examplecode,menus:deleting,PopupMenuobject:deletingmenuitems,PopupMenuItemobject:deletingmenuitems,Deletemethod:examplecode,PopupMenuItemobject:Tagproperty,PopupMenuItemobject:Labelproperty,PopupMenuItemobject:Captionproperty,PopupMenuItemobject:Macroproperty,PopupMenuItemobject:HelpStringproperty,PopupMenuItemobject:Enableproperty,PopupMenuItemobject:Checkproperty,menus:enabling,menus:disabling,menus:checking,menus:positioning,PopupMenuItemobject:Indexproperty,PopupMenuItemobject:Typeproperty,PopupMenuItemobject:Submenuproperty,PopupMenuItemobject:Parentproperty,PopupMenuItemobject:Parentproperty,menus:typeofmenuitem,menus:returningsubmenus,menus:assigningmenuitems,menus:menumacros,specialcharacters,InsertInMenuBarmethod:examplecode,">
CustomizeToolbarsandMenus>
CreateandEditPull-DownandShortcutMenus
AutoCADActiveX/VBAhastheabilitytocustomizetwotypesofAutoCADmenus:pull-downmenusandshortcutmenus(sometimescalledcursormenus).Bothpull-downandshortcutmenusaredisplayedascascadingmenus.TheshortcutmenucanprovidequickaccesstofrequentlyusedmenuitemssuchasObjectSnapmodes.
Apull-downmenucancontainupto999menuitems.Ashortcutmenucancontainupto499menuitems.Bothlimitsincludeallmenusinthehierarchy.Ifthenumberofmenuitemsinamenuexceedstheselimits,AutoCADignorestheextraitems.Ifapull-downorshortcutmenuistallerthantheavailablespaceonthegraphicsscreen,itistruncatedtofitonthescreen.
Pull-downmenusarealwayspulleddownfromthemenubar,buttheshortcut
menuisalwaysdisplayedatornearthecrosshairsonthegraphicsscreen.Thehandlingforbothmenutypesisthesameexcepttheshortcutmenucaptionisn'tincludedonthemenubar.Theshortcutmenucaptionisnotdisplayedatall.Accesstotheshortcutmenuisthroughasinglemenuinthebasemenugroup.TheshortcutmenucanbeidentifiedwiththeShortcutMenuproperty.IftheShortcutMenupropertyreturnsTRUE,thenthequeriedmenuistheshortcutmenuforthegroup.
Topicsinthissection
CreateNewMenusAddNewMenuItemstoaMenuAddSeparatorstoaMenuAssignanAcceleratorKeytoaMenuItemCreateCascadingSubmenusDeleteMenuItemsfromaMenuExplorethePropertiesofMenuItems
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateandEditPull-DownandShortcutMenus>
CreateNewMenus
Tocreateanewmenu,usetheAddmethodtoaddanewPopupMenuobjecttothePopupMenuscollection.
Tocreateanewshortcutmenu,youmustdeleteanexistingshortcutmenu.Therecanbeonlyoneshortcutmenupermenugroup.Ifthereisnoothershortcutmenuinamenugroup,youcanaddamenuwiththelabel“POP0”.ThiswilltellAutoCADyouwanttocreateashortcutmenu.
TheAddmethodrequiresasinputthename(label)ofthemenutoadd.Thisnamebecomesthetitleforthemenuwhenitisloadedonthemenubar.Thenameisalsotheeasiestwayofidentifyingthemenuwithinthecollection.
Themenunamecanbeasimplestringoritcancontainspecialcodes.Youcanchangethenameofamenuonceithasbeencreated.Tochangethenameofanexistingmenu,usetheNamepropertyforthatmenu.
Createanewpopupmenu
Thisexamplecreatesanewpopupmenucalled“TestMenu”inthefirstmenugroupoftheMenuGroupscollection.
SubCh6_CreateMenu()
DimcurrMenuGroupAsAcadMenuGroup
SetcurrMenuGroup=ThisDrawing.Application.MenuGroups.Item(0)
'Createthenewmenu
DimnewMenuAsAcadPopupMenu
SetnewMenu=currMenuGroup.Menus.Add("TestMenu")
EndSub
Pleasesendusyourcommentaboutthispage
<$nopage>menuobjects:<$startrange>InsertInMenuBarmethod:examplecode,">
CustomizeToolbarsandMenus>CreateandEditPull-DownandShortcutMenus>
AddNewMenuItemstoaMenu
Toaddanewmenuitemtoamenu,usetheAddMenuItemmethod.ThismethodcreatesanewPopupMenuItemobjectandaddsittothedesignatedmenu.
TheAddMenuItemmethodtakesfourparametersasinput:Index,Label,Tag,andMacro.
Topicsinthissection
SpecifytheIndexParameterSpecifytheLabelParameterSpecifytheTagParameterSpecifytheMacroParameter
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateandEditPull-DownandShortcutMenus>AddNewMenuItemstoaMenu>
SpecifytheIndexParameter
TheIndexparameterisanintegerthatspecifiesthepositionofthenewmenuitemwithinthemenu.Theindexbeginswithpositionzero(0)asthefirstpositiononthemenuafterthetitle.Toaddthenewmenuitemtotheendofamenu,settheIndexparameterequaltotheCountpropertyofthemenu.(TheCountpropertyofthemenurepresentsthetotalnumberofmenuitemsonthatmenu.)
Thefirstindexpositioniszero(0)andtheseparatorsarelistedasindividualmenuitemswiththeirownindexposition.TheCountpropertyforthemenupicturedwouldbesix(6).ToaddamenuitembetweenTileHorizontallyandTileVertically,settheIndexparametertotwo(2),whichistheindexoftheTileVerticallymenuitem.Thisinsertsyournewmenuitemintoindextwo(2)andbumpsalltheremainingmenuitemsdownoneindexposition.
Onceamenuitemhasbeencreated,youcannotchangetheindexofthemenuitemthroughtheIndexproperty.Tochangetheindexofanexistingmenuitemyoumustdeleteandre-addthemenuitemtoadifferentposition,oraddordeletesurroundingmenuitemsuntilaproperplacementisachieved.
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateandEditPull-DownandShortcutMenus>AddNewMenuItemstoaMenu>
SpecifytheLabelParameter
Alabelisastringthatdefinesthecontentandformattingofmenuitems.MenuitemlabelscancontainDIESELstringexpressionsthatconditionallyalterthelabelseachtimetheyaredisplayed.
InadditiontotheDIESELstringexpressions,thelabelmaycontainspecialcodes.Forexample,anampersand(&)placeddirectlybeforeacharacterspecifiesthatcharacterastheacceleratorkey.
ThetexttheuserseesdisplayedforthemenuitemiscalledtheCaption,anditisderivedfromthelabelbyinterpretingalltheDIESELstringexpressionsandspecialcodescontainedinthelabel.Forexample,thelabel“&Edit”producesthecaption“Edit.”
Onceamenuitemhasbeencreated,youcanchangethelabelforthemenuitemusingtheLabelproperty.
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateandEditPull-DownandShortcutMenus>AddNewMenuItemstoaMenu>
SpecifytheTagParameter
Thetag,ornametag,isastringconsistingofalphanumericandunderscore(_)characters.Thisstringuniquelyidentifiesthemenuitemwithinagivenmenu.
Onceamenuitemhasbeencreated,youcanchangethetagforthemenuitemusingtheTagStringproperty.
Pleasesendusyourcommentaboutthispage
<$startrange>InsertInMenuBarmethod:examplecode,">
CustomizeToolbarsandMenus>CreateandEditPull-DownandShortcutMenus>AddNewMenuItemstoaMenu>
SpecifytheMacroParameter
Amacroisaseriesofcommandsthatexecutesspecificactionswhenamenuitemisselected.Menumacroscansimplyberecordingsofkeystrokesthataccomplishatask,ortheycanbeacomplexcombinationofcommands,AutoLISP,DIESEL,orActiveXprogrammingcode.
Onceamenuitemhasbeencreated,youcanchangethemacroforthemenuitemusingtheMacroproperty.
Addmenuitemstoapopupmenu
Thisexamplecreatesanewmenucalled“TestMenu”andinsertsamenuitem.Themenuitemisgiventhename“Open,”andthemacroassignedtothemenuitemistheOPENcommand.
SubCh6_AddAMenuItem()
DimcurrMenuGroupAsAcadMenuGroup
SetcurrMenuGroup=ThisDrawing.Application.MenuGroups.Item(0)
'Createthenewmenu
DimnewMenuAsAcadPopupMenu
SetnewMenu=currMenuGroup.Menus.Add("TestMenu")
'Addamenuitemtothenewmenu
DimnewMenuItemAsAcadPopupMenuItem
DimopenMacroAsString
'AssignthemacrotheVBAequivalentof"ESCESC_open"
openMacro=Chr(3)+Chr(3)+"_open"
SetnewMenuItem=newMenu.AddMenuItem_
(newMenu.count+1,"Open",openMacro)
'Displaythemenuonthemenubar
newMenu.InsertInMenuBar_
(ThisDrawing.Application.menuBar.count+1)
EndSub
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateandEditPull-DownandShortcutMenus>
AddSeparatorstoaMenu
Toaddaseparatortoamenu,usetheAddSeparatormethod.ThismethodcreatesanewPopupMenuItemobjectandaddsittothedesignatedmenu.ThiskindofPopupMenuItemobjectisassignedthetypeofacSeparator.ThetypeofamenuitemcanbefoundthroughtheTypeproperty.
TheAddSeparatormethodtakestheIndexparameterasitsonlyinput.TheIndexparameterisanintegerthatspecifiesthepositionoftheseparatorwithinthemenu.Theindexbeginswithpositionzero(0)asthefirstpositiononthemenuafterthetitle.
SeeEnableanddisablemenuitemsforanexampleofaddingseparatorstoamenu.
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateandEditPull-DownandShortcutMenus>
AssignanAcceleratorKeytoaMenuItem
ToassigntheacceleratorkeyforamenuitemthroughAutoCADActiveX/VBA,usetheLabelpropertyofthegivenmenuitem.Tospecifyanacceleratorkey,inserttheASCIIequivalentofanampersand(&)inthelabeldirectlyinfrontofthecharactertobeusedastheaccelerator.Forexample,thelabelChr(Asc("&"))+"Edit"willbedisplayedas“Edit,”withthecharacter“E”beingusedastheacceleratorkey.
Addacceleratorkeystomenus
ThisexamplerepeatstheexamplefromAddmenuitemstoapopupmenu,addingacceleratorkeysforboththe“TestMenu”and“Open”menus.The“s”isusedastheacceleratorkeyforthe“TestMenu”menuandthe“O”isusedastheacceleratorkeyforthe“Open”menu.
SubCh6_AddAMenuItem()
DimcurrMenuGroupAsAcadMenuGroup
SetcurrMenuGroup=ThisDrawing.Application.MenuGroups.Item(0)
'Createthenewmenu
DimnewMenuAsAcadPopupMenu
SetnewMenu=currMenuGroup.Menus.Add_
("Te"+Chr(Asc("&"))+"stMenu")
'Addamenuitemtothenewmenu
DimnewMenuItemAsAcadPopupMenuItem
DimopenMacroAsString
'AssignthemacrotheVBAequivalentof"ESCESC_open"
openMacro=Chr(3)+Chr(3)+"_open"
SetnewMenuItem=newMenu.AddMenuItem_
(newMenu.count+1,Chr(Asc("&"))_
+"Open",openMacro)
'Displaythemenuonthemenubar
newMenu.InsertInMenuBar_
(ThisDrawing.Application.menuBar.count+1)
EndSub
Pleasesendusyourcommentaboutthispage
<$nopage>cascadingmenus.<$endrange>InsertInMenuBarmethod:examplecode,">
CustomizeToolbarsandMenus>CreateandEditPull-DownandShortcutMenus>
CreateCascadingSubmenus
Toaddacascadingsubmenu,createasubmenuusingtheAddSubmenumethod.ThismethodcreatesanewPopupMenuItemobjectandaddsittothedesignatedmenu.ThisspecialkindofPopupMenuItemobjectisassignedthetypeofacSubmenu.
TheAddSubmenumethodtakesthreeparametersasinput:Index,Label,andTag.
TheIndexparameterisanintegerthatspecifiesthepositionofthenewmenuitemwithinthemenu.Theindexbeginswithpositionzero(0)asthefirstpositiononthemenuafterthetitle.Toaddthenewmenuitemtotheendofamenu,settheIndexparameterequaltotheCountpropertyofthemenu.(TheCountpropertyofthemenurepresentsthetotalnumberofmenuitemsonthatmenu.)
TheLabelparameterisastringthatdefinesthecontentandformattingofmenuitems.ThetextthattheuserseesdisplayedforthemenuitemiscalledtheCaption,anditisderivedfromthelabelbyinterpretingalltheDIESELstringexpressionsandspecialcodescontainedinthelabel.Forexample,thelabel“&Edit”producesthecaption“Edit.”
TheTagparameter,ornametag,isastringconsistingofalphanumericandunderscore(_)characters.Thisstringuniquelyidentifiesthemenuitemwithinagivenmenu.
TheAddSubmenumethoddoesnotreturnthePopupMenuItemobjectthatitcreates.Instead,itreturnsthenewmenuthatthesubmenupointsto.Thenewmenu,whichisreturnedasaPopupMenuobject,canthenbepopulatedasanormalmenuwouldbe.Forinformationonpopulatingamenu,seeAddNew
MenuItemstoaMenu.
Createandpopulateasubmenu
Thisexamplecreatesanewmenucalled“TestMenu”andaddsittoasubmenucalled“OpenFile.”Thesubmenuisthenpopulatedwithamenuitemcalled“Open,”whichopensadrawingwhenexecuted.Finally,themenuisdisplayedonthemenubar.
SubCh6_AddASubMenu()
DimcurrMenuGroupAsAcadMenuGroup
SetcurrMenuGroup=ThisDrawing.Application.MenuGroups.Item(0)
'Createthenewmenu
DimnewMenuAsAcadPopupMenu
SetnewMenu=currMenuGroup.Menus.Add("TestMenu")
'Addthesubmenu
DimFileSubMenuAsAcadPopupMenu
SetFileSubMenu=newMenu.AddSubMenu("","OpenFile")
'Addamenuitemtothesubmenu
DimnewMenuItemAsAcadPopupMenuItem
DimopenMacroAsString
'AssignthemacrotheVBequivalentof"ESCESC_open"
openMacro=Chr(3)+Chr(3)+"_open"
SetnewMenuItem=FileSubMenu.AddMenuItem_
(newMenu.count+1,"Open",openMacro)
'Displaythemenuonthemenubar
newMenu.InsertInMenuBar_
(ThisDrawing.Application.menuBar.count+1)
EndSub
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateandEditPull-DownandShortcutMenus>
DeleteMenuItemsfromaMenu
Toremovemenuitemsfromamenu,usetheDeletemethodfoundonthemenuitem.
Warning Ifyoudeleteamenuitem,donotcallanothermethodorpropertythatwoulddirectlyorindirectlycausethesameCUIfiletobeloadedagainwithinthesamemacro.Forexample,afterdeletingamenuitem,donotusetheMenuGroup.LoadmethodorthePreferences.Profiles.ActiveProfileproperty,orissuea"Menuload"commandusingtheDocument.SendCommandmethod.TheseitemsdirectlyorindirectlycausetheloadingofCUIfiles.Youshouldonlyusethesemethodsorpropertiesinaseparatemacro.
Deleteamenuitemfromamenu
Thisexampleaddsamenuitemtotheendofthelastmenudisplayedonthemenubar.Itthendeletesthemenuitem.
SubCh6_DeleteMenuItem()
DimLastMenuAsAcadPopupMenu
SetLastMenu=ThisDrawing.Application.menuBar._
Item(ThisDrawing.Application.menuBar.count-1)
'Addamenuitem
DimnewMenuItemAsAcadPopupMenuItem
DimopenMacroAsString
'AssignthemacrotheVBequivalentof"ESCESC_open"
openMacro=Chr(3)+Chr(3)+"_open"
SetnewMenuItem=LastMenu.AddMenuItem_
(LastMenu.count+1,"Open",openMacro)
'Removethemenuitemfromthemenu
newMenuItem.Delete
EndSub
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateandEditPull-DownandShortcutMenus>
ExplorethePropertiesofMenuItems
Allmenuitemssharethefollowingproperties:
TagString
Atag,ornametag,isastringconsistingofalphanumericandunderscore(_)characters.Thisstringuniquelyidentifiesthemenuitemwithinagivenmenu.Tagsidentifytheacceleratorkeys(keyboardkeysequences)thatcorrespondtothemenuitem.YoucanreadorwritethevalueofatagbyusingtheTagStringproperty.
Label
Alabelisastringthatdefinesthecontentandformattingofmenuitems.MenuitemlabelscancontainDIESELstringexpressionsthatconditionallyalterthelabelseachtimetheyaredisplayed.YoucanreadorwritethevalueofalabelbyusingtheLabelproperty.
Caption
Acaptionisthetextthattheuserseesdisplayedonthemenu.Thispropertyisread-onlyandisderivedfromtheLabelpropertybyremovinganyDIESELstringexpressions.YoucanreadthevalueofacaptionbyusingtheCaptionproperty.
Macro
Amacroisaseriesofcommandsthatexecutesspecificactionswhenamenuitemisselected.Menumacroscansimplyberecordingsofkeystrokesthataccomplishatask,ortheycanbeacomplexcombinationofcommands,AutoLISP,DIESEL,orActiveXprogrammingcode.YoucanreadorwritethevalueofamenumacrobyusingtheMacroproperty.
HelpString
AhelpstringisthetextstringthatappearsintheAutoCADstatuslinewhenauserhighlightsamenuitemforselection.YoucanreadorwritethevalueofahelpstringbyusingtheHelpStringproperty.
Enable
UsingtheEnableproperty,youcanenableordisableamenuitem.YoucanalsoreadtheEnablepropertytodetermineifamenuitemiscurrentlyenabledordisabled.UsingthispropertytoenableordisableamenuitemoverridesanysettingforenablingintheDIESELexpressionofthemenuitem.SeeExplorethePropertiesofMenuItemsforanexampleofdisablingmenuitems.
Check
UsingtheCheckpropertyyoucancheckoruncheckamenuitem.YoucanalsoreadtheCheckpropertytodetermineifamenuitemiscurrentlycheckedorunchecked.UsingthispropertytocheckoruncheckamenuitemoverridesanysettingforcheckingintheDIESELexpressionofthemenuitem.
Index
Theindexofamenuitemspecifiesthepositionofthatmenuitemonthemenuonwhichitbelongs.Theindexpositionofamenualwaysbeginswithposition0.Forexample,iftheitemisthefirstitemonamenu,itreturnsanindexpositionof0.Ifitistheseconditemonamenu,itreturnsanindexpositionof1andsoon.
Type
YoucandeterminethetypeofamenuitembyusingtheTypeproperty.Amenuitemcanbeoneofthefollowingtypes:aregularmenu,aseparator,ortheheadingforasubmenu.Iftheitemisaregularmenuitem,thispropertyreturnsacMenuItem.Iftheitemisaseparator,thispropertyreturnsacMenuSeparator.Iftheitemisaheadingforasubmenu,thispropertyreturnsacSubMenu.
SubMenu
YoucanfindthesubmenubyusingtheSubMenuproperty.Ifthemenuitem
isofthetypeacSubMenu,thispropertyreturnsthemenuthatisattachedasthesubmenu,orembeddedmenu.TheembeddedmenuisreturnedasaPopupMenuobject.IfthemenuitemisnotofthetypeacSubMenu,thispropertyreturnsanerror.
Parent
YoucanfindthemenutowhichamenuitembelongsbyusingtheParentproperty.Thispropertyreturnsthemenuonwhichthemenuitemresides.TheparentmenuisreturnedasaPopupMenuobject.
Enableanddisablemenuitems
Thisexamplecreatesanewmenucalled“TestMenu”andinsertstwomenuitems.ThesecondmenuitemisthendisabledusingtheEnablepropertyandthemenuisdisplayedonthemenubar.
SubCh6_DisableMenuItem()
DimcurrMenuGroupAsAcadMenuGroup
SetcurrMenuGroup=ThisDrawing.Application.MenuGroups.Item(0)
'Createthenewmenu
DimnewMenuAsAcadPopupMenu
SetnewMenu=currMenuGroup.Menus.Add("TestMenu")
'Addtwomenuitemsandamenuseparatortothenewmenu
DimMenuEnableAsAcadPopupMenuItem
DimMenuDisableAsAcadPopupMenuItem
DimMenuSeparatorAsAcadPopupMenuItem
DimopenMacroAsString
'AssignthemacrotheVBequivalentof"ESCESC_open"
openMacro=Chr(3)+Chr(3)+"_open"
SetMenuEnable=newMenu.AddMenuItem_
(newMenu.count+1,"OpenEnabled",openMacro)
SetMenuSeparator=newMenu.AddSeparator("")
SetMenuDisable=newMenu.AddMenuItem_
(newMenu.count+1,"OpenDisabled",openMacro)
'Disablethesecondmenuitem
MenuDisable.Enable=False
'Displaythemenuonthemenubar
newMenu.InsertInMenuBar_
(ThisDrawing.Application.menuBar.count+1)
EndSub
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>
CreateandEditToolbars
UsingAutoCADActiveX/VBAyoucancreateandedittoolbarswithinanexistingmenugroup.
Topicsinthissection
CreateNewToolbarsAddNewToolbarButtonstoaToolbarAddSeparatorstoaToolbarDefinetheToolbarButtonImageCreateFlyoutToolbarsFloatandDockToolbarsDeleteToolbarButtonsfromaToolbarExplorethePropertiesofToolbarItems
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateandEditToolbars>
CreateNewToolbars
Tocreateanewtoolbar,usetheAddmethodtoaddanewToolbarobjecttotheToolbarscollection.
TheAddmethodrequiresasinputthenameofthetoolbartoadd.Thenameisastringofalphanumericcharacterswithnopunctuationotherthanadash(-)oranunderscore(_).Thenameistheeasiestwayofidentifyingthetoolbarwithinthecollection.
Youcanchangethenameofatoolbaronceithasbeencreated.Tochangethenameofanexistingtoolbar,usetheNamepropertyforthattoolbar.
Createanewtoolbar
Thisexamplecreatesanewtoolbarcalled“TestToolbar”inthefirstmenugroupintheMenuGroupscollection.
SubCh6_CreateToolbar()
DimcurrMenuGroupAsAcadMenuGroup
SetcurrMenuGroup=ThisDrawing.Application.MenuGroups.Item(0)
'Createthenewtoolbar
DimnewToolbarAsAcadToolbar
SetnewToolbar=currMenuGroup.Toolbars.Add("TestToolbar")
EndSub
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateandEditToolbars>
AddNewToolbarButtonstoaToolbar
Toaddanewtoolbarbuttontoatoolbar,usetheAddToolbarButtonmethod.ThismethodcreatesanewToolbarItemobjectandaddsittothedesignatedtoolbar.Youshouldonlyaddbuttonstoatoolbarwhilethetoolbarisvisible.
TheAddToolbarButtonmethodtakesfiveparametersasinput:Index,Name,HelpString,Macro,andFlyoutButton.
Index
TheIndexparameterisanintegerthatspecifiesthepositionofthenewToolbaritemwithinthetoolbar.Theindexbeginswithpositionzero(0)asthefirstpositiononthetoolbarafterthetitle.Toaddthenewtoolbarbuttontotheendofatoolbar,settheIndexparameterequaltotheCountpropertyofthetoolbar.(TheCountpropertyofthetoolbarrepresentsthetotalnumberoftoolbarbuttonsonthattoolbar.)Onceatoolbarbuttonhasbeencreated,youcannotchangetheindexofthebuttonthroughtheIndexproperty.Tochangetheindexofanexistingtoolbarbutton,youmustdeleteandre-addthetoolbarbuttontoadifferentposition,oraddordeletesurroundingtoolbarbuttonsuntilaproperplacementisachieved.
Name
Anameisastringthatidentifiesthetoolbarbutton.Thestringmustcomprisealphanumericcharacterswithnopunctuationotherthanadash(-)oranunderscore(_).Thisstringisdisplayedasthetooltipwhenthecursorisplacedoverthetoolbarbutton.Onceatoolbarbuttonhasbeencreated,youcanchangethenameusingtheNameparameter.
HelpString
AhelpstringisthetextstringthatappearsintheAutoCADstatuslinewhen
auserhighlightsamenuitemforselection.Onceatoolbarbuttonhasbeencreated,youcanchangethehelpstringforthebuttonusingtheHelpStringparameter.
Macro
Amacroisaseriesofcommandsthatexecutesspecificactionswhenatoolbarbuttonisselected.Toolbarmacroscanbesimplyrecordingsofkeystrokesthataccomplishatask,ortheycanbeacomplexcombinationofcommands,AutoLISP,DIESEL,orActiveXprogrammingcode.OnceaToolbarbuttonhasbeencreated,youcanchangethemacroforthebuttonusingtheMacroparameter.
FlyoutButton
TheFlyoutButtonparameterisanoptionalflagstatingwhetherornotthenewbuttonistobeaflyoutbutton.Ifthenewbuttonistobeaflyoutbutton,thisparametermustbesettoTRUE.Ifthenewbuttonisnottobeaflyoutbutton,thisparametercanbesettoFALSEoritcanbeignored.
Addbuttonstoanewtoolbar
Thisexamplecreatesanewtoolbarandaddsabuttontothetoolbar.ThebuttonisassignedamacrothatwillexecutetheOPENcommandwhenthebuttonisselected.
SubCh6_AddButton()
DimcurrMenuGroupAsAcadMenuGroup
SetcurrMenuGroup=ThisDrawing.Application.MenuGroups.Item(0)
'Createthenewtoolbar
DimnewToolbarAsAcadToolbar
SetnewToolbar=currMenuGroup.Toolbars.Add("TestToolbar")
'Addabuttontothenewtoolbar
DimnewButtonAsAcadToolbarItem
DimopenMacroAsString
'AssignthemacrotheVBequivalentof"ESCESC_open"
openMacro=Chr(3)+Chr(3)+"_open"
SetnewButton=newToolbar.AddToolbarButton_
("","NewButton","Openafile.",openMacro)
EndSub
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateandEditToolbars>
AddSeparatorstoaToolbar
Toaddaseparatortoatoolbar,usetheAddSeparatormethod.ThismethodcreatesanewToolbarItemobjectandaddsittothedesignatedtoolbar.ThiskindofToolbarItemobjectisassignedthetypeofacSeparator.ThetypeofaToolbarbuttoncanbefoundthroughtheTypeproperty.
TheAddSeparatormethodtakesoneparameterasinput:Index.TheIndexparameterisanintegerthatspecifiesthepositionoftheseparatorwithinthetoolbar.Theindexbeginswithpositionzero(0)asthefirstpositiononthetoolbarafterthetitle.
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateandEditToolbars>
DefinetheToolbarButtonImage
Todefinetheimagestobeusedonatoolbarbutton,usetheSetBitmapsandGetBitmapsmethods.
TheSetBitmapsmethodtakestwoparameters:SmallIconNameandLargeIconName.
SmallIconName
ThesmalliconnameidentifiestheIDstringofthesmall-imageresource(16×15bitmap).Thestringmustcomprisealphanumericcharacterswithnopunctuationotherthanadash(-)oranunderscore(_),andshouldincludethe.bmpextension.Theresourcecanbeeitherasystembitmaporauser-definedbitmap.User-definedbitmapsmustbeoftheappropriatesizeandmustresideintheSupportpath.
LargeIconName
ThelargeiconnameidentifiestheIDstringofthelarge-imageresource(24×22bitmap).Thestringmustcomprisealphanumericcharacterswithnopunctuationotherthanadash(-)oranunderscore(_),andshouldincludethe.bmpextension.Theresourcecanbeeitherasystembitmaporauser-definedbitmap.User-definedbitmapsmustbeoftheappropriatesizeandmustresideintheSupportpath.
Queryanexistingtoolbartofindthenameoftheiconsforthebuttons
SubCh6_GetButtonImages()
DimButtonAsAcadToolbarItem
DimToolbar0AsAcadToolbar
DimMenuGroup0AsAcadMenuGroup
DimSmallButtonNameAsString
DimLargeButtonNameAsString
DimmsgAsString
DimButtonTypeAsString
'Getthefirsttoolbarinthefirstmenugroup
SetMenuGroup0=ThisDrawing.Application._
MenuGroups.Item(0)
SetToolbar0=MenuGroup0.Toolbars.Item(0)
'Clearthestringvariables
SmallButtonName=""
LargeButtonName=""
'Createaheaderforthemessageboxand
'displaythetoolbartobequeried
msg="Toolbar:"+Toolbar0.Name+vbCrLf
Toolbar0.Visible=True
'Iteratethroughthetoolbarandcollectdata
'foreachbuttoninthetoolbar.Ifthetoolbaris
'anormalbuttonoraflyout,collectthesmall
'andlargebuttonnamesforthebutton.
ForEachButtonInToolbar0
ButtonType=Choose(Button.Type+1,"Button",_
"Separator","Control","Flyout")
msg=msg&ButtonType&":"
IfButton.Type=acToolbarButtonOr_
Button.Type=acToolbarFlyoutThen
Button.GetBitmapsSmallButtonName,_
LargeButtonName
msg=msg+SmallButtonName+","_
+LargeButtonName
EndIf
msg=msg+vbCrLf
NextButton
'Displaytheresults
MsgBoxmsg
EndSub
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateandEditToolbars>
CreateFlyoutToolbars
Toaddaflyouttoolbarbuttontoatoolbar,usetheAddToolbarButtonmethod.ThismethodcreatesanewToolbarItemobjectandaddsittothedesignatedtoolbar.
TheAddToolbarButtonmethodtakesfiveparametersasinput:Index,Name,HelpString,Macro,andFlyoutButton.BysettingtheFlyoutButtonparametertoTRUE,thenewbuttonwillbecreatedasaflyoutbutton.Thereturnvaluefromthismethodwillbethenewflyouttoolbar.Theflyouttoolbarcanthenbepopulatedasanormaltoolbarwouldbe.
Formoreinformationaboutpopulatingatoolbar,seeAddNewToolbarButtonstoaToolbar.
Createaflyouttoolbarbutton
Thisexamplecreatestwotoolbars.Thefirsttoolbarcontainsaflyoutbutton.Thesecondtoolbarisattachedtotheflyoutbuttononthefirsttoolbar.
SubCh6_AddFlyoutButton()
DimcurrMenuGroupAsAcadMenuGroup
SetcurrMenuGroup=ThisDrawing.Application._
MenuGroups.Item(0)
'Createthefirsttoolbar
DimFirstToolbarAsAcadToolbar
SetFirstToolbar=currMenuGroup.Toolbars._
Add("FirstToolbar")
'Addaflyoutbuttontothefirstmenuonthemenubar
DimFlyoutButtonAsAcadToolbarItem
SetFlyoutButton=FirstToolbar.AddToolbarButton_
("","Flyout","Demonstratesaflyoutbutton",_
"OPEN",True)
'Createthesecondtoolbar.Thiswillbeattachedto
'thefirsttoolbarthroughtheflyoutbutton.
DimSecondToolbarAsAcadToolbar
SetSecondToolbar=currMenuGroup.Toolbars._
Add("SecondToolbar")
'Addabuttontothenexttoolbar
DimnewButtonAsAcadToolbarItem
DimopenMacroAsString
'AssignthemacrotheVBequivalentof"ESCESC_open"
openMacro=Chr(3)+Chr(3)+"_open"
SetnewButton=SecondToolbar.AddToolbarButton_
("","NewButton","Openafile.",openMacro)
'Attachthesecondtoolbartotheflyout
'buttononthefirsttoolbar
FlyoutButton.AttachToolbarToFlyoutcurrMenuGroup.Name,_
SecondToolbar.Name
'Displaythefirsttoolbar,hidethesecondtoolbar
FirstToolbar.Visible=True
SecondToolbar.Visible=False
EndSub
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateandEditToolbars>
FloatandDockToolbars
Toolbarscanbedockedorfloatedprogrammatically.
Tofloatatoolbar,usetheFloatmethodforthetoolbar.TheFloatmethodtakesthreeparametersasinput:Top,Left,andNumberFloatRows.TheTopandLeftparametersspecifythepixellocationforthetopandleftedgeofthetoolbar.TheNumberFloatRowsparameterspecifiesthenumberofrowswithwhichtocreateahorizontaltoolbar.Thisnumbermustbeequaltoorgreaterthanone.Thebuttonsofthetoolbarwillbedistributedequallyacrossthenumberofrowsspecified.Forverticallyalignedtoolbars,thisvaluespecifiesthenumberofcolumns.
Todockatoolbar,usetheDockmethodforthetoolbar.TheDockmethodtakesthreeparametersasinput:Side,Row,andColumn.TheSideparameterspecifiesthesideofthetoolbarthatyouwillbepositioninginthedockingmaneuver.Youcanspecifythetop,bottom,left,orrightsideofthetoolbar.TheRowandColumnparametersspecifyanumberontheexistingrowsandcolumnsofdockedtoolbarsatwhichtodockthetoolbar.
YoucanqueryatoolbartoseeifitisdockedbyusingtheDockStatusproperty.TheDockStatuspropertywillreturnTRUEifthetoolbarisdockedandFALSEifthetoolbarisfloating.
Dockatoolbar
Thisexamplecreatesanewtoolbarwiththreebuttonsonit.Thetoolbaristhendisplayedanddockedontheleftsideofthescreen.
SubCh6_DockToolbar()
DimcurrMenuGroupAsAcadMenuGroup
SetcurrMenuGroup=ThisDrawing.Application._
MenuGroups.Item(0)
'Createthenewtoolbar
DimnewToolbarAsAcadToolbar
SetnewToolbar=currMenuGroup.Toolbars._
Add("TestToolbar")
'Addthreebuttonstothenewtoolbar.
'Allthreebuttonswillhavethesamemacroattached.
DimnewButton1AsAcadToolbarItem
DimnewButton2AsAcadToolbarItem
DimnewButton3AsAcadToolbarItem
DimopenMacroAsString
'AssignthemacrotheVBequivalentof"ESCESC_open"
openMacro=Chr(3)+Chr(3)+"_open"
SetnewButton1=newToolbar.AddToolbarButton_
("","NewButton1","Openafile.",openMacro)
SetnewButton2=newToolbar.AddToolbarButton_
("","NewButton2","Openafile.",openMacro)
SetnewButton3=newToolbar.AddToolbarButton_
("","NewButton3","Openafile.",openMacro)
'Displaythetoolbar
newToolbar.Visible=True
'Dockthetoolbartotheleftofthescreen.
newToolbar.DockacToolbarDockLeft
EndSub
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateandEditToolbars>
DeleteToolbarButtonsfromaToolbar
Toremovetoolbarbuttonsfromatoolbar,usetheDeletemethodfoundonthetoolbarbutton.Youshouldonlydeletebuttonsfromatoolbarwhilethetoolbarisvisible.
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateandEditToolbars>
ExplorethePropertiesofToolbarItems
Alltoolbaritemssharethefollowingproperties:
Tagstring
Atag,ornametag,isastringconsistingofalphanumericandunderscore(_)characters.Thisstringuniquelyidentifiesthetoolbaritemwithinagiventoolbar.Anewtagisassignedautomaticallywhenatoolbaritemiscreated.YoucanreadorwritethevalueofatagbyusingtheTagstringproperty.
Name
Anameisastringidentifyingthetoolbaritem.Itisalsothestringusedforthetooltiptext,whichisthetextstringthatpopsupinAutoCADwhenauserholdsthemouseoranotherpointingdeviceoverthetoolbaritem.YoucanreadorwritethevalueofanamebyusingtheNameproperty.
Macro
Amacroisaseriesofcommandsthatexecutesspecificactionswhenatoolbaritemisselected.Macroscansimplyberecordingsofkeystrokesthataccomplishatask,ortheycanbeacomplexcombinationofcommands,AutoLISP,DIESEL,orActiveXprogrammingcode.YoucanreadorwritethevalueofamacrobyusingtheMacroproperty.
HelpString
AhelpstringisthetextstringthatappearsintheAutoCADstatuslineforatoolbarbutton.YoucanreadorwritethevalueofahelpstringbyusingtheHelpStringproperty.
Index
Theindexofatoolbaritemspecifiesthepositionofthattoolbaritemonthe
toolbartowhichitbelongs.Theindexpositionofatoolbaralwaysbeginswithposition0.Forexample,iftheitemisthefirstitemonatoolbar,itwillhaveanindexpositionof0.Ifitistheseconditemonatoolbar,itwillhaveanindexpositionof1,andsoon.YoucanreadtheindexpositionofatoolbaritembyusingtheIndexproperty.
Type
Atoolbaritemcanbeoneofthefollowingtypes:aregulartoolbarbutton,aseparator,aflyouttoolbarbutton,oraspecialcontrolelement.Iftheitemisaregulartoolbarbutton,thispropertyreturnsacButton.Iftheitemisaseparator,thispropertyreturnsacToolButtonSeparator.Iftheitemisaflyoutbutton,thispropertyreturnsacFlyout.Iftheitemisaspecialcontrolelement,thispropertyreturnsacControl.YoucandeterminethetypeofatoolbaritembyusingtheTypeproperty.
Flyout
IfthetoolbaritemisofthetypeacFlyout,thispropertyreturnsthetoolbarthatisattachedastheflyouttoolbar.TheflyouttoolbarisreturnedasaToolbarobject.IfthemenuitemisnotofthetypeacFlyout,thispropertyreturnsNULL.YoucanfindtheflyouttoolbarofatoolbaritembyusingtheFlyoutproperty.
Parent
Thispropertyreturnsthetoolbaronwhichthetoolbaritemresides.TheParenttoolbarisreturnedasaToolbarobject.YoucanfindthetoolbartowhichatoolbaritembelongsbyusingtheParentproperty.
ToolbarProperties
Thereareotherpropertiesthatapplytoalltoolbaritemsonthetoolbar.Suchpropertiesincludewhetherthetoolbarisdockedorfloating,visibleorhidden,andwhetherthetoolbaruseslargebuttonsorsmallbuttons.
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>
CreateMacros
Amacroisaseriesofcommandsthatexecutesspecificactionswhenatoolbaritemisselected.Macroscansimplyberecordingsofkeystrokesthataccomplishatask,ortheycanbeacomplexcombinationofcommands,AutoLISP,DIESEL,orActiveXprogrammingcode.
Ifyouintendtoincludecommandparametersinamenumacro,youmustknowthesequenceinwhichthatcommandexpectsitsparameters.Everycharacterinamenumacroissignificant,eventheblankspaces.AsAutoCADisrevisedandenhanced,thesequenceofpromptsforvariouscommands(andsometimeseventhecommandnames)mightchange.Therefore,yourcustommenusmightrequireminorchangeswhenyouupgradetoanewreleaseofAutoCAD.
Whencommandinputcomesfromamenuitem,thesettingsofthePICKADDandPICKAUTOsystemvariablesareassumedtobe1and0,respectively.ThispreservescompatibilitywithpreviousreleasesofAutoCADandmakescustomizationeasierbecauseyouarenotrequiredtocheckthesettingsofthesevariables.
Topicsinthissection
MacroCharactersMappedtoASCIIEquivalentsMacroTerminationPauseforUserInputCancelaCommandMacroRepetitionUseofSingleObjectSelectionMode
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateMacros>
MacroCharactersMappedtoASCIIEquivalents
ThefollowingtableprovidesasynopsisofspecialcharactersusedinmenumacrosandtheirequivalentASCIInumbersastheyareusedinVBandVBA.UsetheASCIIequivalentforthesespecialcharacterswhencreatingthestringfortheMacroproperty.
Specialcharactersusedinmenuandtoolbarmacros
Character ASCIIequivalent Description
; chr(59) IssuesENTER
^M chr(13) IssuesENTER
^| chr(94)+chr(124)
IssuesTAB
SPACEBAR chr(32) Entersaspace;blankspacebetweencommandsequencesinamenuitemisequivalenttopressingtheSPACEBAR
\ chr(92) Pausesforuserinput
_ chr(95) TranslatesAutoCADcommandsandkey
wordsthatfollow
+ chr(43) Continuesmenumacrotothenextline(iflastcharacter)
=* chr(61)+chr(42)
Displaysthecurrenttop-levelimage,pull-down,orshortcutmenu
*^C^C chr(42)+chr(3)+chr(3)
Prefixforarepeatingitem
$ chr(36) LoadsamenusectionorintroducesaconditionalDIESELmacroexpression
^B chr(2) TogglesSnaponoroff(CTRL+B)
^C chr(3) Cancelscommand(CTRL+C)
ESC chr(3) Cancelscommand(ESC)
^D chr(4) TogglesCoordsonoroff(CTRL+D)
^E chr(5) Setsthenextisometricplane(CTRL+E)
^G chr(7) TogglesGridonor
off(CTRL+G)
^H chr(8) Issuesbackspace
^O chr(15) TogglesOrthoonoroff(CTRL+O)
^P chr(16) TogglesMENUECHOonoroff
^Q chr(17) Echoesallprompts,statuslistings,andinputtotheprinter(CTRL+Q)
^T chr(20) TogglesTabletonoroff(CTRL+T)
^V chr(22) Changescurrentviewport(CTRL+V)
^Z chr(26) NullcharacterthatsuppressestheautomaticadditionofSPACEBARattheendofamenuitem
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateMacros>
MacroTermination
Whenamacroisexecuted,AutoCADplacesaspaceattheendofthemacrobeforeprocessingthecommandsequence.AutoCADprocessesthefollowingmenumacroasthoughyouhadenteredlineSPACEBAR.
line
Sometimesthisisundesirable;forexample,theTEXTorDIMcommandmustbeterminatedbyENTER,notbyaspace.Also,itsometimestakesmorethanonespace(orENTER)tocompleteacommand,butsometexteditorsdon'tletyoucreatealinewithtrailingblanks.Twospecialconventionsgetaroundtheseproblems.
Whenasemicolon(;)appearsinamacro,AutoCADsubstitutesanENTER.
Ifalineendswithacontrolcharacter,abackslash(\),aplussign(+),orasemicolon(;),AutoCADdoesnotaddablankafterit.
Lookatthefollowingmacro:
erase\;
Ifthisitemsimplyendedwiththebackslash(whichindicatesuserinput),itwouldfailtocompletetheERASEoperation,becauseAutoCADdoesn'taddablankafterthebackslash.Therefore,thismacrousesasemicolon(;)toforceanENTERaftertheuserinput.Herearemoreexamples:
ucs
ucs;
text\.40DRAFTInc;;;MainSt.;;;City,State;
SelectingthefirstmacroentersucsandSPACEBARonthecommandline,andthefollowingpromptappears:
Enteranoption[New/Move/orthoGraphic/Prev/Restore/Save/Del/Apply/?/World]<World>:
Selectingthesecondmacroentersucs,SPACEBAR,andsemicolon(;)atthecommandline,whichacceptsthedefaultvalue,World.Nodifferencebetweenthefirstandseconditemwouldbeevidentonthescreen;naturally,youwouldn'tputbothonthesamemenu.
Selectingthethirdmacrodisplaysapromptforastartingpointandthendrawstheaddressonthreelines.Inthetriple-semicolon(;;;),thefirstsemicolonendsthetextstring,thesecondcausesrepetitionoftheTEXTcommand,andthethirdcallsforthedefaultplacementbelowthepreviousline.
Note AllspecialcharactersmustbeinputusingtheirASCIIequivalents.ForalistofASCIIequivalents,seeMacroCharactersMappedtoASCIIEquivalents.
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateMacros>
PauseforUserInput
Sometimesitisusefultoacceptinputfromthekeyboardorthepointingdeviceinthemidstofamacrobyplacingabackslash(\)atthepointwhereyouwantinput.
circle\1
layeroff\;
Thefirstmacropausestoasktheuserforthecenterpointandthenreadsaradiusof1fromthemacro.Notethatthereisnospaceafterthebackslashcharacter(\).Thenextmacropausestoasktheusertoenteronelayername,thenturnsthatlayeroffandexitstheLAYERcommand.TheLAYERcommandnormallypromptsforanotheroperationandexitsonlyifyoupressSPACEBAR(blank)orENTER(;).
Normally,themacroresumesafteroneitemisentered.Therefore,itisn'tpossibletoconstructamacrothatacceptsavariablenumberofinputs(asinobjectselection)andthencontinues.However,anexceptionismadefortheSELECTcommand;abackslashsuspendsthemacrountilobjectselectionhascompleted.Forexample,considerthefollowingmacro:
select\changeprevious;propertiescolorred;
ThismacrousestheSELECTcommandtocreateaselectionsetofoneormoreobjects.ItthenissuestheCHANGEcommand,referencesthisselectionsetusingthePreviousoption,andchangesthecolorofallselectedobjectstored.
Becausethebackslashcharacter(\)causesamacrotopauseforuserinput,youcannotuseabackslashforanyotherpurposeinamacro.Whenspecifyingfiledirectorypaths,useaforwardslash(/)asthepathdelimiter:forexample,/direct/file.
Thefollowingcircumstancesdelayresumptionofamacro:
Ifinputofapointisexpected,ObjectSnapmodesmayprecedeentryoftheactualpoint.
IfX/Y/Zpointfiltersareused,themacroremainssuspendeduntiltheentirepointhasbeenaccumulated.
FortheSELECTcommandonly,themacrodoesn'tresumeuntilobjectselectionhasbeencompleted.
Iftheuserrespondswithatransparentcommand,thesuspendedmacroremainssuspendeduntilthetransparentcommandiscompletedandtheoriginallyrequestedinputisreceived.
Iftheuserrespondsbychoosinganothermacro(tosupplyoptionsortoexecuteatransparentcommand),theoriginalmacroissuspended,andthenewlyselecteditemisprocessedtocompletionbeforethesuspendedmacroisresumed.
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateMacros>
CancelaCommand
Tomakesureyouhavenopreviousincompletecommands,use^C^Cinamacro.ThisisthesameaspressingESCtwicefromthekeyboard.Althoughasingle^Ccancelsmostcommands,^C^CisrequiredtoreturntotheCommandpromptfromaDIMcommand.Therefore,^C^CensuresthatAutoCADreturnstotheCommandpromptinmostcases.
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateMacros>
MacroRepetition
Onceyouhaveselectedacommand,youarelikelytouseitseveraltimesbeforemovingontoanothercommand.Thatishowmostpeopleusetools;youpickupatool,doseveralthingswithit,thenpickupanothertool,andsoon.Toavoidpickingupthetoolbeforeeachuse,AutoCADprovidesacommandrepetitioncapability,triggeredbyanullresponse.However,youcannotusethisfeaturetospecifycommandoptions.
Thisfeaturemakesitpossibleforyoutorepeatfrequentlyusedcommandsuntilyouchooseanothercommand.Ifamacrobeginswith*^C^Cimmediatelyfollowingtheitemlabel,themacroissavedinmemory.SubsequentCommandpromptsareansweredbythatmacrountilitisterminatedbyESCorbytheselectionofanothermacro.
Donotuse^C(Cancel)withinamacrothatbeginswiththestring*^C^C;thiscancelsthemacrorepetition.
Thefollowingisanexampleoftherepetitive,ormodal,approachtocommandhandling.
*^C^CMOVESingle
*^C^CCOPYSingle
*^C^CERASESingle
*^C^CSTRETCHSingleCrossing
*^C^CROTATESingle
*^C^CSCALESingle
Macrorepetitiondoesnotworkforitemsinimagetilemenus.
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>CreateMacros>
UseofSingleObjectSelectionMode
Singleobjectselectionputsobjectselectioninsingleselectionmode,disablesthenormaldialogconductedbyobjectselection,andcausestheselectiontoreturnthefirstobject(s)selectedbyasubsequentoption.Thiscanbequitehandyinamacro.Forexample,considerthefollowingmacro:
*^C^CERASEsingle
ThismacroterminatesthecurrentcommandandactivatestheERASEcommandwiththesingleselectionoption.Afteryouselectthisitem,youeitherpointtothesingleobjecttobeerasedorpointtoablankareaandspecifyawindow.Theobject(s)selectedinthiswayareerased,andthemacroisrepeated(duetotheleadingasterisk)sothatyoucanerasesomethingelse.SingleselectionmodeleadstomoredynamicinteractionwithAutoCAD.
Pleasesendusyourcommentaboutthispage
CustomizeToolbarsandMenus>
CreateStatus-LineHelpforMenuItemsandToolbarItems
Status-linehelpmessagesareanimportantaspectofnativehelpsupport.Thesearethesimple,descriptivemessagesthatappearinthestatuslinewhenamenuortoolbaritemishighlighted.Thestatus-linehelpforallmenuandtoolbaritemsiscontainedintheHelpStringpropertyforthatitem.
TheHelpStringpropertyisemptywhenthemenuortoolbaritemisfirstcreated.
Addstatus-linehelptoamenuitem
Thisexamplecreatesanewmenucalled“TestMenu”andthencreatesamenuitemcalled“Open.”Themenuitemisthenassignedstatus-linehelpwiththeHelpStringproperty.
SubCh6_AddHelp()
DimcurrMenuGroupAsAcadMenuGroup
SetcurrMenuGroup=ThisDrawing.Application.MenuGroups.Item(0)
'Createthenewmenu
DimnewMenuAsAcadPopupMenu
SetnewMenu=currMenuGroup.Menus.Add_
("Te"+Chr(Asc("&"))+"stMenu")
'Addamenuitemtothenewmenu
DimnewMenuItemAsAcadPopupMenuItem
DimopenMacroAsString
'AssignthemacrotheVBAequivalentof"ESCESC_open"
openMacro=Chr(3)+Chr(3)+"_open"
'Createthemenuitem
SetnewMenuItem=newMenu.AddMenuItem_
(newMenu.count+1,Chr(Asc("&"))_
+"Open",openMacro)
'Addthestatuslinehelptothemenuitem
newMenuItem.HelpString="OpensanAutoCADdrawingfile."
'Displaythemenuonthemenubar
newMenu.InsertInMenuBar_
(ThisDrawing.Application.menuBar.count+1)
EndSub
Pleasesendusyourcommentaboutthispage
<$nopage>right-clickmenu.
CustomizeToolbarsandMenus>
AddEntriestotheRight-ClickMenu
Theright-clickmenu,orshortcutmenu,isaspecialmenuincludedintheAutoCADbasemenugroup.ThismenuappearswhentheuserholdsSHIFTandclickstherightmousebutton.
AutoCADfindstheshortcutmenubylookinginthebasemenugroupforamenuwiththeShortcutMenupropertyequaltoTRUE.YoucanaddnewmenuitemstotheshortcutmenubyfollowingthestepslistedinAddNewMenuItemstoaMenu.
Newmenugroupsmayormaynothaveashortcutmenuavailable.Tocreateashortcutmenuforamenugroup,followtheguidelineslistedinCreateNewMenus,andusePOP0asthelabelforthenewmenu.
Addamenuitemtotheendoftheright-clickmenu
Thisexampleaddsthemenuitem“OpenDWG”totheendoftheright-clickmenu.
SubCh6_AddMenuItemToshortcutMenu()
DimcurrMenuGroupAsAcadMenuGroup
SetcurrMenuGroup=ThisDrawing.Application.MenuGroups.Item(0)
'Findtheshortcutmenuandassignittothe
'shortcutMenuvariable
DimscMenuAsAcadPopupMenu
DimentryAsAcadPopupMenu
ForEachentryIncurrMenuGroup.Menus
Ifentry.shortcutMenu=TrueThen
SetscMenu=entry
EndIf
Nextentry
'Addamenuitemtotheshortcutmenu
DimnewMenuItemAsAcadPopupMenuItem
DimopenMacroAsString
'AssignthemacrotheVBAequivalentof"ESCESC_open"
openMacro=Chr(3)+Chr(3)+"_open"
SetnewMenuItem=scMenu.AddMenuItem_
("",Chr(Asc("&"))_
+"OpenDWG",openMacro)
EndSub
Pleasesendusyourcommentaboutthispage
UseEvents
Eventsarenotifications,ormessages,thataresentoutbyAutoCADtoinformyouaboutthecurrentstateofthesession,oralertyouthatsomethinghashappened.Forexample,whenadrawingisopenedtheBeginOpeneventistriggered.ThiseventcontainsthenameoftheAutoCADdrawingthatwasopened.Thereisanothereventtriggeredwhenadrawingisclosed.Giventhisinformationyoucouldwriteasubroutine,oreventhandler,thatusestheseeventstotracktheamountoftimeauserspendsworkingonaparticulardrawing.
Topicsinthissection
UnderstandtheEventsinAutoCADGuidelinesforEventHandlersHandleApplicationLevelEventsHandleDocumentLevelEventsHandleObjectLevelEvents
Pleasesendusyourcommentaboutthispage
UseEvents>
UnderstandtheEventsinAutoCAD
TherearethreetypesofeventsinAutoCAD®:
ApplicationleveleventsrespondtochangesintheAutoCADapplicationanditsenvironment.Theseeventsrespondtotheopening,saving,closingandprintingofdrawings,creationofnewdrawings,issuingofAutoCADcommands,loadingorunloadingofARXandLISPapplications,changestosystemvariables,andchangestotheApplicationwindow.
Documentleveleventsrespondtothechangesofaspecificdocumentoritscontents.Theseeventsrespondtotheaddition,deletion,ormodificationofobjects,activationofashortcutmenu,changesinthepickfirstselectionset,changestotheDrawingwindow,andregenerationofthedrawing.Therearealsodocumentleveleventsfortheopening,closing,andprintingofadrawing,andtheloadingorunloadingofARXandLISPapplicationsfromthedrawing.
Objectleveleventsrespondtothechangesofaspecificobject.Currentlythereisonlyoneobjectlevelevent.Itistriggeredwheneveranobjectismodified.
Subroutinesthatrespondtoeventsarecalledeventhandlersandareexecutedautomaticallyeachandeverytimetheirdesignatedeventistriggered.Informationcontainedinevents,suchasthedrawingnameintheBeginOpenevent,arepassedtoeventhandlersthroughparameters.
Pleasesendusyourcommentaboutthispage
UseEvents>
GuidelinesforEventHandlers
ItisimportanttorememberthateventssimplyprovideinformationonthestateoractivitiestakingplacewithinAutoCAD.Althougheventhandlerscanbewrittentorespondtothoseevents,AutoCADisofteninthemiddleofprocessingcommandswhentheeventhandleristriggered.Eventhandlers,therefore,havesomerestrictionsonwhattheycandoiftheyaretoprovidesafeoperationsinconjunctionwithAutoCADanditsdatabase.
Donotrelyonthesequenceofevents.Whenwritingeventhandlers,donotrelyonthesequenceofeventstohappenintheexactorderyouthinktheyoccur.Forexample,ifyouissueanOPENcommand,theeventsBeginCommand,BeginOpen,EndOpen,andEndCommandwillallbetriggered.However,theymaynotoccurinthatorder.TheonlyeventsequenceyoucansafelyrelyonisthataBegineventwilloccurbeforethecorrespondingEndevent.Inthepreviousexample,theeventsmaygettriggeredinthefollowingorder:BeginCommand,BeginOpen,EndCommand,andEndOpen,orevenBeginCommand,EndCommand,BeginOpen,andEndOpen.
Donotrelyonthesequenceofoperations.Ifyoudeleteobject1andthenobject2,donotrelyonthefactthatyouwillreceivetheObjectErasedeventforobject1andthenforobject2.YoumayreceivetheObjectErasedeventforobject2first.
Donotattemptanyinteractivefunctionsfromaneventhandler.Attemptingtoexecuteinteractivefunctionsfromwithinaneventhandlercancauseseriousproblems,asAutoCADmaystillbeprocessingacommandatthetimetheeventistriggered.Therefore,youshouldalwaysavoidtheuseofinput-acquisitionmethodssuchasGetPoint,GetEntity,GetKeyword,andsoon,aswellasselectionsetoperationsandtheSendCommandmethodfromwithineventhandlers.
Donotlaunchadialogboxfromwithinaneventhandler.DialogboxesareconsideredinteractivefunctionsandcaninterferewiththecurrentoperationofAutoCAD.Messageboxesandalertboxesarenotconsideredinteractiveandcanbeissuedsafely;howeverissuingamessageboxwithinaneventhandlerfortheBeginModal,EndModal,Activate,Deactivate,andBeginRightClickeventsresultsinunexpectedsequencing.
Youcanwritedatatoanyobjectinthedatabase,excepttheobjectthatissuedtheevent.Obviously,anyobjectcausinganeventtobetriggeredcouldstillbeopenforusewithAutoCADandtheoperationcurrentlyinprogress.Therefore,avoidwritinganyinformationtoanobjectfromaneventhandlerforthesameobject.However,youcansafelyreadinformationfromtheobjecttriggeringanevent.Forexample,supposeyouhaveafloorthatisfilledwithtilesandyoucreateaneventhandlerattachedtotheborderofthefloor.Ifyouchangethesizeofthefloor,theeventhandlerwillautomaticallyaddorsubtracttilestofillthenewarea.Theeventhandlerwillbeabletoreadthenewareaoftheborder,butitcannotattemptanychangesontheborderitself.
Donotperformanyactionfromaneventhandlerthatwilltriggerthesameevent.Ifyouperformthesameactioninaneventhandlerthattriggersthatsameevent,youwillcreateaninfiniteloop.Forexample,youshouldneverattempttoopenadrawingfromwithintheBeginOpenevent,orAutoCADwillsimplycontinuetoopenmoredrawingsuntilthemaximumnumberofopendrawingsisreached.
RememberthatnoeventswillbefiredwhileAutoCADisdisplayingamodaldialogbox.
Pleasesendusyourcommentaboutthispage
UseEvents>
HandleApplicationLevelEvents
ApplicationleveleventsarenotpersistentinAutoCADVBA.Thatis,theyarenotautomaticallyenabledwhenaVBAprojectisloaded.ApplicationleveleventsmustthereforebeenabledforVBAandallotherActiveX®Automationcontrollers.
Oncetheapplicationleveleventsareenabled,youhaveawiderangeofeventsavailabletoyou.Theseeventsinclude:
AppActivate
TriggeredjustbeforethemainApplicationwindowisactivated.
AppDeactivate
TriggeredjustbeforethemainApplicationwindowisdeactivated.
ARXLoaded
TriggeredwhenanObjectARXapplicationhasbeenloaded.
ARXUnloaded
TriggeredwhenanObjectARXapplicationhasbeenunloaded.
BeginCommand
Triggeredimmediatelyafteracommandisissued,butbeforeitcompletes.
BeginFileDrop
TriggeredwhenafileisdroppedonthemainApplicationwindow.
BeginLISP
TriggeredimmediatelyafterAutoCADreceivesarequesttoevaluateaLISPexpression.
BeginModal
Triggeredjustbeforeamodaldialogboxisdisplayed.
BeginOpen
TriggeredimmediatelyafterAutoCADreceivesarequesttoopenanexistingdrawing.
BeginPlot
TriggeredimmediatelyafterAutoCADreceivesarequesttoprintadrawing.
BeginQuit
TriggeredjustbeforeanAutoCADsessionends.
BeginSave
TriggeredimmediatelyafterAutoCADreceivesarequesttosavethedrawing.
EndCommand
Triggeredimmediatelyafteracommandcompletes.
EndLISP
TriggereduponcompletionofevaluatingaLISPexpression.
EndModal
Triggeredjustafteramodaldialogboxisdismissed.
EndOpen
TriggeredimmediatelyafterAutoCADfinishesopeninganexistingdrawing.
EndPlot
Triggeredafteradocumenthasbeensenttotheprinter.
EndSave
TriggeredwhenAutoCADhasfinishedsavingthedrawing.
LISPCancelled
TriggeredwhentheevaluationofaLISPexpressioniscanceled.
NewDrawing
Triggeredjustbeforeanewdrawingiscreated.
SysVarChanged
Triggeredwhenthevalueofasystemvariableischanged.
WindowChanged
TriggeredwhenthereisachangetotheApplicationwindow.
WindowMovedOrResized
TriggeredjustaftertheApplicationwindowhasbeenmovedorresized.
Topicsinthissection
EnableApplicationLevelEvents
Pleasesendusyourcommentaboutthispage
UseEvents>HandleApplicationLevelEvents>
EnableApplicationLevelEvents
BeforeyoucanuseapplicationleveleventsyoumustcreateanewclassmoduleanddeclareanobjectoftypeAcadApplicationwithevents.Forexample,assumethatanewclassmoduleiscreatedandcalledEventClassModule.ThenewclassmodulecontainsthedeclarationoftheapplicationwiththeVBAkeywordWithEvents.
TocreateanewclassanddeclareanApplicationobjectwithevents
1. IntheVBAIDE,insertaclassmodule.FromtheInsertmenu,chooseClassModule.
2. SelectthenewclassmoduleintheProjectwindow.
3. ChangethenameoftheclassinthePropertieswindowtoEventClass-Module.
4. OpentheCodewindowfortheclassusingF7,orbyselectingthemenuoptionView Code.
5. IntheCodewindowfortheclass,addthefollowingline:
PublicWithEventsAppAsAcadApplication
Afterthenewobjecthasbeendeclaredwithevents,itappearsintheObjectdrop-downlistboxintheclassmodule,andyoucanwriteeventproceduresforthenewobjectintheclassmodule.(WhenyouselectthenewobjectintheObjectbox,thevalideventsforthatobjectarelistedintheProceduredrop-downlistbox.)
Beforetheprocedureswillrun,however,youmustconnectthedeclaredobjectintheclassmodulewiththeApplicationobject.Youcandothiswiththefollowingcodefromanymodule.
ToconnectthedeclaredobjecttotheApplicationobject
1. IntheCodewindowforyourmainmodule,addthefollowinglinetothedeclarationssection:
DimXAsNewEventClassModule
2. Inthesamewindow,addthefollowingsubroutine:
SubInitializeEvents()
SetX.App=ThisDrawing.Application
EndSub
3. Inthecodeforyourmainmodule,addacalltotheInitializeEventssubroutine:
CallInitializeEvents
OncetheInitializeEventsprocedurehasbeenrun,theAppobjectintheclassmodulepointstotheApplicationobjectspecified,andanyeventproceduresintheclassmodulewillrunwhentheeventsoccur.
PrompttocontinuewhenadrawingisdroppedintoAutoCAD
ThisexampleinterceptstheloadprocesswhenafilehasbeendraggedanddroppedintoAutoCAD.AmessageboxcontainingthenameofthefilethatwasdroppedandYes/No/Continuebuttonsthatallowtheusertodecideifthefileshouldcontinuetobeloadedordisplayed.Iftheuserchoosestocanceloutoftheoperation,thatdecisionisreturnedthroughtheCancelparameteroftheBeginFileDropeventandthefileisnotloaded.
PublicWithEventsACADAppAsAcadApplication
SubExample_AcadApplication_Events()
'Thisexampleintializesthepublicvariable(ACADApp)
'whichwillbeusedtointerceptAcadApplicationEvents
'
'RunthisprocedureFIRST!
'WecouldgettheapplicationfromtheThisDocument
'object,butthatwouldrequirehavingadrawingopen,
'sowegrabitfromthesystem.
SetACADApp=GetObject(,"AutoCAD.Application.17")
EndSub
PrivateSubACADApp_BeginFileDrop_
(ByValFileNameAsString,CancelAsBoolean)
'ThisexampleinterceptsanApplicationBeginFileDropevent.
'
'Thiseventistriggeredwhenadrawingfileisdragged
'intoAutoCAD.
'
'Totriggerthisexampleevent:
'1)Makesuretoruntheexamplethatinitializes
'thepublicvariable(namedACADApp)linkedtothisevent.
'
'2)DraganAutoCADdrawingfileintotheAutoCAD
'applicationfromeithertheWindowsDesktop
'orWindowsExplorer
'Usethe"Cancel"variabletostoptheloadingofthe
'draggedfile,andthe"FileName"variabletonotify
'theuserwhichfileisabouttobedraggedin.
IfMsgBox("AutoCADisabouttoload"&FileName&vbCrLf_
&"Doyouwanttocontinueloadingthisfile?",_
vbYesNoCancel+vbQuestion)<>vbYesThen
Cancel=True
EndIf
EndSub
Pleasesendusyourcommentaboutthispage
UseEvents>
HandleDocumentLevelEvents
DocumentleveleventsarepersistentinAutoCADVBA.Thatis,theyareautomaticallyenabledwhenaVBAprojectisloaded.However,theyarenotenabledforanyothercontroller,suchasVB.DocumentleveleventsmustthereforebeenabledforallotherActiveXAutomationcontrollers.
Oncethedocumentleveleventsareenabled,youhaveawiderangeofeventsavailabletoyou.Theseeventsinclude
Activate
TriggeredwhenaDocumentwindowisactivated.
BeginDocClose
Triggeredjustafterarequestisreceivedtocloseadrawing.
BeginCommand
Triggeredimmediatelyafteracommandisissued,butbeforeitcompletes.
BeginDoubleClick
Triggeredaftertheuserdouble-clicksonanobjectinthedrawing.
BeginLISP
TriggeredimmediatelyafterAutoCADreceivesarequesttoevaluateaLISPexpression.
BeginPlot
TriggeredimmediatelyafterAutoCADreceivesarequesttoprintadrawing.
BeginRightClick
Triggeredaftertheuserright-clicksontheDrawingwindow.
BeginSave
TriggeredimmediatelyafterAutoCADreceivesarequesttosavethedrawing.
BeginShortcutMenuCommand
Triggeredaftertheuserright-clicksontheDrawingwindow,andbeforetheshortcutmenuappearsinCommandmode.
BeginShortcutMenuDefault
Triggeredaftertheuserright-clicksontheDrawingwindow,andbeforetheshortcutmenuappearsinDefaultmode.
BeginShortcutMenuEdit
Triggeredaftertheuserright-clicksontheDrawingwindow,andbeforetheshortcutmenuappearsinEditmode.
BeginShortcutMenuGrip
Triggeredaftertheuserright-clicksontheDrawingwindow,andbeforetheshortcutmenuappearsinGripmode.
BeginShortcutMenuOsnap
Triggeredaftertheuserright-clicksontheDrawingwindow,andbeforetheshortcutmenuappearsinOsnapmode.
Deactivate
TriggeredwhentheDrawingwindowisdeactivated.
EndCommand
Triggeredimmediatelyafteracommandcompletes.
EndLISP
TriggereduponcompletionofevaluatingaLISPexpression.
EndPlot
Triggeredafteradocumenthasbeensenttotheprinter.
EndSave
TriggeredwhenAutoCADhasfinishedsavingthedrawing.
EndShortcutMenu
Triggeredaftertheshortcutmenuappears.
LayoutSwitched
Triggeredaftertheuserswitchestoadifferentlayout.
LISPCancelled
TriggeredwhentheevaluationofaLISPexpressioniscanceled.
ObjectAdded
Triggeredwhenanobjecthasbeenaddedtothedrawing.
ObjectErased
Triggeredwhenanobjecthasbeenerasedfromthedrawing.
ObjectModified
Triggeredwhenanobjectinthedrawinghasbeenmodified.
SelectionChanged
Triggeredwhenthecurrentpickfirstselectionsetchanges.
WindowChanged
TriggeredwhenthereisachangetotheDocumentwindow.
WindowMovedOrResized
TriggeredjustaftertheDrawingwindowhasbeenmovedorresized.
Topicsinthissection
EnableDocumentLevelEventsinEnvironmentsOtherThanVBACodeDocumentLevelEventsinEnvironmentsOtherThanVBACodeDocumentLevelEventsinVBA
Pleasesendusyourcommentaboutthispage
UseEvents>HandleDocumentLevelEvents>
EnableDocumentLevelEventsinEnvironmentsOtherThanVBA
BeforeyoucanusedocumentleveleventsinVBoranotherenvironmentbesidesVBA,youmustcreateanewclassmoduleanddeclareanobjectoftypeAcadDocumentwithevents.Forexample,assumeanewclassmoduleiscreatedandcalledEventClassModule.ThenewclassmodulecontainsthedeclarationoftheapplicationwiththeVBAkeywordWithEvents.
TocreateanewclassanddeclareaDocumentobjectwithevents
1. IntheVBAIDE,insertaclassmodule.FromtheInsertmenu,chooseClassModule.
2. SelectthenewclassmoduleintheProjectwindow.
3. ChangethenameoftheclassinthePropertieswindowtoEventClass-Module.
4. OpentheCodewindowfortheclassusingF7,orbyselectingthemenuoptionView Code.
5. IntheCodewindowfortheclass,addthefollowingline:
PublicWithEventsDocAsAcadDocument
Afterthenewobjecthasbeendeclaredwithevents,itappearsintheObjectdrop-downlistboxintheclassmodule,andyoucanwriteeventproceduresforthenewobjectintheclassmodule.(WhenyouselectthenewobjectintheObjectbox,thevalideventsforthatobjectarelistedintheProceduredrop-downlistbox.)
Beforetheprocedureswillrun,however,youmustconnectthedeclaredobjectintheclassmodulewiththeDocumentobject.Youcandothiswiththefollowing
codefromanymodule.
ToconnectthedeclaredobjecttotheDocumentobject
1. IntheCodewindowforyourmainmodule,addthefollowinglinetothedeclarationssection:
DimXAsNewEventClassModule
2. Inthesamewindow,addthefollowingsubroutine:
ubInitializeEvents()
SetX.Doc=ThisDrawing
EndSub
3. Inthecodeforyourmainmodule,addacalltotheInitializeAppsubroutine:
CallInitializeEvents
OncetheInitializeEventsprocedurehasbeenrun,theDocobjectintheclassmodulepointstotheDocumentobjectcreated,andanyeventproceduresintheclassmodulewillrunwhentheeventsoccur.
Pleasesendusyourcommentaboutthispage
UseEvents>HandleDocumentLevelEvents>
CodeDocumentLevelEventsinEnvironmentsOtherThanVBA
Oncethedocumentleveleventshavebeenenabled,youwillfindtheDocclassvariableavailablefromtheObjectdrop-downlistoftheClassModuleCodewindow.SelecttheDocclassandthelistofavailableeventswillappearintheProceduredrop-downlist.Simplyselecttheeventyouwanttowriteahandlerforandthehandlerskeletoniscreatedautomatically.
Pleasesendusyourcommentaboutthispage
UseEvents>HandleDocumentLevelEvents>
CodeDocumentLevelEventsinVBA
DocumentleveleventsareautomaticallyenabledwhenaVBAprojectisloaded.TowriteeventhandlersfordocumentleveleventsinVBA,yousimplyselectAcadDocumentfromtheObjectdrop-downlistintheCodewindow.TheavailableeventsforthedocumentwillappearintheProceduredrop-downlist.Simplyselecttheeventyouwanttowriteahandlerforandthehandlerskeletoniscreatedautomatically.
Notethateventhandlerscreatedinthisfashionapplytothecurrentactivedrawing.Tocreateeventhandlersforaspecificdrawing,firstfollowthestepslistedinEnableDocumentLevelEventsinEnvironmentsOtherThanVBA.Thiswillallowyoutoenableaspecificdocumentforevents.
ThefollowingexampleusestheeventhandlerfortheBeginShortcutMenuDefaulteventtoaddthe“OpenDWG”menuitemtothebeginningoftheshortcutmenu.ThentheeventhandlerfortheEndShortcutMenueventremovestheadditionalmenuitemsothatitisnotsavedpermanentlyintheuser'smenuconfiguration.
PrivateSubAcadDocument_BeginShortcutMenuDefault_
(ShortcutMenuAsAutoCAD.IAcadPopupMenu)
OnErrorResumeNext
'Addamenuitemtothecursormenu
DimnewMenuItemAsAcadPopupMenuItem
DimopenMacroAsString
openMacro=Chr(vbKeyEscape)+Chr(vbKeyEscape)+"_open"
SetnewMenuItem=ShortcutMenu.AddMenuItem_
(0,Chr(Asc("&"))_
+"OpenDWG",openMacro)
EndSub
PrivateSubAcadDocument_EndShortcutMenu_
(ShortcutMenuAsAutoCAD.IAcadPopupMenu)
OnErrorResumeNext
ShortcutMenu.Item("OpenDWG").Delete
EndSub
Pleasesendusyourcommentaboutthispage
UseEvents>
HandleObjectLevelEvents
TheobjectleveleventisnotpersistentinAutoCADVBA.Thatis,itisnotautomaticallyenabledwhenaVBAprojectisloaded.AnobjectleveleventmustbeenabledforVBAandallotherActiveXAutomationcontrollers.
Oncetheobjectleveleventsisenabled,theModifiedeventisavailabletoyou.Thiseventistriggeredwhenanobjectinthedrawinghasbeenmodified.
Topicsinthissection
EnabletheObjectLevelEvent
Pleasesendusyourcommentaboutthispage
UseEvents>HandleObjectLevelEvents>
EnabletheObjectLevelEvent
BeforeyoucanuseobjectleveleventsyoumustcreateanewclassmoduleanddeclareanobjectoftypeAcadObjectwithevents.Forexample,assumethatanewclassmoduleiscreatedandcalledEventClassModule.ThenewclassmodulecontainsthedeclarationoftheapplicationwiththeVBAkeywordWithEvents.
TocreateanewclassanddeclareaCircleobjectwithevents
1. IntheVBAIDE,insertaclassmodule.FromtheInsertmenu,chooseClassModule.
2. SelectthenewclassmoduleintheProjectwindow.
3. ChangethenameoftheclassinthePropertieswindowtoEventClass-Module.
4. OpentheCodewindowfortheclassusingF7,orbyselectingthemenuoptionView Code.
5. IntheCodewindowfortheclass,addthefollowingline:
PublicWithEventsObjectAsAcadCircle
Afterthenewobjecthasbeendeclaredwithevents,itappearsintheObjectdrop-downlistboxintheclassmodule,andyoucanwriteeventproceduresforthenewobjectintheclassmodule.(WhenyouselectthenewobjectintheObjectbox,thevalideventsforthatobjectarelistedintheProceduredrop-downlistbox.)
Beforetheprocedureswillrun,however,youmustconnectthedeclaredobjectintheclassmodulewiththeCircleobject.Youcandothiswiththefollowingcodefromanymodule.
ToconnectthedeclaredobjecttotheAutomationobject
1. IntheCodewindowforyourmainmodule,addthefollowinglinetothedeclarationssection:
DimXAsNewEventClassModule
2. Inthesamewindow,createacirclecalled“MyCircle”andinitializeitascontainingevents:
SubInitializeEvents()
DimMyCircleAsAcadCircle
DimcenterPoint(0To2)AsDouble
DimradiusAsDouble
centerPoint(0)=0#:centerPoint(1)=0#:centerPoint(2)=0#
radius=5#
SetMyCircle=ThisDrawing.ModelSpace.AddCircle(centerPoint,radius)
SetX.Object=MyCircle
EndSub
3. Inthecodeforyourmainmodule,addacalltotheInitializeAppsubroutine:
CallInitializeEvents
OncetheInitializeEventsprocedurehasbeenrun,theCircleobjectintheclassmodulepointstotheCircleobjectcreated,andanyeventproceduresintheclassmodulewillrunwhentheeventsoccur.Note WhencodinginVBA,youmustprovideaneventhandlerforallobjectsenabledfortheModifiedevent.Ifyoudonotprovideahandler,VBAmayterminateunexpectedly.
DisplaytheareaofaclosedpolylinewheneverthepolylineisupdatedThisexamplecreatesalightweightpolylinewithevents.Theeventhandlerforthepolylinethendisplaysthenewareawheneverthepolylineischanged.Totriggertheevent,simplychangethesizeofthepolylineinAutoCAD.RememberthatyoumustruntheCreatePLineWithEventssubroutinebeforetheeventhandlerisactivated.
PublicWithEventsPLineAsAcadLWPolyline
SubCreatePLineWithEvents()
'Thisexamplecreatesalightweightpolyline
Dimpoints(0To9)AsDouble
points(0)=1:points(1)=1
points(2)=1:points(3)=2
points(4)=2:points(5)=2
points(6)=3:points(7)=3
points(8)=3:points(9)=2
SetPLine=ThisDrawing.ModelSpace._
AddLightWeightPolyline(points)
PLine.Closed=True
ThisDrawing.Application.ZoomAll
EndSub
PrivateSubPLine_Modified_
(ByValpObjectAsAutoCAD.IAcadObject)
'Thiseventistriggeredwhenthepolylineisresized.
'Ifthepolylineisdeletedthemodifiedeventisstill
'triggered,soweusetheerrorhandlertoavoid
'readingdatafromadeletedobject.
OnErrorGoToERRORHANDLER
MsgBox"Theareaof"&pObject.ObjectName&"is:"_
&pObject.Area
ExitSub
ERRORHANDLER:
MsgBoxErr.Description
EndSub
Pleasesendusyourcommentaboutthispage
WorkinThree-DimensionalSpace
Mostdrawingsconsistoftwo-dimensional(2D)viewsofobjectsthatarethreedimensional(3D).Thoughthismethodofdraftingiswidelyusedinthearchitecturalandengineeringcommunities,itislimited:thedrawingsare2Drepresentationsof3Dobjectsandmustbevisuallyinterpreted.Moreover,becausetheviewsarecreatedindependently,therearemorepossibilitiesforerrorandambiguity.Asaresult,youmaywanttocreatetrue3Dmodelsinsteadof2Drepresentations.YoucanusetheAutoCADdrawingtoolstocreatedetailed,realistic3Dobjectsandmanipulatetheminvariousways.
Topicsinthissection
Specify3DCoordinatesDefineaUserCoordinateSystemConvertCoordinatesCreate3DObjectsEditin3DEdit3DSolids
Pleasesendusyourcommentaboutthispage
WorkinThree-DimensionalSpace>
Specify3DCoordinates
Entering3Dworldcoordinatesystem(WCS)coordinatesissimilartoentering2DWCScoordinates.InadditiontospecifyingXandYvalues,youspecifyaZvalue.Aswiththe2Dcoordinates,avariantisusedtopassthecoordinatestoActiveX®methodsandproperties,andtoquerythecoordinates.
Formoreinformationaboutspecifying3Dcoordinates,see“Enter3DCoordinates”intheUser'sGuide.
Defineandquerythecoordinatesfor2Dand3Dpolylines
Thisexamplecreatestwopolylines,eachwiththreecoordinates.Thefirstpolylineisa2Dpolyline,thesecondpolylineis3D.NoticethatthelengthofthearraycontainingtheverticesisexpandedtoincludetheZcoordinatesinthecreationofthe3Dpolyline.Theexampleconcludesbyqueryingthecoordinatesofthepolylinesanddisplayingthecoordinatesinamessagebox.
SubCh8_Polyline_2D_3D()
Dimpline2DObjAsAcadLWPolyline
Dimpline3DObjAsAcadPolyline
Dimpoints2D(0To5)AsDouble
Dimpoints3D(0To8)AsDouble
'Definethree2Dpolylinepoints
points2D(0)=1:points2D(1)=1
points2D(2)=1:points2D(3)=2
points2D(4)=2:points2D(5)=2
'Definethree3Dpolylinepoints
points3D(0)=1:points3D(1)=1:points3D(2)=0
points3D(3)=2:points3D(4)=1:points3D(5)=0
points3D(6)=2:points3D(7)=2:points3D(8)=0
'Createthe2DlightweightPolyline
Setpline2DObj=ThisDrawing.ModelSpace._
AddLightWeightPolyline(points2D)
pline2DObj.Color=acRed
pline2DObj.Update
'Createthe3Dpolyline
Setpline3DObj=ThisDrawing.ModelSpace._
AddPolyline(points3D)
pline3DObj.Color=acBlue
pline3DObj.Update
'Querythecoordinatesofthepolylines
Dimget2DptsAsVariant
Dimget3DptsAsVariant
get2Dpts=pline2DObj.Coordinates
get3Dpts=pline3DObj.Coordinates
'Displaythecoordinates
MsgBox("2Dpolyline(red):"&vbCrLf&_
get2Dpts(0)&","&get2Dpts(1)&vbCrLf&_
get2Dpts(2)&","&get2Dpts(3)&vbCrLf&_
get2Dpts(4)&","&get2Dpts(5))
MsgBox("3Dpolyline(blue):"&vbCrLf&_
get3Dpts(0)&","&get3Dpts(1)&","&_
get3Dpts(2)&vbCrLf&_
get3Dpts(3)&","&get3Dpts(4)&","&_
get3Dpts(5)&vbCrLf&_
get3Dpts(6)&","&get3Dpts(7)&","&_
get3Dpts(8))
EndSub
Pleasesendusyourcommentaboutthispage
WorkinThree-DimensionalSpace>
DefineaUserCoordinateSystem
Youdefineausercoordinatesystem(UCS)objecttochangethelocationofthe(0,0,0)originpointandtheorientationoftheXYplaneandZaxis.YoucanlocateandorientaUCSanywherein3Dspace,andyoucandefine,save,andrecallasmanyusercoordinatesystemsasyourequire.CoordinateinputanddisplayarerelativetothecurrentUCS.
ToindicatetheoriginandorientationoftheUCS,youcandisplaytheUCSiconattheUCSoriginpointusingtheUCSIconAtOriginproperty.IftheUCSiconisturnedon(seetheUCSIconOnproperty)andisnotdisplayedattheorigin,itisdisplayedattheWCScoordinatedefinedbytheUCSORGsystemvariable.
YoucancreateanewusercoordinatesystemusingtheAddmethod.Thismethodrequiresfourvaluesasinput:thecoordinateoftheorigin,acoordinateontheXandYaxes,andthenameoftheUCS.
AllcoordinatesintheAutoCAD®ActiveXAutomationareenteredintheworldcoordinatesystem.UsetheGetUCSMatrixmethodtoreturnthetransformationmatrixofagivenUCS.UsethistransformationmatrixtofindtheequivalentWCScoordinates.
TomakeaUCSactive,usetheActiveUCSpropertyontheDocumentobject.IfchangesaremadetotheactiveUCS,thenewUCSobjectmustberesetastheactiveUCSforthechangestoappear.ToresettheactiveUCS,simplycalltheActiveUCSpropertyagainwiththeupdatedUCSobject.
FormoreinformationaboutdefiningaUCS,see“ControltheUserCoordinateSystemin3D”intheUser'sGuide.
CreateanewUCS,makeitactive,andtranslatethecoordinatesofapointintotheUCScoordinates
ThefollowingsubroutinecreatesanewUCSandsetsitastheactiveUCSfor
thedrawing.Itthenaskstheusertopickapointinthedrawing,andreturnsbothWCSandUCScoordinatesforthepoint.
SubCh8_NewUCS()
'Definethevariableswewillneed
DimucsObjAsAcadUCS
Dimorigin(0To2)AsDouble
DimxAxisPnt(0To2)AsDouble
DimyAxisPnt(0To2)AsDouble
'DefinetheUCSpoints
origin(0)=4:origin(1)=5:origin(2)=3
xAxisPnt(0)=5:xAxisPnt(1)=5:xAxisPnt(2)=3
yAxisPnt(0)=4:yAxisPnt(1)=6:yAxisPnt(2)=3
'AddtheUCStothe
'UserCoordinatesSystemscollection
SetucsObj=ThisDrawing.UserCoordinateSystems._
Add(origin,xAxisPnt,yAxisPnt,"New_UCS")
'DisplaytheUCSicon
ThisDrawing.ActiveViewport.UCSIconAtOrigin=True
ThisDrawing.ActiveViewport.UCSIconOn=True
'MakethenewUCStheactiveUCS
ThisDrawing.ActiveUCS=ucsObj
MsgBox"ThecurrentUCSis:"&ThisDrawing.ActiveUCS.Name_
&vbCrLf&"Pickapointinthedrawing."
'FindtheWCSandUCScoordinateofapoint
DimWCSPntAsVariant
DimUCSPntAsVariant
WCSPnt=ThisDrawing.Utility.GetPoint(,"Enterapoint:")
UCSPnt=ThisDrawing.Utility.TranslateCoordinates_
(WCSPnt,acWorld,acUCS,False)
MsgBox"TheWCScoordinatesare:"&WCSPnt(0)&","_
&WCSPnt(1)&","&WCSPnt(2)&vbCrLf&_
"TheUCScoordinatesare:"&UCSPnt(0)&","_
&UCSPnt(1)&","&UCSPnt(2)
EndSub
Pleasesendusyourcommentaboutthispage
WorkinThree-DimensionalSpace>
ConvertCoordinates
TheTranslateCoordinatesmethodtranslatesapointoradisplacementfromonecoordinatesystemtoanother.Apointargument,calledOriginalPoint,canbeinterpretedaseithera3Dpointora3Ddisplacementvector.ThisargumentisdistinguishedbytheBooleanargument,Disp.IftheDispargumentissettoTRUE,theOriginalPointargumentistreatedasadisplacementvector;otherwise,itistreatedasapoint.TwomoreargumentsdeterminewhichcoordinatesystemtheOriginalPointisfrom,andtowhichcoordinatesystemtheOriginalPointistobeconverted.ThefollowingAutoCADcoordinatesystemscanbespecifiedintheFromandToarguments:
WCS
Worldcoordinatesystem:Thereferencecoordinatesystem.AllothercoordinatesystemsaredefinedrelativetotheWCS,whichneverchanges.ValuesmeasuredrelativetotheWCSarestableacrosschangestoothercoordinatesystems.AllpointspassedinandoutofActiveXmethodsandpropertiesareexpressedintheWCSunlessotherwisespecified.
UCS
Usercoordinatesystem(UCS):Theworkingcoordinatesystem.TheuserspecifiesaUCStomakedrawingtaskseasier.AllpointspassedtoAutoCADcommands,includingthosereturnedfromAutoLISProutinesandexternalfunctions,arepointsinthecurrentUCS(unlesstheuserprecedesthemwithan*attheCommandprompt).IfyouwantyourapplicationtosendcoordinatesintheWCS,OCS,orDCStoAutoCADcommands,youmustfirstconvertthemtotheUCSbycallingtheTranslateCoordinatesmethod.
OCS
Objectcoordinatesystem:PointvaluesspecifiedbycertainmethodsandpropertiesforthePolylineandLightweightPolylineobjectsareexpressedinthiscoordinatesystem,relativetotheobject.Thesepointsareusually
convertedintotheWCS,currentUCS,orcurrentDCS,accordingtotheintendeduseoftheobject.Conversely,pointsinWCS,UCS,orDCSmustbetranslatedintoanOCSbeforetheyarewrittentothedatabasebymeansofthesameproperties.SeetheAutoCADActiveXandVBAReferenceforthemethodsandpropertiesthatusethiscoordinatesystem.WhenconvertingcoordinatestoorfromtheOCSyoumustenterthenormalfortheOCSinthefinalargumentoftheTranslateCoordinatesfunction.
DCS
Displaycoordinatesystem:Thecoordinatesystemwhereobjectsaretransformedbeforetheyaredisplayed.TheoriginoftheDCSisthepointstoredintheAutoCADsystemvariableTARGET,anditsZaxisistheviewingdirection.Inotherwords,aviewportisalwaysaplanviewofitsDCS.ThesecoordinatescanbeusedtodeterminewheresomethingwillbedisplayedtotheAutoCADuser.
PSDCS
PaperspaceDCS:ThiscoordinatesystemcanbetransformedonlytoorfromtheDCSofthecurrentlyactivemodelspaceviewport.Thisisessentiallya2Dtransformation,wheretheXandYcoordinatesarealwaysscaledandoffsetiftheDispargumentisFALSE.TheZcoordinateisscaledbutnevertranslated.Therefore,itcanbeusedtofindthescalefactorbetweenthetwocoordinatesystems.ThePSDCScanbetransformedonlyintothecurrentmodelspaceviewport.IfthefromargumentequalsPSDCS,thenthetoargumentmustequalDCS,andviceversa.
TranslateOCScoordinatestoWCScoordinates
Thisexamplecreatesapolylineinmodelspace.ThefirstvertexforthepolylineisthendisplayedinboththeOCSandWCScoordinates.TheconversionfromOCStoWCSrequiresthenormalfortheOCSbeplacedinthelastargumentoftheTranslateCoordinatesmethod.
SubCh8_TranslateCoordinates()
'Createapolylineinmodelspace.
DimplineObjAsAcadPolyline
Dimpoints(0To14)AsDouble
'Definethe2Dpolylinepoints
points(0)=1:points(1)=1:points(2)=0
points(3)=1:points(4)=2:points(5)=0
points(6)=2:points(7)=2:points(8)=0
points(9)=3:points(10)=2:points(11)=0
points(12)=4:points(13)=4:points(14)=0
'CreatealightweightPolylineobjectinmodelspace
SetplineObj=ThisDrawing.ModelSpace.AddPolyline(points)
'FindtheXandYcoordinatesofthe
'firstvertexofthepolyline
DimfirstVertexAsVariant
firstVertex=plineObj.Coordinate(0)
'FindtheZcoordinateforthepolyline
'usingtheelevationproperty
firstVertex(2)=plineObj.Elevation
'Changethenormalfortheplinesothatthe
'differencebetweenthecoordinatesystems
'isobvious.
DimplineNormal(0To2)AsDouble
plineNormal(0)=0#
plineNormal(1)=1#
plineNormal(2)=2#
plineObj.Normal=plineNormal
'TranslatetheOCScoordinateintoWCS
DimcoordinateWCSAsVariant
coordinateWCS=ThisDrawing.Utility.TranslateCoordinates_
(firstVertex,acOCS,acWorld,False,plineNormal)
'Displaythecoordinatesofthepoint
MsgBox"Thefirstvertexhasthefollowingcoordinates:"_
&vbCrLf&"OCS:"&firstVertex(0)&","&_
firstVertex(1)&","&firstVertex(2)&vbCrLf&_
"WCS:"&coordinateWCS(0)&","&_
coordinateWCS(1)&","&coordinateWCS(2)
EndSub
Pleasesendusyourcommentaboutthispage
WorkinThree-DimensionalSpace>
Create3DObjects
CreateapolyfacemeshCreateawedgesolidAutoCADsupportsthreetypesof3Dmodeling:wireframe,surface,andsolid.Eachtypehasitsowncreationandeditingtechniques.
Formoreinformationaboutcreating3Dobjects,see“Create3DObjects”intheUser'sGuide.
Topicsinthissection
CreateWireframesCreateMeshesCreatePolyfaceMeshesCreateSolids
Pleasesendusyourcommentaboutthispage
WorkinThree-DimensionalSpace>Create3DObjects>
CreateWireframes
WithAutoCADyoucancreatewireframemodelsbypositioningany2Dplanarobjectanywherein3Dspace.Youcanposition2Dobjectsin3Dspaceusingseveralmethods:
Createtheobjectbyentering3Dpoints.YouenteracoordinatethatdefinestheX,Y,andZlocationofthepoint.
Setthedefaultconstructionplane(XYplane)onwhichyouwilldrawtheobjectbydefiningaUCS.
Movetheobjecttoitsproperorientationin3Dspaceafteryoucreateit.
Also,youcancreatesomewireframeobjects,suchaspolylines,thatcanexistinallthreedimensions.UsetheAdd3DPolymethodtocreate3Dpolylines.
Formoreinformationoncreatingwireframes,see“CreateWireframeModels”intheUser'sGuide.
Pleasesendusyourcommentaboutthispage
WorkinThree-DimensionalSpace>Create3DObjects>
CreateMeshes
Arectangularmesh(PolygonMeshobject)representsanobject'ssurfaceusingplanarfacets.Themeshdensity,ornumberoffacets,isdefinedintermsofamatrixofMandNvertices,similartoagridconsistingofcolumnsandrows.MandNspecifythecolumnandrowposition,respectively,ofanygivenvertex.Youcancreatemeshesinboth2Dand3D,buttheyareusedprimarilyfor3D.
UsetheAdd3DMeshmethodforcreatingrectangularmeshes.Thismethodtakesthreevaluesasinput:thenumberofverticesintheMdirection,thenumerofverticesintheNdirection,andavariantarraycontainingcoordinatesforalltheverticesinthemesh.
OncethePolygonMeshiscreated,usetheMCloseandNClosepropertiestoclosethemesh.
Formoreinformationoncreatingmeshes,see“CreateSurfaces”intheUser'sGuide.
Createapolygonmesh
Thisexamplecreatesa4×4polygonmesh.Thedirectionoftheactiveviewportisthenadjustedsothatthethree-dimensionalnatureofthemeshismoreeasilyviewed.
SubCh8_Create3DMesh()
DimmeshObjAsAcadPolygonMesh
DimmSize,nSize,CountAsInteger
Dimpoints(0To47)AsDouble
'createthematrixofpoints
points(0)=0:points(1)=0:points(2)=0
points(3)=2:points(4)=0:points(5)=1
points(6)=4:points(7)=0:points(8)=0
points(9)=6:points(10)=0:points(11)=1
points(12)=0:points(13)=2:points(14)=0
points(15)=2:points(16)=2:points(17)=1
points(18)=4:points(19)=2:points(20)=0
points(21)=6:points(22)=2:points(23)=1
points(24)=0:points(25)=4:points(26)=0
points(27)=2:points(28)=4:points(29)=1
points(30)=4:points(31)=4:points(32)=0
points(33)=6:points(34)=4:points(35)=0
points(36)=0:points(37)=6:points(38)=0
points(39)=2:points(40)=6:points(41)=1
points(42)=4:points(43)=6:points(44)=0
points(45)=6:points(46)=6:points(47)=0
mSize=4:nSize=4
'createsa3Dmeshinmodelspace
SetmeshObj=ThisDrawing.ModelSpace._
Add3DMesh(mSize,nSize,points)
'Changetheviewingdirectionoftheviewport
'tobetterseethecylinder
DimNewDirection(0To2)AsDouble
NewDirection(0)=-1
NewDirection(1)=-1
NewDirection(2)=1
ThisDrawing.ActiveViewport.direction=NewDirection
ThisDrawing.ActiveViewport=ThisDrawing.ActiveViewport
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
WorkinThree-DimensionalSpace>Create3DObjects>
CreatePolyfaceMeshes
UsetheAddPolyfaceMeshmethodtocreateapolyfacemesh,witheachfacecapableofhavingnumerousvertices.
Creatingapolyfacemeshissimilartocreatingarectangularmesh.Tocreateapolyfacemesh,specifycoordinatesforallitsverticesandthendefineeachfacebyenteringvertexnumbersforalltheverticesofthatface.Asyoucreatethepolyfacemesh,youcansetspecificedgestobeinvisible,assignthemtolayers,orgivethemcolors.
Tomakeanedgeinvisible,enterthevertexnumberfortheedgeasanegativevalue.Formoreinformationoncreatingpolyfacemeshes,seetheAddPolyfaceMeshmethodintheActiveXandVBAReference.
Createapolyfacemesh
ThisexamplecreatesaPolyfaceMeshobjectinmodelspace.Theviewingdirectionoftheactiveviewportisupdatedtodisplaythethree-dimensionalnatureofthemeshmoreeasily.
SubCh8_CreatePolyfaceMesh()
'Definethemeshvertices
Dimvertex(0To17)AsDouble
vertex(0)=4:vertex(1)=7:vertex(2)=0
vertex(3)=5:vertex(4)=7:vertex(5)=0
vertex(6)=6:vertex(7)=7:vertex(8)=0
vertex(9)=4:vertex(10)=6:vertex(11)=0
vertex(12)=5:vertex(13)=6:vertex(14)=0
vertex(15)=6:vertex(16)=6:vertex(17)=1
'Definethefacelist
DimFaceList(0To7)AsInteger
FaceList(0)=1
FaceList(1)=2
FaceList(2)=5
FaceList(3)=4
FaceList(4)=2
FaceList(5)=3
FaceList(6)=6
FaceList(7)=5
'Createthepolyfacemesh
DimpolyfaceMeshObjAsAcadPolyfaceMesh
SetpolyfaceMeshObj=ThisDrawing.ModelSpace.AddPolyfaceMesh_
(vertex,FaceList)
'Changetheviewingdirectionoftheviewportto
'betterseethepolyfacemesh
DimNewDirection(0To2)AsDouble
NewDirection(0)=-1
NewDirection(1)=-1
NewDirection(2)=1
ThisDrawing.ActiveViewport.direction=NewDirection
ThisDrawing.ActiveViewport=ThisDrawing.ActiveViewport
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
WorkinThree-DimensionalSpace>Create3DObjects>
CreateSolids
Asolidobject(3DSolidobject)representstheentirevolumeofanobject.Solidsarethemostinformationallycompleteandleastambiguousofthe3Dmodelingtypes.Complexsolidshapesarealsoeasiertoconstructandeditthanwireframesandmeshes.
Youcreatesolidsfromoneofthebasicsolidshapesofbox,cone,cylinder,sphere,torus,andwedgeorbyextrudinga2Dobjectalongapathorrevolvinga2Dobjectaboutanaxis.Useoneofthefollowingmethodstocreatesolids:
AddBox,AddCone,AddCylinder,AddEllipticalCone,AddEllipticalCylinder,AddExtrudedSolid,AddExtrudedSolidAlongPath,AddRevolvedSolid,AddSolid,AddSphere,AddTorus,orAddWedge.
Likemeshes,solidsaredisplayedaswireframesuntilyouhide,shade,orrenderthem.Additionally,youcananalyzesolidsfortheirmassproperties(volume,momentsofinertia,centerofgravity,andsoforth).Usethefollowingpropertiestoanalyzesolids:MomentOfInertia,PrincipalDirections,PrincipalMoments,ProductOfInertia,RadiiOfGyration,andVolume.
TheContourlinesPerSurfacepropertycontrolsthenumberoftessellationlinesusedtovisualizecurvedportionsofthewireframe.TheRenderSmoothnesspropertyadjuststhesmoothnessofshadedandhidden-lineobjects.
Formoreinformationoncreatingsolids,see“Create3DObjects”intheUser'sGuide.
Createawedgesolid
Thefollowingexamplecreatesawedge-shapedsolidinmodelspace.Theviewingdirectionoftheactiveviewportisupdatedtodisplaythethree-dimensionalnatureofthewedgemoreeasily.
SubCh8_CreateWedge()
DimwedgeObjAsAcad3DSolid
Dimcenter(0To2)AsDouble
DimlengthAsDouble
DimwidthAsDouble
DimheightAsDouble
'Definethewedge
center(0)=5#:center(1)=5#:center(2)=0
length=10#:width=15#:height=20#
'Createthewedgeinmodelspace
SetwedgeObj=ThisDrawing.ModelSpace._
AddWedge(center,length,width,height)
'Changetheviewingdirectionoftheviewport
DimNewDirection(0To2)AsDouble
NewDirection(0)=-1
NewDirection(1)=-1
NewDirection(2)=1
ThisDrawing.ActiveViewport.direction=NewDirection
ThisDrawing.ActiveViewport=ThisDrawing.ActiveViewport
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
WorkinThree-DimensionalSpace>
Editin3D
Thissectiondescribeshowtoedit3Dobjectsby,forexample,rotating,arraying,andmirroring.
Topicsinthissection
Rotatein3DArrayin3DMirrorObjectsAlongaPlane
Pleasesendusyourcommentaboutthispage
WorkinThree-DimensionalSpace>Editin3D>
Rotatein3D
WiththeRotatemethod,youcanrotateobjectsin2Daboutaspecifiedpoint.ThedirectionofrotationisdeterminedbytheWCS.TheRotate3Dmethodrotatesobjectsin3Daboutaspecifiedaxis.TheRotate3Dmethodtakesthreevaluesasinput:theWCScoordinatesofthetwopointsdefiningtherotationaxisandtherotationangleinradians.
Torotate3Dobjects,useeithertheRotateorRotate3Dmethod.
Formoreinformationonrotatingin3D,see“RotateObjects”intheUser'sGuide.
Createa3Dboxandrotateitaboutanaxis
Thisexamplecreatesa3Dbox.Itthendefinestheaxisforrotationandfinallyrotatesthebox30degreesabouttheaxis.
SubCh8_Rotate_3DBox()
DimboxObjAsAcad3DSolid
DimlengthAsDouble
DimwidthAsDouble
DimheightAsDouble
Dimcenter(0To2)AsDouble
'Definethebox
center(0)=5:center(1)=5:center(2)=0
length=5
width=7
height=10
'Createtheboxobjectinmodelspace
SetboxObj=ThisDrawing.ModelSpace._
AddBox(center,length,width,height)
'Definetherotationaxiswithtwopoints
DimrotatePt1(0To2)AsDouble
DimrotatePt2(0To2)AsDouble
DimrotateAngleAsDouble
rotatePt1(0)=-3:rotatePt1(1)=4:rotatePt1(2)=0
rotatePt2(0)=-3:rotatePt2(1)=-4:rotatePt2(2)=0
rotateAngle=30
rotateAngle=rotateAngle*3.141592/180#
'Rotatethebox
boxObj.Rotate3DrotatePt1,rotatePt2,rotateAngle
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
WorkinThree-DimensionalSpace>Editin3D>
Arrayin3D
WiththeArrayRectangularmethod,youcancreatearectangulararrayin3D.Inadditiontospecifyingthenumberofcolumns(Xdirection)androws(Ydirection),youalsospecifythenumberoflevels(Zdirection).
Formoreinformationonusingarraysofobjectsin3D,see“CreateanArrayofObjects”intheUser'sGuide.
Createa3Drectangulararray
Thisexamplecreatesacircleandthenusesthatcircletocreatearectangulararrayoffourrows,fourcolumns,andthreelevelsofcircles.
SubCh8_CreateRectangularArray()
'Createthecircle
DimcircleObjAsAcadCircle
Dimcenter(0To2)AsDouble
DimradiusAsDouble
center(0)=2:center(1)=2:center(2)=0
radius=0.5
SetcircleObj=ThisDrawing.ModelSpace._
AddCircle(center,radius)
'Definetherectangulararray
DimnumberOfRowsAsLong
DimnumberOfColumnsAsLong
DimnumberOfLevelsAsLong
DimdistanceBwtnRowsAsDouble
DimdistanceBwtnColumnsAsDouble
DimdistanceBwtnLevelsAsDouble
numberOfRows=4
numberOfColumns=4
numberOfLevels=3
distanceBwtnRows=1
distanceBwtnColumns=1
distanceBwtnLevels=4
'Createthearrayofobjects
DimretObjAsVariant
retObj=circleObj.ArrayRectangular_
(numberOfRows,numberOfColumns,_
numberOfLevels,distanceBwtnRows,_
distanceBwtnColumns,distanceBwtnLevels)
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
WorkinThree-DimensionalSpace>Editin3D>
MirrorObjectsAlongaPlane
WiththeMirror3Dmethod,youcanmirrorobjectsalongaspecifiedmirroringplanespecifiedbythreepoints.
Formoreinformationonmirroringobjectsin3D,see“MirrorObjects”intheUser'sGuide.
Mirrorin3D
Thisexamplecreatesaboxinmodelspace.Itthenmirrorstheboxaboutaplaneandcolorsthemirroredboxred.
SubCh8_MirrorABox3D()
'Createtheboxobject
DimboxObjAsAcad3DSolid
DimlengthAsDouble
DimwidthAsDouble
DimheightAsDouble
Dimcenter(0To2)AsDouble
center(0)=5#:center(1)=5#:center(2)=0
length=5#:width=7:height=10#
'Createthebox(3DSolid)objectinmodelspace
SetboxObj=ThisDrawing.ModelSpace._
AddBox(center,length,width,height)
'Definethemirroringplanewiththreepoints
DimmirrorPt1(0To2)AsDouble
DimmirrorPt2(0To2)AsDouble
DimmirrorPt3(0To2)AsDouble
mirrorPt1(0)=1.25:mirrorPt1(1)=0:mirrorPt1(2)=0
mirrorPt2(0)=1.25:mirrorPt2(1)=2:mirrorPt2(2)=0
mirrorPt3(0)=1.25:mirrorPt3(1)=2:mirrorPt3(2)=2
'Mirrorthebox
DimmirrorBoxObjAsAcad3DSolid
SetmirrorBoxObj=boxObj.Mirror3D_
(mirrorPt1,mirrorPt2,mirrorPt3)
mirrorBoxObj.Color=acRed
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
WorkinThree-DimensionalSpace>
Edit3DSolids
Onceyouhavecreatedasolid,youcancreatemorecomplexshapesbycombiningsolids.Youcanjoinsolids,subtractsolidsfromeachother,orfindthecommonvolume(overlappingportion)ofsolids.UsetheBooleanorCheckInterferencemethodtoperformthesecombinations.
Solidsarefurthermodifiedbyobtainingthe2Dcrosssectionofasolidorslicingasolidintotwopieces.UsetheSectionSolidmethodtofindcrosssectionsofsolids,andtheSliceSolidmethodforslicingasolidintotwopieces.
Findtheinterferencebetweentwosolids
Thisexamplecreatesaboxandacylinderinmodelspace.Itthenfindstheinterferencebetweenthetwosolidsandcreatesanewsolidfromthatinterference.Foreaseofviewing,theboxiscoloredwhite,thecylinderiscoloredcyan,andtheinterferencesolidiscoloredred.
SubCh8_FindInterferenceBetweenSolids()
'Definethebox
DimboxObjAsAcad3DSolid
DimlengthAsDouble
DimwidthAsDouble
DimheightAsDouble
Dimcenter(0To2)AsDouble
center(0)=5:center(1)=5:center(2)=0
length=5
width=7
height=10
'Createtheboxobjectinmodelspace
'andcoloritwhite
SetboxObj=ThisDrawing.ModelSpace._
AddBox(center,length,width,height)
boxObj.Color=acWhite
'Definethecylinder
DimcylinderObjAsAcad3DSolid
DimcylinderRadiusAsDouble
DimcylinderHeightAsDouble
center(0)=0:center(1)=0:center(2)=0
cylinderRadius=5
cylinderHeight=20
'CreatetheCylinderand
'coloritcyan
SetcylinderObj=ThisDrawing.ModelSpace.AddCylinder_
(center,cylinderRadius,cylinderHeight)
cylinderObj.Color=acCyan
'Findtheinterferencebetweenthetwosolids
'andcreateanewsolidfromit.Colorthe
'newsolidred.
DimsolidObjAsAcad3DSolid
SetsolidObj=boxObj.CheckInterference(cylinderObj,True)
solidObj.Color=acRed
ZoomAll
EndSub
Sliceasolidintotwosolids
Thisexamplecreatesaboxinmodelspace.Itthenslicestheboxbasedonaplanedefinedbythreepoints.Thesliceisreturnedasa3DSolid.
SubCh8_SliceABox()
'Createtheboxobject
DimboxObjAsAcad3DSolid
DimlengthAsDouble
DimwidthAsDouble
DimheightAsDouble
Dimcenter(0To2)AsDouble
center(0)=5#:center(1)=5#:center(2)=0
length=5#:width=7:height=10#
'Createthebox(3DSolid)objectinmodelspace
SetboxObj=ThisDrawing.ModelSpace._
AddBox(center,length,width,height)
boxObj.Color=acWhite
'Definethesectionplanewiththreepoints
DimslicePt1(0To2)AsDouble
DimslicePt2(0To2)AsDouble
DimslicePt3(0To2)AsDouble
slicePt1(0)=1.5:slicePt1(1)=7.5:slicePt1(2)=0
slicePt2(0)=1.5:slicePt2(1)=7.5:slicePt2(2)=10
slicePt3(0)=8.5:slicePt3(1)=2.5:slicePt3(2)=10
'slicetheboxandcolorthenewsolidred
DimsliceObjAsAcad3DSolid
SetsliceObj=boxObj.SliceSolid_
(slicePt1,slicePt2,slicePt3,True)
sliceObj.Color=acRed
ZoomAll
EndSub
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot
Afteryou'vecreatedyourdrawingwithAutoCAD,youusuallyplotitonpaper.Aplotteddrawingcancontainasingleviewofyourdrawingoramorecomplexarrangementofviews.Inpaperspace,youcancreatewindowscalledfloatingviewports,whichdisplayvariousviewsofthedrawing.Dependingonyourneeds,youcanplotoneormoreviewports,orsetoptionsthatdeterminewhatisplottedandhowtheimagefitsonthepaper.
Topicsinthissection
ModelSpaceandPaperSpaceLayoutsViewportsPlotYourDrawing
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>
ModelSpaceandPaperSpace
Modelspaceisthedrawingenvironmentinwhichyoucreatethegeometryforyourmodel.Normally,asyoubegintodrawinmodelspace,youdesignateyourdrawinglimitstodeterminetheextentsofthedrawingenvironment,andyoudrawinrealworldunits.
Paperspacerepresentsthepaperrepresentationofyourmodelasitwillbeplotted.Inpaperspaceyoucanlayoutdifferentviewsofyourdrawing,scaleviewsindependentlyfromoneanother,andarrangethedifferentviewsofyourdrawingasyouwantthemtobeplotted.Therecanbemanydifferentpaperspacerepresentationsofyourdrawing.
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>
Layouts
Allthegeometryofyourdrawingiscontainedinlayouts.ModelspacegeometryiscontainedonasinglelayoutnamedModel.Youcannotrenamethemodelspacelayout,norcanyoucreateanothermodelspacelayout.Therecanbeonlyonemodelspacelayoutperdrawing.
Paperspacegeometryisalsocontainedonlayouts.Youcanhavemanydifferentpaperspacelayoutsinyourdrawing,eachrepresentingadifferentconfigurationtoprint.Youcanchangethenameofthepaperspacelayouts.
InActiveX®AutomationtheModelSpacecollectioncontainsallthegeometryinthemodelspacelayout.Becausetherecanbemorethanonepaperspacelayoutinadrawing,thePaperSpacecollectionpointstothelastactivepaperspacelayout.
Formoreinformationaboutworkingwithpaperspacelayouts,see“Hatches,Fills,andWipeouts”intheUser'sGuide.
Topicsinthissection
LayoutsandBlocksPlotConfigurationsLayoutSettings
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>Layouts>
LayoutsandBlocks
ThecontentofanylayoutisdistributedamongtwodifferentActiveXobjects:theLayoutobjectandtheBlockobject.TheLayoutobjectcontainstheplotsettingsandthevisualpropertiesofthelayoutasitappearsintheAutoCADuserinterface.TheBlockobjectcontainsthegeometryforthelayout.
EachLayoutobjectisassociatedwithone,andonlyone,Blockobject.ToaccesstheBlockobjectassociatedwithagivenlayout,usetheBlockproperty.Conversely,eachBlockobjectisassociatedwithone,andonlyone,Layoutobject.ToaccesstheLayoutobjectassociatedwithagivenBlock,usetheLayoutpropertyforthatblock.
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>Layouts>
PlotConfigurations
APlotConfigurationobjectissimilartoaLayoutobject,asbothcontainidenticalplotinformation.ThedifferenceisthataLayoutobjectisassociatedwithaBlockobjectcontainingthegeometrytoplot.APlotConfigurationobjectisnotassociatedwithaparticularBlockobject.Itissimplyanamedcollectionofplotsettingsavailableforusewithanygeometry.
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>Layouts>
LayoutSettings
Layoutsettingscontrolthefinalplottedoutput.Thesesettingsaffectthepapersize,plotscale,plotarea,plotorigin,andtheplotdevicename.Understandinghowtouselayoutsettingsensuresthatthelayoutisplottedasexpected.AllthesettingsforalayoutcanbechangedfromtheLayoutobjectpropertiesandmethods.
Topicsinthissection
PaperSizeandUnitsAdjustthePlotOriginSetthePlotAreaSetthePlotScaleSettheLineweightScaleSetthePlotDevice
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>Layouts>LayoutSettings>
PaperSizeandUnits
Thechoiceofpapersizedependsontheplotterconfiguredforyoursystem.Eachdifferentplotterwillhaveastandardlistofavailablepapersizes.YoucanchangethepapersizeforalayoutbyusingtheCanonicalMediaNameproperty.
YoucanalsospecifytheunitsforyourlayoutusingthePaperUnitsproperty.Thispropertytakesoneofthreevalues:acInches,acMillimeters,oracPixels.Ifyourplotterisconfiguredforrasteroutput,youmustspecifytheoutputsizeinpixels.
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>Layouts>LayoutSettings>
AdjustthePlotOrigin
Theplotoriginisthelower-leftcornerofthespecifiedplottedareaandiscontrolledwiththePlotOriginproperty.Typically,theplotoriginissetto(0,0).However,youcancentertheplotonthesheetofpaperbysettingtheCenterPlotpropertytoTRUE.Centeringtheplotalterstheplotorigin.
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>Layouts>LayoutSettings>
SetthePlotArea
Whenyoupreparetoplotalayout,youcanspecifytheplotareatodeterminewhatwillbeincludedintheplot.Tospecifytheplotarea,usethePlotTypeproperty.Thispropertyrequiresoneofthefollowingvaluesasinput:
acDisplay
Printseverythingthatisinthecurrentmodelspacedisplay.Thisoptionisunavailablewhenplottingfromapaperspacelayout.
acExtents
Printseverythingthatfallswithintheboundariesofthecurrentlyselectedspace.
acLimits
Printseverythingthatisinthelimitsofthecurrentspace.
acView
PrintstheviewnamedbytheViewToPlotproperty.
acWindow
PrintseverythinginthewindowspecifiedbytheSetWindowToPlotmethod.
acLayout
Printseverythingthatfallswithinthemarginsofthespecifiedpapersize.Thisoptionisnotavailablewhenprintingfrommodelspace.
Whenyoucreateanewpaperspacelayout,thedefaultoptionisacLayout.
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>Layouts>LayoutSettings>
SetthePlotScale
Generally,youdrawobjectsattheiractualsize.Whenyouplotthedrawing,youcaneitherspecifyaprecisescaleorfittheimagetothepaper.Tospecifyascale,entereitherastandardorcustomplotscale.
Toenterastandardscale,firstsettheUseStandardScalepropertytoTRUE.YoucanthenenterthedesiredscaleusingtheStandardScaleproperty.
Toenteracustomscale,firstsettheUseStandardScalepropertytoFALSE.YoucanthenenterthecustomscaleusingtheSetCustomScalemethod.
Whenyouarereviewinganearlydraftview,aprecisescaleisnotalwaysimportant.YoucanusetheacScaleToFitvalueoftheStandardScalepropertytoplotthelayoutatthelargestpossiblesizethatfitsthepaper.
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>Layouts>LayoutSettings>
SettheLineweightScale
Lineweightscanbescaledproportionatelyinalayoutwiththeplotscale.Typically,lineweightsspecifythelinewidthofplottedobjectsandareplottedwiththelinewidthsizeregardlessoftheplotscale.Mostoften,youusethedefaultplotscaleof1:1whenplottingalayout.However,ifyouwanttoplotanE-sizelayoutthatisscaledtofitonanA-sizesheetofpaper,forexample,youcanspecifylineweightstobescaledinproportiontothenewplotscale.
Toscalelineweights,settheScaleLineweightspropertytoTRUE.Ifyoudonotwantlineweightstobescaled,setthispropertytoFALSE.
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>Layouts>LayoutSettings>
SetthePlotDevice
TheplotdevicenameisspecifiedintheConfigNameproperty.Youcansetthisnametoanyvaliddevicenameforyoursystem.Ifyoudonotsetthisproperty,plotswillbesenttothedefaultdeviceforyoursystem.
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>
Viewports
Whenworkinginmodelspaceyoudrawgeometryintileviewports(referredtoasViewportobjectsinActiveXAutomation).Youcandisplayoneorseveraldifferentviewportsatatime.Ifseveraltiledviewportsaredisplayed,editinginoneviewportaffectsallotherviewports.However,youcansetmagnification,viewpoint,grid,andsnapsettingsindividuallyforeachviewport.
Inpaperspace,youworkinfloatingpaperspaceviewports(referredtoasPViewportobjectsinActiveXAutomation)tocontaindifferentviewsofyourmodel.Floatingviewportsaretreatedasobjectsyoucanmove,resize,andshapetocreateasuitablelayout.Youalsocandrawobjects,suchastitleblocksorannotations,directlyinthepaperspaceviewwithoutaffectingthemodelitself.
Formoreinformationaboutviewports,see“SetModelSpaceViewports”and
“DisplayMultipleViewsinModelSpace”intheUser'sGuide.
Topicsinthissection
FloatingViewportsSwitchtoaPaperSpaceLayoutSwitchtotheModelSpaceLayoutCreatePaperSpaceViewportsChangeViewportViewsandContentScaleViewsRelativetoPaperSpace
ScalePatternLinetypesinPaperSpaceUseShadedViewports
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>Viewports>
FloatingViewports
Youcannoteditthemodelinpaperspace.ToaccessthemodelinaPViewportobject,togglefrompaperspacetomodelspaceusingtheActiveSpaceproperty.Asaresult,youcanworkwiththemodelwhilekeepingtheoveralllayoutvisible.InPViewportobjects,theeditingandview-changingcapabilitiesarealmostthesameasinViewportobjects.However,youhavemorecontrolovertheindividualviews.Forexample,youcanfreezeorturnofflayersinsomeviewportswithoutaffectingothers.Youcanturnanentireviewportdisplayonoroff.Youcanalsoalignviewsbetweenviewportsandscaletheviewsrelativetotheoveralllayout.
Thefollowingillustrationshowshowdifferentviewsofamodelaredisplayedinpaperspace.EachpaperspaceimagerepresentsaPViewportobjectwithadifferentview.Inoneview,thedimensioninglayerisfrozen.Noticethatthetitleblock,border,andannotation,whicharedrawninpaperspace,donotappearintheModelSpaceview.Also,thelayercontainingtheviewportbordershasbeenturnedoff.
WhenyouworkinaViewportobject,theActiveSpacepropertymustalwaysbesettoacModelSpace.WhenyouareworkinginaPViewportobject,youcansettheActiveSpacepropertytoeitheracModelSpaceoracPaperSpace,thusallowingyoutoswitchbetweenpaperspaceandmodelspaceasneeded.
PViewportobject,Viewportobject,andActiveSpace
propertysettings
Typeofviewport Status Usage
PViewport ActiveSpace=acPaperspace
Arrangethelayoutbycreatingfloatingviewportsandaddingtitleblock,borders,andannotation.Editingdoesnotaffectthemodel.
PViewport ActiveSpace=acModelspace
Workwithinfloatingviewportstoeditthemodelorchangeviews.Youcanturnofforfreezelayersinindividualviewports.
Viewport ActiveSpace=acModelspace
Splitthescreenintotiledviewportstoeditdifferentviewsofthemodel.
InAutoCAD®ActiveXAutomation,theActiveSpacepropertyisusedtocontroltheTILEMODEsystemvariable.SettingThisDrawing.ActiveSpace=acModelSpaceisequivalenttosettingTILEMODE=on,andsettingThisDrawing.ActiveSpace=acPaperSpaceisequivalenttosettingTILEMODE=off.
Similarly,theMSpacepropertyistheequivalentofboththeMSPACEandPSPACEcommandsinAutoCAD.SettingThisDrawing.MSpace=TRUEisthesameasusingtheMSPACEcommand:itswitchestomodelspace.SettingThisDrawing.MSpace=FALSEisthesameasusingthePSPACEcommand:itswitchestopaperspace.
Inaddition,youarerequiredtousetheDisplaymethodbeforesettingtheMSpacepropertytoTRUE.TheDisplaymethodinitializescertaingraphic
settingsthatmustbesetbeforeswitchingtomodelspace.InAutoCADthisisdone“behindthescenes.”However,intheActiveXAutomationinterface,theprogrammermusttakecareofthisinitialization.
Note Remember,youmustturnonthedisplayusingtheDisplaymethodforatleastonePViewportobjectbeforeyoucansettheMSpacepropertytoTRUE.FailuretoturnonthedisplaywillresultinanerrorbeingreturnedwhenyoutrytosettheMSpaceproperty.
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>Viewports>
SwitchtoaPaperSpaceLayout
Frommodelspace,youcanswitchtothelastactivepaperspacelayout.
Toswitchtothelastactivepaperspacelayout
1. SettheActiveSpacepropertytoacPaperSpace:
ThisDrawing.ActiveSpace=acPaperSpace
2. ToggletheMSpacepropertytoFALSE:
ThisDrawing.MSpace=FALSE
Whenyouareinpaperspace,AutoCADdisplaysthepaperspaceusercoordinatesystem(UCS)iconinthelower-leftcornerofthegraphicsarea.Thecrosshairsindicatethatthepaperspacelayoutarea(nottheviewsintheviewports)canbeedited.
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>Viewports>
SwitchtotheModelSpaceLayout
Frompaperspace,youcanswitchtomodelspacefloatingviewportsormodelspacetiledviewports.
Toswitchtofloatingviewports
1. UsetheDisplaymethodtoinitializegraphicsettings:
ThisDrawing.ActivePViewport.DisplayTRUE
2. ToggletheMSpacepropertytoTRUE:
ThisDrawing.MSpace=TRUE
Thiswillplaceyouinmodelspace,floatingviewports.
Note Youmustcreatefloatingviewportsbeforeyouattempttoswitchtomodelspace.
Toswitchtotiledviewports
Toswitchtotiledviewports,performthisadditionalstep:
SettheActiveSpacepropertytoacModelSpace:
ThisDrawing.ActiveSpace=acModelSpace
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>Viewports>
CreatePaperSpaceViewports
PaperspaceviewportsarecreatedwiththeAddPViewportmethod.Thismethodrequiresacenterpointandthewidthandheightofthenewviewport.Beforecreatingtheviewport,usetheActiveSpacepropertytosetpaperspaceasthecurrentspace(normallydonebysettingTILEMODEto0).
AftercreatingthePViewportobject,youcansetpropertiesoftheviewitself,suchasviewingdirection(Directionproperty),lenslengthforperspectiveviews(LensLengthproperty),andgriddisplay(GridOnproperty).Youcanalsocontrolpropertiesoftheviewportitself,suchaslayer(Layerproperty),linetype(Linetypeproperty),andlinetypescaling(LinetypeScaleproperty).
Createandenableafloatingviewport
ThisexampleswitchesAutoCADtopaperspace,createsafloatingviewport,setstheview,andenablestheviewport.
SubCh9_SwitchToPaperSpace()
'Settheactivespacetopaperspace
ThisDrawing.ActiveSpace=acPaperSpace
'Createthepaperspaceviewport
DimnewVportAsAcadPViewport
Dimcenter(0To2)AsDouble
center(0)=3.25
center(1)=3
center(2)=0
SetnewVport=ThisDrawing.PaperSpace._
AddPViewport(center,6,5)
'Changetheviewdirectionfortheviewport
DimviewDir(0To2)AsDouble
viewDir(0)=1
viewDir(1)=1
viewDir(2)=1
newVport.direction=viewDir
'Enabletheviewport
newVport.DisplayTrue
'Switchtomodelspace
ThisDrawing.MSpace=True
'SetnewVportcurrent
'(notalwaysnecessarybutagoodidea)
ThisDrawing.ActivePViewport=newVport
'ZoomExtentsinmodelspace
ZoomExtents
'Turnmodelspaceeditingoff
ThisDrawing.MSpace=False
'ZoomExtentsinpaperspace
ZoomExtents
EndSub
Theorderofstepsintheprecedingcodeisimportant.Ingeneral,thingsmustbedoneinthesameordertheywouldbedoneattheAutoCADcommandline.Theonlyunexpectedactionsinvolvedefiningtheviewandenablingtheviewport.
Note Tosetormodifyaspectsoftheview(viewdirection,lenslength,andsoforth),theViewportobject'sDisplaymethodmustbesettooff(FALSE),andbeforeyoucansetaviewportcurrenttheDisplaymethodmustbesettoon(TRUE).
Createfourfloatingviewports
Thisexampletakestheexamplefrom"Createandenableafloatingviewport"andcontinuesitbycreatingfourfloatingviewportsandsettingtheviewofeachtotop,front,right,andisometricviews,respectively.Eachviewisscaledtohalfthescaleofpaperspace.Toensurethereissomethingtoseeintheseviewports,youmaywanttocreatea3Dsolidspherebeforetryingthisexample.
SubCh9_FourPViewports()
DimtopVport,frontVportAsAcadPViewport
DimrightVport,isoVportAsAcadPViewport
Dimpt(0To2)AsDouble
DimviewDir(0To2)AsDouble
ThisDrawing.ActiveSpace=acPaperSpace
ThisDrawing.MSpace=True
'TaketheexistingPViewportandmakeitthetopVport
pt(0)=2.5:pt(1)=5.5:pt(2)=0
SettopVport=ThisDrawing.ActivePViewport
'NoneedtosetDirectionfortopview
topVport.center=pt
topVport.width=2.5
topVport.height=2.5
topVport.DisplayTrue
ThisDrawing.MSpace=True
ThisDrawing.ActivePViewport=topVport
ZoomExtents
ZoomScaled0.5,acZoomScaledRelativePSpace
'CreateandsetupfrontVport
pt(0)=2.5:pt(1)=2.5:pt(2)=0
SetfrontVport=ThisDrawing.PaperSpace._
AddPViewport(pt,2.5,2.5)
viewDir(0)=0:viewDir(1)=1:viewDir(2)=0
frontVport.direction=viewDir
frontVport.DisplayacOn
ThisDrawing.MSpace=True
ThisDrawing.ActivePViewport=frontVport
ZoomExtents
ZoomScaled0.5,acZoomScaledRelativePSpace
'CreateandsetuprightVport
pt(0)=5.5:pt(1)=5.5:pt(2)=0
SetrightVport=ThisDrawing.PaperSpace._
AddPViewport(pt,2.5,2.5)
viewDir(0)=1:viewDir(1)=0:viewDir(2)=0
rightVport.direction=viewDir
rightVport.DisplayacOn
ThisDrawing.MSpace=True
ThisDrawing.ActivePViewport=rightVport
ZoomExtents
ZoomScaled0.5,acZoomScaledRelativePSpace
'CreateandsetupisoVport
pt(0)=5.5:pt(1)=2.5:pt(2)=0
SetisoVport=ThisDrawing.PaperSpace._
AddPViewport(pt,2.5,2.5)
viewDir(0)=1:viewDir(1)=1:viewDir(2)=1
isoVport.direction=viewDir
isoVport.DisplayacOn
ThisDrawing.MSpace=True
ThisDrawing.ActivePViewport=isoVport
ZoomExtents
ZoomScaled0.5,acZoomScaledRelativePSpace
'Finish:Performaregeninallviewports
ThisDrawing.RegenTrue
EndSub
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>Viewports>
ChangeViewportViewsandContent
TochangetheviewwithinaViewportobject,youmustbeinmodelspaceandtheviewportmustbeactive.
Toeditadrawinginafloatingviewport
1. Inmodelspace,maketheviewportactivebysettingtheActiveViewportproperty:
Thisdrawing.ActiveViewport=MyViewportObject
2. Editthedrawing.
Youcanalsocreateobjectssuchasannotations,dimensions,andtitleblocksinpaperspace.Youmust,however,settheActiveSpacepropertytoFALSE,andturnpaperspaceonusingtheMSpaceproperty.Objectscreatedinpaperspacearevisibleonlyinpaperspace.
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>Viewports>
ScaleViewsRelativetoPaperSpace
Beforeyouplot,youcanestablishaccuratezoomscalefactorsforeachsectionofyourdrawing.Scalingviewsrelativetopaperspaceestablishesaconsistentscaleforeachdisplayedview.Forexample,thefollowingillustrationshowsapaperspaceviewwithseveralviewports—eachsettodifferentscalesandviews.Toscaletheplotteddrawingaccurately,youmustscaleeachviewrelativetopaperspace,notrelativetothepreviousviewortothefull-scalemodel.
Whenyouworkinpaperspace,thescalefactorrepresentsaratiobetweenthesizeoftheplotteddrawingandtheactualsizeofthemodeldisplayedintheviewports.Toderivethisscale,dividepaperspaceunitsbymodelspaceunits.Foraquarter-scaledrawing,forexample,youspecifyascalefactorofonepaperspaceunittofourmodelspaceunits(1:4).
UsetheZoomScaledmethodtoscaleviewportsrelativetopaperspaceunits.Thismethodtakesthreevaluesasinput:theviewporttoscale,thescalefactor,andhowyouwantthatscalefactorapplied.Thethirdvalueisoptionalanddetermineshowthescaleisapplied:
Relativetothedrawinglimits
Relativetothecurrentview
Relativetopaperspaceunits
Tospecifythescalerelativetopaperspaceunits,entertheacZoomScaled-
RelativePSpaceconstantforthisvalue.
Asshownintheillustrations,ifyouenterascaleof2relativetothepaperspaceunits,thescaleintheviewportincreasestotwicethesizeofthepaperspaceunits.Ascaleof.5relativetothepaperspaceunitssetsthescaletohalfthesizeofthepaperspaceunits.Themodelisplottedathalfitsactualsize.
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>Viewports>
ScalePatternLinetypesinPaperSpace
Inpaperspace,youcanscaleanytypeoflinetypeintwoways.Thescalecanbebasedonthedrawingunitsofthespaceinwhichtheobjectwascreated(modelorpaper).Thelinetypescalealsocanbeauniformscalebasedonpaperspaceunits.YoucanusethePSLTSCALEsystemvariabletomaintainthesamelinetypescalingforobjectsdisplayedatdifferentzoomscalesindifferentviewports.Italsoaffectsthelinedisplayin3Dviews.
Inthefollowingillustration,thepatternlinetypeofthelinesinmodelspaceisscaleduniformlyinpaperspacebythePSLTSCALEsystemvariable.Noticethatthelinetypeinthetwoviewportshasthesamescale,eventhoughtheobjectshavedifferentzoomscales.
UsetheSetVariablemethodtosetthevalueofthePSLTSCALEsystemvariable.
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>Viewports>
UseShadedViewports
Ifyourdrawingcontains3Dfaces,meshes,extrudedobjects,surfaces,orsolids,youcanplotfrompaperspaceusingtheAsDisplayed,Wireframe,Hidden,andRenderedoptions.Shadedandrenderedviewportsareplot-previewed,plotted,andplottedtofilewithfullshadingandrendering.
Tosetanoptionforshadedviewportplottinginpaperspace,usetheShadePlotpropertyofthePViewportobject.
Note Tohidelinesinplotsofmodelspaceviewports(Viewportobjects)usethePlotHiddenpropertyoftheLayoutobject.ThispropertytakesaBooleanvalue:TRUEtoremovehiddenlines,FALSEtodrawthem.
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>
PlotYourDrawing
Youcanplotyourdrawingasitisviewedinmodelspace,oryoucanplotoneofyourpreparedpaperspacelayouts.Plottingfrommodelspaceisoftenpreferablewhenyouwanttovieworverifyyourdrawingpriortocreatingapaperspacelayout.Onceyourmodelisready,youcanprepareandplotapaperspacelayout.
Note TheBACKGROUNDPLOTsystemvariablemustbesetto0beforeascriptcanplotmultiplejobs.
PlottinginvolvesworkingwithtwoActiveXAutomationobjects:theLayoutobjectandthePlotobject.TheLayoutobjectcontainstheplotsettingsforagivenlayout.ThePlotobjectcontainsthemethodsandpropertiesthatinitiateandmonitoraplottingsequence.
Topicsinthissection
PerformBasicPlottingPlotfromModelSpacePlotfromPaperSpace
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>PlotYourDrawing>
PerformBasicPlotting
FromthePlotobject,youcanusethefollowingmethodsandproperties:
PlotToFile
Plotstoafile.
PlotToDevice
Plotstoaplotterorprinter.
DisplayPlotPreview
Displaysapreviewofthespecifiedplot.
QuietErrorMode
Togglesthequieterrormodeforploterrorreporting.
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>PlotYourDrawing>
PlotfromModelSpace
Typically,whenyouplotalargedrawingsuchasafloorplan,youcanspecifyascaletoconverttherealdrawingunitsintoplottedinchesormillimeters.However,whenyouplotfrommodelspace,thedefaultsthatareusediftherearenosettingsspecifiedincludeplottosystemprinter,plotthecurrentdisplay,scaledtofit,0rotation,and0,0offset.Tomodifytheplotsettings,changethepropertiesontheLayoutobjectassociatedwithmodelspace.
Plottheextentsofanactivemodelspacelayout
Thisexamplefirstcheckstomakesuretheactivespaceismodelspace.Theexamplethenestablishesseveralplotsettings.Finally,theplotissentusingthePlotToDevicemethod.
SubCh9_PrintModelSpace()
'Verifythattheactivespaceismodelspace
IfThisDrawing.ActiveSpace=acPaperSpaceThen
ThisDrawing.MSpace=True
ThisDrawing.ActiveSpace=acModelSpace
EndIf
'Settheextentsandscaleoftheplotarea
ThisDrawing.ModelSpace.Layout.PlotType=acExtents
ThisDrawing.ModelSpace.Layout._
StandardScale=acScaleToFit
'Setthenumberofcopiestoone
ThisDrawing.Plot.NumberOfCopies=1
'Initiatetheplot
ThisDrawing.Plot.PlotToDevice
EndSub
ThedevicenamecanbespecifiedusingtheConfigNameproperty.ThisdevicecanbeoverriddeninthePlotToDevicemethodbyspecifyingaPC3file.
Pleasesendusyourcommentaboutthispage
DefineLayoutsandPlot>PlotYourDrawing>
PlotfromPaperSpace
Youcanplotapaperspacelayout.Youcanplottheactivelayout,asdemonstratedin"PlotfromModelSpace",oryoucanspecifybynamethelayouttoplot.
Pleasesendusyourcommentaboutthispage
<$nopage>bitonalimages.<$nopage>blockreferences:<$nopage>BlockReferenceobject:<$nopage>xrefs.
AdvancedDrawingandOrganizationalTechniques
Asyougainexperience,youcantakeadvantageofthemanyadvancedfeaturesofAutoCADtofurtherenhanceyourapplications.
Youcanincludeinyourdrawingrasterimagessuchasaerial,satellite,anddigitalphotographs,aswellascomputer-renderedimages.Forinformationaboutrasterimagesinadditiontotheinformationinthissection,seetheUser'sGuide.
Inadditiontoenhancingyourdrawing'svisualimage,AutoCADprovidesseveralfeaturestohelpyouorganizedata,allowingyoutofurtherexpandtheintelligenceoftheobjectsinyourdrawing.
Topicsinthissection
WorkwithRasterImagesUseBlocksandAttributesUseExternalReferencesAssignandRetrieveExtendedData
Pleasesendusyourcommentaboutthispage
<$nopage>bitonalimages.
AdvancedDrawingandOrganizationalTechniques>
WorkwithRasterImages
WithAutoCAD®,youcanaddrasterimagestoyourvector-basedAutoCADdrawings,andthenviewandplottheresultingfile.
Topicsinthissection
AttachandScaleaRasterImageManageRasterImagesModifyImagesandImageBoundariesClipImages
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>WorkwithRasterImages>
AttachandScaleaRasterImage
Imagescanbeplacedinadrawingfile,buttheyarenotactuallypartofthefile.TheimageislinkedtothedrawingfilethroughapathnameoradatamanagementdocumentID.Linkedimagepathscanbechangedorremovedatanytime.Toattachanimage,youcreateaRasterobjectinyourdrawingusingtheAddRastermethod.Thismethodtakesfourvaluesasinput:thenameoftheimagefiletoattach,theinsertionpointinthedrawingtoplacetheimage,thescalefactoroftheimage,andtherotationangleoftheimage.Remember,theRasterobjectrepresentsanindependentlinktotheimage,nottheimageitself.
Onceyou'veattachedanimage,youcanreattachitmanytimes,creatinganewRasterobjectforeachattachment.Eachattachmenthasitsownclipboundaryanditsownsettingsforbrightness,contrast,fade,andtransparency.Asingleimagecanbecutintomultiplepiecesandrearrangedindependentlyinyourdrawing.
YoucansettherasterimagescalefactorwhenyoucreatetheRasterobjectsothattheimage'sgeometryscalematchesthescaleofthegeometrycreatedintheAutoCADdrawing.Whenyouselectanimagetoattach,theimageisinsertedatascalefactorof1imageunitofmeasurementto1AutoCADunitofmeasurement.Tosettheimagescalefactor,youneedtoknowthescaleofthegeometryontheimage,andyouneedtoknowwhatunitofmeasurement(inches,feet,andsoforth)youwanttousetodefine1AutoCADunit.TheimagefilemustcontainresolutioninformationdefiningtheDPI,ordotsperinch,andnumberofpixelsintheimage.
Ifanimagehasresolutioninformation,AutoCADcombinesitwiththescalefactorandtheAutoCADunitofmeasurementyousupplytoscaletheimageinyourdrawing.Forexample,ifyourrasterimageisascannedblueprintonwhichthescaleis1inchequals50feet,or1:600,andyourAutoCADdrawingissetupsothat1unitrepresents1inch,thentosetthescalefactoroftheimage,you
enter600fortheScaleFactorparameteroftheAddRastermethod.AutoCADtheninsertstheimageatascalethatbringsthegeometryintheimageintoalignmentwiththevectorgeometryinthedrawing.
Note Ifnoresolutioninformationisdefinedwiththeattachedimagefile,AutoCADcalculatestheimage'soriginalwidthasoneunit.Afterinsertion,theimagewidthinAutoCADunitsisequaltothescalefactor.
Attacharasterimage
Thisexampleaddsarasterimageinmodelspace.Thisexampleusesthewatch.jpgfilefoundinthesampledirectory.Ifyoudonothavethisimage,orifitislocatedinadifferentdirectory,insertavalidpathandfilenamefortheimageNamevariable.
SubCh10_AttachingARaster()
DiminsertionPoint(0To2)AsDouble
DimscalefactorAsDouble
DimrotationAngleAsDouble
DimimageNameAsString
DimrasterObjAsAcadRasterImage
imageName="C:/ProgramFiles/AutoCADDirectory/sample/watch.jpg'
insertionPoint(0)=5
insertionPoint(1)=5
insertionPoint(2)=0
scalefactor=2
rotationAngle=0
OnErrorGoToERRORHANDLER
'Attachtherasterimageinmodelspace
SetrasterObj=ThisDrawing.ModelSpace.AddRaster_
(imageName,insertionPoint,_
scalefactor,rotationAngle)
ZoomAll
ExitSub
ERRORHANDLER:
MsgBoxErr.Description
EndSub
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>WorkwithRasterImages>
ManageRasterImages
Youcanmanagerasterimagename,filename,andfilepathusingthepropertiesoftheRasterobject.
Topicsinthissection
ChangeImageFilePathsNameImages
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>WorkwithRasterImages>ManageRasterImages>
ChangeImageFilePaths
ThepathandfilenameofanimageisqueriedorchangedusingtheImageFileproperty.ThepathsetbythispropertyistheactualpathwhereAutoCADlooksfortheimage.
IfAutoCADcannotlocatethedrawing(forexample,ifyouhavemovedthefiletoadifferentdirectorythantheonesavedwiththeImageFileproperty),itremovesrelativeorabsolutepathinformationfromthename(forexample,\images\tree.tgaorc:\myproject\images\tree.tgabecomestree.tga)andsearchesthepathsyouhavedefinedusingtheSetProjectFilePathmethodonthePreferencesobject.Ifthedrawingisnotlocatedinthepaths,itattemptsthefirstsearchpathagain.
YoucanremovethepathfromthefilenameorspecifyarelativepathbyresettingtheImageFileproperty.
ChangingthepathintheImageFilepropertydoesnotaffecttheprojectfiles'search-pathsettings.
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>WorkwithRasterImages>ManageRasterImages>
NameImages
Imagenamesarenotnecessarilythesameasimagefilenames.Whenyouattachanimagetoadrawing,AutoCADusesthefilenamewithoutthefileextensionastheimagename.Youcanchangetheimagenamewithoutaffectingthenameofthefile.
TheimagefileisrepresentedbytheImageFilepropertyontheRasterobject.ChangingtheImageFilepropertywillchangetheimageinthedrawing.TheimagenameisrepresentedbytheNameproperty,andchangingtheNamepropertywillchangethenameoftheimageonly,notthefileassociatedwithit.
Pleasesendusyourcommentaboutthispage
<$nopage>bitonalimages.
AdvancedDrawingandOrganizationalTechniques>WorkwithRasterImages>
ModifyImagesandImageBoundaries
Allimageshaveanimageboundary.Whenyouattachanimagetoadrawing,theimageboundaryinheritsthecurrentpropertysettings,includingcolor,layer,linetype,andlinetypescale.Iftheimageisabitonalimage,theimagecolorandboundarycolorarethesame.
AswithotherAutoCADobjects,youcanmodifyimagesandtheirboundaryproperties.Forexample,youcan:
Displayorhidetheimageboundary
Modifytheimagelayer,boundarycolor,andlinetype
Changetheimagelocation
Scale,rotate,andchangethewidthandheightoftheimage
Toggletheimagevisibility
Changetheimagetransparency
Changetheimagebrightness,contrast,andfade
Changethequalityandspeedofimagedisplay
Topicsinthissection
ShowandHideImageBoundariesChangeImageLayer,BoundaryColor,andBoundaryLinetypeChangeImageScale,Rotation,Location,Width,andHeightChangeImageVisibility
ModifyBitonalImageColorandTransparencyAdjustImageBrightness,Contrast,andFade
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>WorkwithRasterImages>ModifyImagesandImageBoundaries>
ShowandHideImageBoundaries
Hidinganimageboundaryensuresthattheimagecannotaccidentallybemovedormodifiedandpreventstheboundaryfrombeingplottedordisplayed.Whenimageboundariesarehidden,clippedimagesarestilldisplayedtotheirspecifiedboundarylimits;onlytheboundaryisaffected.Showingandhidingimageboundariesaffectsallimagesattachedtoyourdrawing.
Toshoworhidetheimageboundaries,usetheClippingEnabledproperty.
Note Thispropertyaffectsonlytheimageboundary.Toseeachangeintheimagewhentogglingthisproperty,lookcloselyatthesmallboundarysurroundingtheimage.
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>WorkwithRasterImages>ModifyImagesandImageBoundaries>
ChangeImageLayer,BoundaryColor,andBoundaryLinetype
Youcanchangethecolorandlinetypeofimageboundariesandthelayerofanimageusingthefollowingproperties
Layer
Specifiesthelayerfortheimage
Color
Specifiesthecoloroftheimageboundary
Linetype
Specifiesthelinetypeoftheimage
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>WorkwithRasterImages>ModifyImagesandImageBoundaries>
ChangeImageScale,Rotation,Location,Width,andHeight
Youcanchangethescale,rotation,location,width,andheightofanimageusingthefollowingmethodsandproperties:
ScaleEntity
Scalestheimage
Rotate
Rotatestheimage
Origin
Specifiestheimagelocation
Width
Specifiesthewidthoftheimageinpixels
Height
Specifiestheheightoftheimageinpixels
ImageWidth
Specifiesthewidthoftheimageindatabaseunits
ImageHeight
Specifiestheheightoftheimageindatabaseunits
ShowRotation
Determinesiftherasterisdisplayedasrotated
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>WorkwithRasterImages>ModifyImagesandImageBoundaries>
ChangeImageVisibility
Imagevisibilityaffectstheredrawspeedbyhidingimagesinthecurrentdrawingsession.Hiddenimagesarenotdisplayedorplotted;onlythedrawingboundaryisdisplayed.Tohideimages,settheImageVisibilitypropertytoFALSE.Toredisplaytheimages,settheImageVisibilitypropertytoTRUE.
Pleasesendusyourcommentaboutthispage
<$nopage>bitonalimages.
AdvancedDrawingandOrganizationalTechniques>WorkwithRasterImages>ModifyImagesandImageBoundaries>
ModifyBitonalImageColorandTransparency
Bitonalrasterimagesareimagesconsistingonlyofaforegroundcolorandabackgroundcolor.Whenyouattachabitonalimage,theforegroundpixelsintheimageinheritthecurrentlayersettingsforcolor.Inadditiontothemodificationsyoucanmaketoanyattachedimage,youcanmodifybitonalimagesbychangingtheforegroundcolorandbyturningthetransparencyofthebackgroundonandoff.
Note Bitonalimagesandbitonalimageboundariesarealwaysthesamecolor.
Tochangetheforegroundcolorofabitonalimage,usetheColorproperty.Toturnthetransparencyonandoff,usetheTransparencyproperty.
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>WorkwithRasterImages>ModifyImagesandImageBoundaries>
AdjustImageBrightness,Contrast,andFade
Youcanadjustimagebrightness,contrast,andfadeinAutoCADtothedisplayoftheimageandtoplottedoutputwithoutaffectingtheoriginalrasterimagefile.
Usethefollowingpropertiestoadjustbrightness,contrast,andfade:
Brightness
Specifiesthebrightnesslevelofanimage
Contrast
Specifiesthecontrastlevelofanimage
Fade
Specifiesthefadelevelofanimage
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>WorkwithRasterImages>
ClipImages
Youcandefinearegionofanimagefordisplayandplottingbyclippingtheimage.Theclippingboundarymustbea2Dpolygonorrectanglewithverticesconstrainedtoliewithintheboundariesoftheimage.Multipleinstancesofthesameimagecanhavedifferentboundaries
Toclipanimage
1. TurnontheimageboundariesusingtheClippingEnabledproperty
2. SpecifytheclippingboundaryandperformtheclipusingtheClipBoundarymethod.Thismethodtakesonevalueasinput:avariantarrayof2Dworldcoordinatesystemcoordinatesspecifyingtheclippingboundaryofarasterimage.
Topicsinthissection
ChangetheClippingBoundaryShowandHidetheClippingBoundary
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>WorkwithRasterImages>ClipImages>
ChangetheClippingBoundary
Tochangeanexistingclippingboundary,simplyrepeattheprevioussteps.Theoldboundarywillbedeletedandthenewboundarywillreplacetheoldone.
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>WorkwithRasterImages>ClipImages>
ShowandHidetheClippingBoundary
Youcandisplayaclippedimageusingtheclippingboundary,oryoucanhidetheclippingboundaryanddisplaytheoriginalimageboundaries.Tohideaclippingboundaryanddisplaytheoriginalimage,settheClippingEnabledpropertytoFALSE.Todisplaytheclippedimage,settheClippingEnabledpropertytoTRUE.
Topicsinthissection
Cliparasterimageboundary
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>WorkwithRasterImages>ClipImages>ShowandHidetheClippingBoundary>
Cliparasterimageboundary
Thisexampleaddsarasterimageinmodelspace.Itthenclipstheimagebasedonaclipboundary.Thisexampleusesthedowntown.jpgfilefoundinthesampledirectory.Ifyoudonothavethisimage,orifitislocatedinadifferentdirectory,insertavalidpathandfilenamefortheimageNamevariable.
SubCh10_ClippingRasterBoundary()
DiminsertionPoint(0To2)AsDouble
DimscalefactorAsDouble
DimrotationAngleAsDouble
DimimageNameAsString
DimrasterObjAsAcadRasterImage
imageName="C:\AutoCAD\sample\downtown.jpg"
insertionPoint(0)=5
insertionPoint(1)=5
insertionPoint(2)=0
scalefactor=2
rotationAngle=0
OnErrorGoToERRORHANDLER
'Createsarasterimageinmodelspace
SetrasterObj=ThisDrawing.ModelSpace.AddRaster_
(imageName,insertionPoint,_
scalefactor,rotationAngle)
ZoomAll
'Establishtheclipboundarywithanarrayofpoints
DimclipPoints(0To9)AsDouble
clipPoints(0)=6:clipPoints(1)=6.75
clipPoints(2)=7:clipPoints(3)=6
clipPoints(4)=6:clipPoints(5)=5
clipPoints(6)=5:clipPoints(7)=6
clipPoints(8)=6:clipPoints(9)=6.75
'Cliptheimage
rasterObj.ClipBoundaryclipPoints
'Enablethedisplayoftheclip
rasterObj.ClippingEnabled=True
ThisDrawing.RegenacActiveViewport
ExitSub
ERRORHANDLER:
MsgBoxErr.Description
EndSub
Pleasesendusyourcommentaboutthispage
<$nopage>blockreferences:<$nopage>BlockReferenceobject:
AdvancedDrawingandOrganizationalTechniques>
UseBlocksandAttributes
AutoCADprovidesseveralfeaturestohelpyoumanageobjectsinyourdrawings.Withblocksyoucanorganizeandmanipulatemanyobjectsasonecomponent.Attributesassociateitemsofinformationwiththeblocksinyourdrawings—forexample,partnumbersandprices.
UsingAutoCADexternalreferences,orxrefs,youcanattachoroverlayentiredrawingstoyourcurrentdrawing.Whenyouopenyourcurrentdrawing,anychangesmadeinthereferenceddrawingappearinthecurrentdrawing.
Topicsinthissection
WorkwithBlocksWorkwithAttributes
Pleasesendusyourcommentaboutthispage
<$nopage>blockreferences:<$nopage>BlockReferenceobject:
AdvancedDrawingandOrganizationalTechniques>UseBlocksandAttributes>
WorkwithBlocks
Ablockisacollectionofobjectsyoucanassociatetogethertoformasingleobject,orablockreference.Youcaninsert,scale,androtateablockreferenceinadrawing.Youcanexplodeablockreferenceintoitscomponentobjects,modifythem,andredefinetheblock.AutoCADupdatesallfutureinstancesofthatblockreferencebasedonthedefinitionoftheblock.
Blockscanbedefinedfromobjectsoriginallydrawnondifferentlayerswithdifferentcolorsandlinetypes.Youcanpreservethelayer,color,andlinetypeinformationofobjectsinablock.Then,eachtimeyouinserttheblock,youhaveeachobjectwithintheblockdrawnonitsoriginallayerwithitsoriginalcolorandlinetype.
Formoreinformationaboutworkingwithblocks,see“CreateandInsertSymbols(Blocks)”intheUser'sGuide.
Topicsinthissection
DefineBlocksInsertBlocksExplodeaBlockReferenceRedefineaBlock
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>UseBlocksandAttributes>WorkwithBlocks>
DefineBlocks
Tocreateanewblock,usetheAddmethod.Thismethodrequirestwovaluesasinput:thelocationinthedrawingwheretheblockisaddedandthenameoftheblocktocreate.
Oncecreated,youcanaddanygeometricalobject,oranotherblock,tothenewlycreatedblock.Youcantheninsertaninstanceoftheblockintothedrawing.Aninsertedblockisanobjectcalledablockreference.
YoucanalsocreateablockbyusingtheWBlockmethodtogroupobjectsinaseparatedrawingfile.Thedrawingfilecanthenbeusedasablockdefinitionforotherdrawings.AutoCADconsidersanydrawingyouinsertintoanotherdrawingtobeablock.
Formoreinformationondefiningblocks,see“CreateBlocks”intheUser'sGuide.
Pleasesendusyourcommentaboutthispage
<$nopage>blockreferences:
AdvancedDrawingandOrganizationalTechniques>UseBlocksandAttributes>WorkwithBlocks>
InsertBlocks
YoucaninsertblocksorentiredrawingsintothecurrentdrawingwiththeInsertBlockmethod.TheInsertBlockmethodtakessixvaluesasinput:theinsertionpoint,thenameoftheblockordrawingtoinsert,theX-scalefactor,theY-scalefactor,theZ-scalefactor,andtherotationangle.
Whenyouinsertanentiredrawingintoanotherdrawing,AutoCADtreatstheinserteddrawinglikeanyotherblockreference.Subsequentinsertionsreferencetheblockdefinition(whichcontainsthegeometricdescriptionoftheblock)withdifferentposition,scale,androtationsettings.Ifyouchangetheoriginaldrawingafterinsertingit,thechangeshavenoeffectontheinsertedblock.Ifyouwanttheinsertedblocktoreflectthechangesyoumadetotheoriginaldrawing,youcanredefinetheblockbyreinsertingtheoriginaldrawing.ThiscanbedonewiththeInsertBlockmethod.
Ifyouinsertadrawingasablock,thefilenameisautomaticallyusedasthenameoftheblock.YoucanchangethenameoftheblockbyusingtheNamepropertyoncetheblockhasbeencreated.
Bydefault,AutoCADusesthecoordinate(0,0,0)asthebasepointforinserteddrawings.YoucanchangethebasepointofadrawingbyopeningtheoriginaldrawingandusingtheSetVariablemethodtospecifyadifferentinsertionbasepointfortheINSBASEsystemvariable.AutoCADusesthenewbasepointthenexttimeyouinsertthedrawing.
IfthedrawingyouinsertcontainsPaperSpaceobjects,thoseobjectsarenotincludedinthecurrentdrawing'sblockdefinition.TousethePaperSpaceobjectsinanotherdrawing,opentheoriginaldrawingandusetheAddmethodtodefinethePaperSpaceobjectsasablock.Youcaninsertthedrawingintoanotherdrawingineitherpaperspaceormodelspace.
Ablockreferencecannotbeiteratedtofindtheoriginalobjectsthatcomposeit.However,youcaniteratetheoriginalblockdefinition,oryoucanexplodetheblockreferenceintoitsoriginalcomponents.
YoucanalsoinsertanarrayofblocksusingtheAddMInsertBlockmethod.Thismethoddoesnotinsertasingleblockintoyourdrawing,astheInsertBlockdoes,butinsteadinsertsanarrayofthespecifiedblock.ThismethodreturnsanMInsertBlockobject.
Formoreinformationoninsertingblocks,see“InsertBlocks”intheUser'sGuide.
Defineablockandinserttheblockintoadrawing
Thisexampledefinesablockandaddsacircletotheblockdefinition.Ittheninsertstheblockintothedrawingasablockreference.
SubCh10_InsertingABlock()
'Definetheblock
DimblockObjAsAcadBlock
DiminsertionPnt(0To2)AsDouble
insertionPnt(0)=0
insertionPnt(1)=0
insertionPnt(2)=0
SetblockObj=ThisDrawing.Blocks.Add_
(insertionPnt,"CircleBlock")
'Addacircletotheblock
DimcircleObjAsAcadCircle
Dimcenter(0To2)AsDouble
DimradiusAsDouble
center(0)=0
center(1)=0
center(2)=0
radius=1
SetcircleObj=blockObj.AddCircle(center,radius)
'Inserttheblock
DimblockRefObjAsAcadBlockReference
insertionPnt(0)=2
insertionPnt(1)=2
insertionPnt(2)=0
SetblockRefObj=ThisDrawing.ModelSpace.InsertBlock_
(insertionPnt,"CircleBlock",1#,1#,1#,0)
ZoomAll
MsgBox"Thecirclebelongsto"&blockRefObj.ObjectName
EndSub
Note Afterinsertion,theexternalfile'sWCSisalignedparalleltotheXYplaneofthecurrentusercoordinatesystem(UCS)inthecurrentdrawing.Thus,ablockfromanexternalfileisinsertedatanyorientationinspacebysettingtheUCSbeforeinsertingit.
Pleasesendusyourcommentaboutthispage
<$nopage>BlockReferenceobject:
AdvancedDrawingandOrganizationalTechniques>UseBlocksandAttributes>WorkwithBlocks>
ExplodeaBlockReference
UsetheExplodemethodtobreakablockreference.Byexplodingablockref-erence,youcanmodifytheblockoraddtoordeletetheobjectsthatdefineit.
Displaytheresultsofanexplodedblockreference
Thisexamplecreatesablockandaddsacircletothedefinitionoftheblock.Theblockistheninsertedintothedrawingasablockreference.Theblockreferenceisthenexploded,andtheobjectsresultingfromtheexplodeprocessaredisplayedalongwiththeirobjecttypes.
SubCh10_ExplodingABlock()
'Definetheblock
DimblockObjAsAcadBlock
DiminsertionPnt(0To2)AsDouble
insertionPnt(0)=0
insertionPnt(1)=0
insertionPnt(2)=0
SetblockObj=ThisDrawing.Blocks.Add_
(insertionPnt,"CircleBlock")
'Addacircletotheblock
DimcircleObjAsAcadCircle
Dimcenter(0To2)AsDouble
DimradiusAsDouble
center(0)=0
center(1)=0
center(2)=0
radius=1
SetcircleObj=blockObj.AddCircle(center,radius)
'Inserttheblock
DimblockRefObjAsAcadBlockReference
insertionPnt(0)=2
insertionPnt(1)=2
insertionPnt(2)=0
SetblockRefObj=ThisDrawing.ModelSpace.InsertBlock_
(insertionPnt,"CircleBlock",1#,1#,1#,0)
ZoomAll
MsgBox"Thecirclebelongsto"&blockRefObj.ObjectName
'Explodetheblockreference
DimexplodedObjectsAsVariant
explodedObjects=blockRefObj.Explode
'Loopthroughtheexplodedobjects
DimIAsInteger
ForI=0ToUBound(explodedObjects)
explodedObjects(I).Color=acRed
explodedObjects(I).Update
MsgBox"ExplodedObject"&I&":"_
&explodedObjects(I).ObjectName
explodedObjects(I).Color=acByLayer
explodedObjects(I).Update
Next
EndSub
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>UseBlocksandAttributes>WorkwithBlocks>
RedefineaBlock
UseanyoftheBlockobjectmethodsandpropertiestoredefineablock.Whenyouredefineablock,allthereferencestothatblockinthedrawingareimmediatelyupdatedtoreflectthenewdefinition.
Redefinitionaffectspreviousandfutureinsertionsofablock.Constantattributesarelostandreplacedbyanynewconstantattributes.Variableattributesremainunchanged,evenifthenewblockhasnoattributes.
Redefinetheobjectsinablockdefinition
Thisexamplecreatesablockandaddsacircletothedefinitionoftheblock.Theblockistheninsertedintothedrawingasablockreference.Thecircleintheblockdefinitionisupdated,andtheblockreferenceisupdatedautomatically.
SubCh10_RedefiningABlock()
'Definetheblock
DimblockObjAsAcadBlock
DiminsertionPnt(0To2)AsDouble
insertionPnt(0)=0
insertionPnt(1)=0
insertionPnt(2)=0
SetblockObj=ThisDrawing.Blocks.Add_
(insertionPnt,"CircleBlock")
'Addacircletotheblock
DimcircleObjAsAcadCircle
Dimcenter(0To2)AsDouble
DimradiusAsDouble
center(0)=0
center(1)=0
center(2)=0
radius=1
SetcircleObj=blockObj.AddCircle(center,radius)
'Inserttheblock
DimblockRefObjAsAcadBlockReference
insertionPnt(0)=2
insertionPnt(1)=2
insertionPnt(2)=0
SetblockRefObj=ThisDrawing.ModelSpace.InsertBlock_
(insertionPnt,"CircleBlock",1#,1#,1#,0)
ZoomAll
'Redefinethecircleintheblock,
'andupdatetheblockreference
circleObj.radius=3
blockRefObj.Update
EndSub
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>UseBlocksandAttributes>
WorkwithAttributes
Anattributereferenceprovidesaninteractivelabelortagforyoutoattachtexttoablock.Examplesofdataarepartnumbers,prices,comments,andowners'names.
Youcanextractattributereferenceinformationfromadrawingandusethatinformationinaspreadsheetordatabasetoproduceitemssuchasapartslistorbillofmaterials(BOM).Youcanassociatemorethanoneattributereferencewithablock,providedthateachattributereferencehasadifferenttag.Youcanalsodefineconstantattributes.Becausetheyhavethesamevalueineveryoccurrenceoftheblock,AutoCADdoesnotpromptforavaluewhenyouinserttheblock.
Attributescanbeinvisible,whichmeanstheattributereferenceisnotdisplayedorplotted.However,informationontheattributereferenceisstoredinthedrawingfile.
Formoreinformationaboutworkingwithattributes,see“OverviewofBlockAttributes”intheUser'sGuide.
Topicsinthissection
CreateAttributeDefinitionsandAttributeReferencesEditAttributeDefinitionsExtractAttributeInformation
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>UseBlocksandAttributes>WorkwithAttributes>
CreateAttributeDefinitionsandAttributeReferences
Tocreateanattributereference,firstyoumustcreateanattributedefinitiononablockbyusingtheAddAttributemethod.Thismethodrequiressixvaluesasinput:theheightoftheattributetext,theAttributemode,apromptstring,theinsertionpoint,thetagstring,andthedefaultattributevalue.
Themodevalueisoptional.TherearefiveconstantsyoucanentertospecifytheAttributemode:
acAttributeModeNormal
Specifiesthatthecurrentmodeofeachattributeismaintained.
acAttributeModeInvisible
Specifiesthatattributevalueswon'tappearwhenyouinserttheblock.TheATTDISPcommandoverridestheInvisiblemode.
acAttributeModeConstant
Givesattributesafixedvalueforblockinsertions.
acAttributeModeVerify
Promptsyoutoverifythattheattributevalueiscorrectwhenyouinserttheblock.
acAttributeModePreset
Setstheattributetoitsdefaultvaluewhenyouinsertablockcontainingapresentattribute.Thevaluecannotbeeditedinthismode.
Youcanenternone,anycombination,oralloftheoptions.Tospecifyacombinationofoptions,addtheconstantstogether.Forexample,youcanenteracAttributeModeInvisible+acAttributeModeConstant.
Thepromptstringappearswhenablockcontainingtheattributeisinserted.ThedefaultforthisstringistheTagstring.InputacAttributeModeConstantforthemodetodisabletheprompt.
Thetagstringidentifieseachoccurrenceoftheattribute.Youcanuseanycharactersexceptspacesorexclamationpoints.AutoCADchangeslowercaseletterstouppercase.
Oncetheattributedefinitionisdefinedinablock,wheneveryouinserttheblockusingtheInsertBlockmethodyoucanspecifyadifferentvaluefortheattributereference.
Anattributedefinitionisassociatedtotheblockuponwhichitiscreated.Attributedefinitionscreatedonmodelspaceorpaperspacearenotconsideredattachedtoanygivenblock.
Defineanattributedefinition
Thisexamplecreatesablockandthenaddsanattributetotheblock.Theblockistheninsertedintothedrawing.
SubCh10_CreatingAnAttribute()
'Definetheblock
DimblockObjAsAcadBlock
DiminsertionPnt(0To2)AsDouble
insertionPnt(0)=0
insertionPnt(1)=0
insertionPnt(2)=0
SetblockObj=ThisDrawing.Blocks.Add_
(insertionPnt,"BlockWithAttribute")
'Addanattributetotheblock
DimattributeObjAsAcadAttribute
DimheightAsDouble
DimmodeAsLong
DimpromptAsString
DiminsertionPoint(0To2)AsDouble
DimtagAsString
DimvalueAsString
height=1
mode=acAttributeModeVerify
prompt="NewPrompt"
insertionPoint(0)=5
insertionPoint(1)=5
insertionPoint(2)=0
tag="NewTag"
value="NewValue"
SetattributeObj=blockObj.AddAttribute(height,mode,_
prompt,insertionPoint,tag,value)
'Inserttheblock,creatingablockreference
'andanattributereference
DimblockRefObjAsAcadBlockReference
insertionPnt(0)=2
insertionPnt(1)=2
insertionPnt(2)=0
SetblockRefObj=ThisDrawing.ModelSpace.InsertBlock_
(insertionPnt,"BlockWithAttribute",1#,1#,1#,0)
EndSub
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>UseBlocksandAttributes>WorkwithAttributes>
EditAttributeDefinitions
YoucanusetheAttributeobjectpropertiesandmethodstoedittheattribute.Someofthepropertiesonanattributeincludethefollowing:
Alignment
Specifiesthehorizontalandverticalalignmentoftheattribute
Backward
Specifiesthedirectionofattributetext
FieldLength
Specifiesthefieldlengthoftheattribute
Height
Specifiestheheightoftheattribute
InsertionPoint
Specifiestheinsertionpointoftheattribute
Mode
Specifiesthemodeoftheattribute
PromptString
Specifiesthepromptstringoftheattribute
Rotation
Specifiestherotationoftheattribute
ScaleFactor
Specifiesthescalefactoroftheattribute
TagString
Specifiesthetagstringoftheattribute
Someofthemethodsyoucanusetoedittheattributeincludethefollowing:
ArrayPolar
Createsapolararray
ArrayRectangular
Createsarectangulararray
Copy
Copiestheattribute
Erase
Erasestheattribute
Mirror
Mirrorstheattribute
Move
Movestheattribute
Rotate
Rotatestheattribute
ScaleEntity
Scalestheattribute
Redefineanattributedefinition
Thisexamplecreatesablockandthenaddsanattributetotheblock.Theblockistheninsertedintothedrawing.Theattributetextisthenupdatedtobedisplayedbackward.
SubCh10_RedefiningAnAttribute()
'Definetheblock
DimblockObjAsAcadBlock
DiminsertionPnt(0To2)AsDouble
insertionPnt(0)=0
insertionPnt(1)=0
insertionPnt(2)=0
SetblockObj=ThisDrawing.Blocks.Add_
(insertionPnt,"BlockWithAttribute")
'Addanattributetotheblock
DimattributeObjAsAcadAttribute
DimheightAsDouble
DimmodeAsLong
DimpromptAsString
DiminsertionPoint(0To2)AsDouble
DimtagAsString
DimvalueAsString
height=1
mode=acAttributeModeVerify
prompt="NewPrompt"
insertionPoint(0)=5
insertionPoint(1)=5
insertionPoint(2)=0
tag="NewTag"
value="NewValue"
SetattributeObj=blockObj.AddAttribute(height,mode,_
prompt,insertionPoint,tag,value)
'Inserttheblock,creatingablockreference
'andanattributereference
DimblockRefObjAsAcadBlockReference
insertionPnt(0)=2
insertionPnt(1)=2
insertionPnt(2)=0
SetblockRefObj=ThisDrawing.ModelSpace.InsertBlock_
(insertionPnt,"BlockWithAttribute",1#,1#,1#,0)
'Redefinetheattributetexttodisplaybackwards.
attributeObj.Backward=True
attributeObj.Update
EndSub
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>UseBlocksandAttributes>WorkwithAttributes>
ExtractAttributeInformation
YoucanextractattributeinformationfromadrawingusingtheGetAttributesandGetConstantAttributesmethods.TheGetAttributesmethodreturnsanarrayoftheattributereferencesattachedtoablock,alongwiththeircurrentvalues.TheGetConstantAttributesmethodreturnsanarrayofconstantattributesattachedtotheblockorexternalreference.Theattributesreturnedbythismethodaretheconstantattributedefinitions,notattributereferences.
Youdonotneedtemplatefilestoextractattributeinformation,andnoattributeinformationfilesarecreated.Simplyiteratethearrayofattributereferences,usingtheTagStringandTextStringpropertiesoftheattribute-referencetoexaminetheattributeinformation.
TheTagStringpropertyrepresentstheindividualtagfortheattributereference.TheTextStringpropertycontainsthevaluefortheattributereference.
Formoreinformationonextractingattributeinformation,see“ExtractDatafromBlockAttributes”intheUser'sGuide.
Getattributereferenceinformation
Thisexamplecreatesablockandthenaddsanattributetotheblock.Theblockistheninsertedintothedrawing.Theattributedataisthenreturnedanddisplayedusingamessagebox.Theattributedataisthenupdatedfortheblockreference,andonceagaintheattributedataisreturnedanddisplayed.
SubCh10_GettingAttributes()
'Createtheblock
DimblockObjAsAcadBlock
DiminsertionPnt(0To2)AsDouble
insertionPnt(0)=0
insertionPnt(1)=0
insertionPnt(2)=0
SetblockObj=ThisDrawing.Blocks.Add_
(insertionPnt,"TESTBLOCK")
'Definetheattributedefinition
DimattributeObjAsAcadAttribute
DimheightAsDouble
DimmodeAsLong
DimpromptAsString
DiminsertionPoint(0To2)AsDouble
DimtagAsString
DimvalueAsString
height=1#
mode=acAttributeModeVerify
prompt="AttributePrompt"
insertionPoint(0)=5
insertionPoint(1)=5
insertionPoint(2)=0
tag="AttributeTag"
value="AttributeValue"
'Createtheattributedefinitionobjectontheblock
SetattributeObj=blockObj.AddAttribute_
(height,mode,prompt,_
insertionPoint,tag,value)
'Inserttheblock
DimblockRefObjAsAcadBlockReference
insertionPnt(0)=2
insertionPnt(1)=2
insertionPnt(2)=0
SetblockRefObj=ThisDrawing.ModelSpace.InsertBlock_
(insertionPnt,"TESTBLOCK",1,1,1,0)
ZoomAll
'Gettheattributesfortheblockreference
DimvarAttributesAsVariant
varAttributes=blockRefObj.GetAttributes
'Movetheattributetagsandvaluesintoa
'stringtobedisplayedinaMsgbox
DimstrAttributesAsString
strAttributes=""
DimIAsInteger
ForI=LBound(varAttributes)ToUBound(varAttributes)
strAttributes=strAttributes+"Tag:"+_
varAttributes(I).TagString+vbCrLf+_
"Value:"+varAttributes(I).textString
Next
MsgBox"TheattributesforblockReference"+_
blockRefObj.Name&"are:"&vbCrLf_
&strAttributes
'Changethevalueoftheattribute
'Note:ThereisnoSetAttributes.Onceyouhavethe
'variantarray,youhavetheobjects.
'Changingthemchangestheobjectsinthedrawing.
varAttributes(0).textString="NEWVALUE!"
'Gettheattributesagain
DimnewvarAttributesAsVariant
newvarAttributes=blockRefObj.GetAttributes
'Again,displaythetagsandvalues
strAttributes=""
ForI=LBound(varAttributes)ToUBound(varAttributes)
strAttributes=strAttributes+"Tag:"+_
newvarAttributes(I).TagString+vbCrLf+_
"Value:"+newvarAttributes(I).textString
Next
MsgBox"TheattributesforblockReference"&_
blockRefObj.Name&"are:"&vbCrLf_
&strAttributes
EndSub
Pleasesendusyourcommentaboutthispage
<$nopage>xrefs.
AdvancedDrawingandOrganizationalTechniques>
UseExternalReferences
Anexternalreference(xref)linksanotherdrawingtothecurrentdrawing.Whenyouinsertadrawingasablock,theblockandalloftheassociatedgeometryisstoredinthecurrentdrawingdatabase.Itisnotupdatediftheoriginaldrawingchanges.Whenyouinsertadrawingasanxref,however,thexrefisupdatedwhentheoriginaldrawingchanges.Adrawingthatcontainsxrefs,therefore,alwaysreflectsthemostcurrenteditingofeachexternallyreferencedfile.
Likeablockreference,anxrefisdisplayedinthecurrentdrawingasasingleobject.However,anxrefdoesnotsignificantlyincreasethefilesizeofthecurrentdrawingandcannotbeexploded.Aswithblocks,youcannestxrefsthatareattachedtoyourdrawing.
Formoreinformationaboutxrefs,see“Attach,Update,andBindExternalReferences”intheUser'sGuide.
Topicsinthissection
UpdateXrefsAttachXrefsDetachXrefsReloadXrefsUnloadXrefsBindXrefsClipBlocksandXrefsDemandLoadingandXrefPerformance
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>UseExternalReferences>
UpdateXrefs
Whenyouopenorplotyourdrawing,AutoCADreloadseachxreftoreflectthelateststateofthereferenceddrawing.Afteryoumakechangestoanexternallyreferenceddrawingandsavethefile,otheruserscanaccessyourchangesimmediatelybyreloadingthexref.
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>UseExternalReferences>
AttachXrefs
Attachinganxreflinksonedrawing(thereferencefile,orxref)tothecurrentdrawing.Whenadrawingreferencesanxref,AutoCADattachesonlythexrefdefinitiontothedrawing,unlikeregularblocks,wheretheblockdefinitionandthecontentsoftheblockarestoredwiththecurrentdrawing.AutoCADreadsthereferencedrawingtodeterminewhattodisplayinthecurrentdrawing.Ifthereferencefileismissingorcorrupt,itsdataisnotdisplayedinthecurrentdrawing.Eachtimeyouopenadrawing,AutoCADloadsallgraphicalandnongraphical(suchaslayers,linetypes,andtextstyles)objectsfromreferencedfiles.IfVISRETAINison,AutoCADstoresanyupdatedxref-dependentlayerinformationinthecurrentdrawing.
Youcanattachasmanycopiesofanxrefasyouwant,andeachcanhaveadifferentposition,scale,androtation.Youcanalsocontrolthedependentlayersandlinetypepropertiesthataredefinedinthexref.
Toattachanxref,usetheAttachExternalReferencemethod.Thismethodrequiresyoutoinputthepathandfilenameofthedrawingtobereferenced,thenamethexrefistouseinthecurrentdrawing,theinsertionpoint,thescale,androtationinformationforthexref.TheAttachExternalReferencemethodreturnsthenewlycreatedExternalReferenceobject.
Formoreinformationonattachingxrefs,see“AttachExternalReferences”intheUser'sGuide.
Attachanexternalreferencetoadrawing
Thisexampledisplaysalltheblocksinthecurrentdrawingbeforeandafteraddinganexternalreference.Thisexampleusesthe3DHouse.dwgfilefoundinthesampledirectory.Ifyoudonothavethisimage,orifitislocatedinadifferentdirectory,insertavalidpathandfilenameforthePathNamevariable.
SubCh10_AttachingExternalReference()
OnErrorGoToERRORHANDLER
DimInsertPoint(0To2)AsDouble
DiminsertedBlockAsAcadExternalReference
DimtempBlockAsAcadBlock
DimmsgAsString,PathNameAsString
'Defineexternalreferencetobeinserted
InsertPoint(0)=1
InsertPoint(1)=1
InsertPoint(2)=0
PathName="C:/ProgramFiles/AutoCAD2009/sample/3DHouse.dwg"
'DisplaycurrentBlockinformationforthisdrawing
GoSubListBlocks
'Addtheexternalreferencetothedrawing
SetinsertedBlock=ThisDrawing.ModelSpace._
AttachExternalReference(PathName,"XREF_IMAGE",_
InsertPoint,1,1,1,0,False)
ZoomAll
'DisplaynewBlockinformationforthisdrawing
GoSubListBlocks
ExitSub
ListBlocks:
msg=vbCrLf'Resetmessage
ForEachtempBlockInThisDrawing.Blocks
msg=msg&tempBlock.Name&vbCrLf
Next
MsgBox"Thecurrentblocksinthisdrawingare:"&msg
Return
ERRORHANDLER:
MsgBoxErr.Description
EndSub
Topicsinthissection
OverlayXrefs
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>UseExternalReferences>AttachXrefs>
OverlayXrefs
Overlayingissimilartoattaching,exceptwhenadrawingisattachedoroverlaid.Anyotheroverlaysnestedinitareignoredand,therefore,notdisplayed.Inotherwords,nestedoverlaysarenotreadin.
Tooverlayanxref,settheOverlayparameteroftheAttachExternalReferencemethodtoTRUE.
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>UseExternalReferences>
DetachXrefs
Youcandetachanxrefdefinitiontoremovethexrefscompletelyfromyourdrawing.Youcanalsoerasetheindividualxrefinstances.Detachingthexrefdefinitionremovesalldependentsymbolsassociatedwiththatxref.Ifalltheinstancesofanxrefareerasedfromthedrawing,AutoCADremovesthexrefdefinitionthenexttimethedrawingisopened.
Todetachanxref,usetheDetachmethod.Youcannotdetachanestedxref.
Detachanxrefdefinition
Thisexampleattachesanexternalreferenceandthendetachestheexternalreference.Thisexampleusesthe3DHouse.dwgfilefoundinthesampledirectory.Ifyoudonothavethisimage,orifitislocatedinadifferentdirectory,insertavalidpathandfilenameforthePathNamevariable.
SubCh10_DetachingExternalReference()
OnErrorGoToERRORHANDLER
'Defineexternalreferencetobeinserted
DimxrefHomeAsAcadBlock
DimxrefInsertedAsAcadExternalReference
DiminsertionPnt(0To2)AsDouble
DimPathNameAsString
insertionPnt(0)=1
insertionPnt(1)=1
insertionPnt(2)=0
PathName="c:/AutoCAD2009/sample/3DHouse.dwg"
'Addtheexternalreference
SetxrefInserted=ThisDrawing.ModelSpace._
AttachExternalReference(PathName,"XREF_IMAGE",_
insertionPnt,1,1,1,0,False)
ZoomAll
MsgBox"Theexternalreferenceisattached."
'Detachtheexternalreferencedefinition
DimnameAsString
name=xrefInserted.name
ThisDrawing.Blocks.Item(name).Detach
MsgBox"Theexternalreferenceisdetached."
ExitSub
ERRORHANDLER:
MsgBoxErr.Description
EndSub
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>UseExternalReferences>
ReloadXrefs
Ifsomeonemodifiesanexternallyreferenceddrawingwhileyouareworkingonthehostdrawingtowhichthatxrefisattached,youcanupdatethatxrefdrawingusingtheReloadmethod.Whenyoureload,theselectedxrefdrawingisupdatedinyourhostdrawing.Also,ifyouhaveunloadedanxref,youcanchoosetoreloadthatexternallyreferenceddrawingatanytime.
Reloadanxrefdefinition
Thisexampleattachesanexternalreferenceandthenreloadstheexternalreference.Thisexampleusesthe3DHouse.dwgfilefoundinthesampledirectory.Ifyoudonothavethisimage,orifitislocatedinadifferentdirectory,insertavalidpathandfilenameforthePathNamevariable.
SubCh10_ReloadingExternalReference()
OnErrorGoToERRORHANDLER
'Defineexternalreferencetobeinserted
DimxrefHomeAsAcadBlock
DimxrefInsertedAsAcadExternalReference
DiminsertionPnt(0To2)AsDouble
DimPathNameAsString
insertionPnt(0)=1
insertionPnt(1)=1
insertionPnt(2)=0
PathName="c:/AutoCAD2009/sample/3DHouse.dwg"
'Addtheexternalreferencetotheblock
SetxrefInserted=ThisDrawing.ModelSpace._
AttachExternalReference(PathName,"XREF_IMAGE",_
insertionPnt,1,1,1,0,False)
ZoomAll
MsgBox"Theexternalreferenceisattached."
'Reloadtheexternalreferencedefinition
ThisDrawing.Blocks.Item(xrefInserted.name).Reload
MsgBox"Theexternalreferenceisreloaded."
ExitSub
ERRORHANDLER:
MsgBoxErr.Description
EndSub
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>UseExternalReferences>
UnloadXrefs
Tounloadanxref,usetheUnloadmethod.Whenyouunloadareferencedfilethatisnotbeingusedinthecurrentdrawing,theAutoCADperformanceisenhancedbynothavingtoreadanddisplayunnecessarydrawinggeometryorsymboltableinformation.Thexrefgeometryandthatofanynestedxrefisnotdisplayedinthecurrentdrawinguntilthexrefisreloaded.
Unloadanxrefdefinition
Thisexampleattachesanexternalreferenceandthenunloadstheexternalreference.Thisexampleusesthe3DHouse.dwgfilefoundinthesampledirectory.Ifyoudonothavethisimage,orifitislocatedinadifferentdirectory,insertavalidpathandfilenameforthePathNamevariable.
SubCh10_UnloadingExternalReference()
OnErrorGoToERRORHANDLER
'Defineexternalreferencetobeinserted
DimxrefHomeAsAcadBlock
DimxrefInsertedAsAcadExternalReference
DiminsertionPnt(0To2)AsDouble
DimPathNameAsString
insertionPnt(0)=1
insertionPnt(1)=1
insertionPnt(2)=0
PathName="c:/AutoCAD2009/sample/3DHouse.dwg"
'Addtheexternalreference
SetxrefInserted=ThisDrawing.ModelSpace._
AttachExternalReference(PathName,"XREF_IMAGE",_
insertionPnt,1,1,1,0,False)
ZoomAll
MsgBox"Theexternalreferenceisattached."
'Unloadtheexternalreferencedefinition
ThisDrawing.Blocks.Item(xrefInserted.name).Unload
MsgBox"Theexternalreferenceisunloaded."
ExitSub
ERRORHANDLER:
MsgBoxErr.Description
EndSub
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>UseExternalReferences>
BindXrefs
BindinganxreftoadrawingusingtheBindmethodmakesthexrefapermanentpartofthedrawingandnolongeranexternallyreferencedfile.Theexternallyreferencedinformationbecomesablock.Whentheexternallyreferenceddrawingisupdated,theboundxrefisnotupdated.Thisprocessbindstheentiredrawing'sdatabase,includingallofitsdependentsymbols.
Dependentsymbolsarenamedobjectssuchasblocks,dimensionstyles,layers,linetypes,andtextstyles.Bindingthexrefallowsnamedobjectsfromthexreftobeusedinthecurrentdrawing.
TheBindmethodrequiresonlyoneparameter:bPrefixName.IfbPrefixNameissettoTRUE,thesymbolnamesofthexrefdrawingareprefixedinthecurrentdrawingwith<blockname>$x$,wherexisanintegerthatisautomaticallyincrementedtoavoidoverridingexistingblockdefinitions.IfthebPrefixNameparameterissettoFALSE,thesymbolnamesofthexrefdrawingaremergedintothecurrentdrawingwithouttheprefix.Ifduplicatenamesexist,AutoCADusesthesymbolsalreadydefinedinthelocaldrawing.Ifyouareunsurewhetheryourdrawingcontainsduplicatesymbolnames,itisrecommendedthatyousetbPrefixNametoTRUE.
Formoreinformationonbindingxrefs,see“ArchiveDrawingsThatContainExternalReferences(Bind)”intheUser'sGuide.
Bindanxrefdefinition
Thisexampleattachesanexternalreferenceandthenbindstheexternal-referencetothedrawing.Thisexampleusesthe3DHouse.dwgfilefoundinthesampledirectory.Ifyoudonothavethisimage,orifitislocatedinadifferentdirectory,insertavalidpathandfilenameforthePathNamevariable.
SubCh10_BindingExternalReference()
OnErrorGoToERRORHANDLER
'Defineexternalreferencetobeinserted
DimxrefHomeAsAcadBlock
DimxrefInsertedAsAcadExternalReference
DiminsertionPnt(0To2)AsDouble
DimPathNameAsString
insertionPnt(0)=1
insertionPnt(1)=1
insertionPnt(2)=0
PathName="c:/AutoCAD2009/sample/3DHouse.dwg"
'Addtheexternalreference
SetxrefInserted=ThisDrawing.ModelSpace._
AttachExternalReference(PathName,"XREF_IMAGE",_
insertionPnt,1,1,1,0,False)
ZoomAll
MsgBox"Theexternalreferenceisattached."
'Bindtheexternalreferencedefinition
ThisDrawing.Blocks.Item(xrefInserted.name).BindFalse
MsgBox"Theexternalreferenceisbound."
ExitSub
ERRORHANDLER:
MsgBoxErr.Description
EndSub
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>UseExternalReferences>
ClipBlocksandXrefs
ThereisnomethodprovidedinActiveXAutomationforclippingtheboundariesofblocksandxrefs.UsetheXCLIPcommandinAutoCAD,orsendtheXCLIPcommandtoAutoCADusingtheSendCommandmethod.
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>UseExternalReferences>
DemandLoadingandXrefPerformance
Throughacombinationofdemandloadingandsavingdrawingswithindexes,youcanincreasetheperformanceofdrawingswithexternalreferences.DemandloadingworksinconjunctionwiththeXLOADCTLandINDEXCTLsystemvariables.Whenyouturnondemandloading,ifindexeshavebeensavedinthereferenceddrawings,AutoCADloadsintomemoryonlythedatafromthereferencedrawingthatisnecessarytoregeneratethecurrentdrawing.Inotherwords,referencedmaterialisreadin“ondemand.”
Torealizethemaximumbenefitsofdemandloading,youneedtosavethereferenceddrawingswithlayerandspatialindexes.Theperformancebenefitsofdemandloadingaremostnoticeablewhenyou
Clipthexreftodisplayasmallfractionofit,andaspatialindexissavedintheexternallyreferenceddrawing.
Freezeseverallayersofthexref,andtheexternallyreferenceddrawingissavedwithalayerindex.
Toturnondemandloading,usetheXRefDemandLoadproperty.IfyouturnondemandloadingwiththeacDemandLoadEnabledWithCopyoption,AutoCADmakesatemporarycopyoftheexternallyreferencedfileanddemandloadsthetemporaryfile.Youcanthendemandloadthexrefwhileallowingtheoriginalreferencedrawingtobeavailableformodification.Whenyoudisabledemandloading,AutoCADreadsintheentirereferencedrawingregardlessoflayervisibilityorclipinstances.
Toturnonlayerandspatialindexes,settheINDEXCTLsystemvariableusingtheSetVariablemethod.ThefollowingsettingsapplytotheINDEXCTLs-ystemvariable:
0=noindexescreated
1=layerindexcreated
2=spatialindexcreated
3=bothspatialandlayerindexescreated
Bydefault,INDEXCTLissetto0whenyoucreateanewAutoCADdrawing.
Formoreinformationondemandloadingandxrefs,see“IncreasePerformancewithLargeXrefs”intheUser'sGuide.
Pleasesendusyourcommentaboutthispage
AdvancedDrawingandOrganizationalTechniques>
AssignandRetrieveExtendedData
Youcanuseextendeddata(xdata)asameansforlinkinginformationwithobjectsinadrawing.
Assignxdatatoallobjectsinaselectionset
Thisexamplepromptstheusertoselectobjectsfromthedrawing.Theselectedobjectsareplacedintoaselectionset,andthespecifiedxdataisattachedtoallobjectsinthatselectionset
SubCh10_AttachXDataToSelectionSetObjects()
'Createtheselectionset
DimssetAsObject
Setsset=ThisDrawing.SelectionSets.Add("SS1")
'Prompttheusertoselectobjects
sset.SelectOnScreen
'Definethexdata
DimappNameAsString,xdataStrAsString
appName="MY_APP"
xdataStr="Thisissomexdata"
DimxdataType(0To1)AsInteger
Dimxdata(0To1)AsVariant
'Definethevaluesforeacharray
'1001indicatestheappName
xdataType(0)=1001
xdata(0)=appName
'1000indicatesastringvalue
xdataType(1)=1000
xdata(1)=xdataStr
'Loopthroughallentitiesintheselection
'setandassignthexdatatoeachentity
DimentAsObject
ForEachentInsset
ent.SetXDataxdataType,xdata
Nextent
EndSub
Viewthexdataofallobjectsinaselectionset
Thisexampledisplaysthexdataattachedwiththepreviousexample.Ifyouattachxdataotherthanstrings(type1000),youwillneedtorevisethiscode
SubCh10_ViewXData()
'Findtheselectioncreatedinpreviousexample
DimssetAsObject
Setsset=ThisDrawing.SelectionSets.Item("SS1")
'Definethexdatavariablestoholdxdatainformation
DimxdataTypeAsVariant
DimxdataAsVariant
DimxdAsVariant
'Defineindexcounter
DimxdiAsInteger
xdi=0
'Loopthroughtheobjectsintheselectionset
'andretrievethexdatafortheobject
DimmsgstrAsString
DimappNameAsString
DimentAsAcadEntity
appName="MY_APP"
ForEachentInsset
msgstr=""
xdi=0
'RetrievetheappNamexdatatypeandvalue
ent.GetXDataappName,xdataType,xdata
'IfthexdataTypevariableisnotinitialized,there
'wasnoappNamexdatatoretrieveforthatentity
IfVarType(xdataType)<>vbEmptyThen
ForEachxdInxdata
msgstr=msgstr&vbCrLf&xdataType(xdi)_
&":"&xd
xdi=xdi+1
Nextxd
EndIf
'IfthemsgstrvariableisNULL,therewasnoxdata
Ifmsgstr=""Thenmsgstr=vbCrLf&"NONE"
MsgBoxappName&"xdataon"&ent.ObjectName&_
":"&vbCrLf&msgstr
Nextent
EndSub
Pleasesendusyourcommentaboutthispage
<$nopage>dialogcontrols.<$nopage>formcontrols.
DevelopApplicationswithVBA
ManyprogrammingtasksinvolvemorethansimplyworkingwiththeAutoCADActiveXobjectmodel.Thischapterprovidesabriefoverviewofcreatingdialogboxes,handlingerrors,controllingwindowfocus,anddistributingyourapplicationtoothers.
Remember,theMicrosoftdocumentationforVBAcontainsmoreinformationonthesetopics.
Topicsinthissection
MoreVBATerminologyFormsinVBAHandleErrorsEncryptVBACodeModulesRunaVBAMacrofromaToolbarorMenuAutomaticallyLoadaVBAProjectAutomaticallyRunaVBAMacroAutomaticallyOpentheVBAIDEWheneveraProjectIsLoadedWorkinaZeroDocumentStateDistributeYourApplication64-bitMigration
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>
MoreVBATerminology
ThischapterexpandsyourexposuretoVBA.ThefollowingtermswillhelpyouunderstandandworkwithintheVBAenvironment.
Project
Asetofformsandmodulesgroupedtogetherinasinglefile.
Module
Agroupof(usuallyrelated)subroutinesandfunctions.
Macro
Apublicsubroutineorfunction.Macrosareexposedtotheuserasanexecutablecomponentofyourproject.
Dialogbox
Ameansbywhichinformationisdisplayedorgatheredduringapplicationexecution.
Form
Containerfordialogboxcontrols.
Pleasesendusyourcommentaboutthispage
<$nopage>dialogcontrols.<$nopage>formcontrols.
DevelopApplicationswithVBA>
FormsinVBA
Formsarethebasicbuildingblocksthroughwhichyoucreateyourowncustomdialogboxesforyourapplication.Throughcustomformsyoucanprovideinformationtousers,getinformationfromusers,orhaveyouruserscontrolactivityintheapplication.
Formsarelikeanartist'scanvas—theystartoutblank.Tofillyourcanvas,youneedapalette.Inthiscase,yourpaletteisthecontroltoolbox.You,astheartist,placeselectedcontrolsfromthetoolboxontotheform.Youcanaddasmanycontrolsasyoulike.Atanytimeyoucanadjustsizeandpropertiesofthecontrolsandeventheformitself.Finally,youaddthefunctionality(code)tothecontrolsthatbringsyourformtolife.
AlthoughVisualBasic6supportsdifferenttypesofforms,VBAsupportsonlytheUserForm.ThismeanssomeformshavebeencreatedandexportedinVisualBasic6thatcannotbeimportedintoVBA.
UserForms—orforms,astheyarecalledinthisguide—canbemodalormodeless.TheShowModalpropertyofaformdetermineswhetheritismodalor
modeless.Modalformsdisplayedinyourrunningapplicationmustbeclosedbeforeuserscanperformanyotheractionintheapplication.Formoreinformationaboutworkingwithmodalforms,seeModalForms.
Tocreateanewforminyourproject
1. OpentheProjectwindowoftheVBAIDEandselecttheprojectyouwanttoaddtheformto.
2. FromtheInsertmenu,chooseUserForm.Ablankformiscreatedandaddedtoyourproject.
Tocreateamodelessforminyourproject
1. OpentheProjectwindowoftheVBAIDEandselecttheprojectyouwanttoaddtheformto.
2. FromtheInsertmenu,chooseUserForm,andchangetheShowModalpropertytoFalse.
3. AddtheAcFocusCtrl(AcFocusCtrl.dll)totheToolbox,anddragthecontrolontotheform.TheAcFocusCtrlkeepsthefocusontheformduringuserinteraction.
Topicsinthissection
DesignandRunModeAddControlstoaFormDisplayandHideFormsLoadandUnloadFormsModalForms
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>FormsinVBA>
DesignandRunMode
WhileyouarebuildingyourformyouareworkinginDesignmode,whereyoucan
Addcontrolstotheform
Changethepropertiesoftheform
Changethepropertiesofcontrolsontheform
Addcodetotheformmodule
WhileinDesignmodethereisnointeractionamongtheuser,theuserinterfaceofAutoCAD®,andyourform.
Onceyourunyourapplication,oryouruserrunsyourapplication,theformistheninRunmode.WhileinRunmodeyoucannotmakeadjustmentstotheformdirectly.However,theformisnowdisplayedintheAutoCADuserinterfaceandtheusercaninteractwiththeformaspartofthenormaloperationofyourapplication.
Pleasesendusyourcommentaboutthispage
<$nopage>dialogcontrols.<$nopage>formcontrols.
DevelopApplicationswithVBA>FormsinVBA>
AddControlstoaForm
Addingcontrolstoaformiseasy.Simplyselectacontrolfromthecontroltoolboxanddragitovertotheform.Whenyoureleaseyourmouse,acopyofthecontrolwillbeplacedontheform.Oncethecontrolisontheform,youcanchangethepositionandsizeofthecontrol.Youcancopyoverasmanycontrolsasyoulike.
Inadditiontothedragmethodpreviouslymentioned,thereareotherwaysofplacingcontrolsonaform.
Topicsinthissection
ChangetheSizeandPlacementofaControlUseFormattingControlsChangethePropertiesofaControlAddCodetoaControl
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>FormsinVBA>AddControlstoaForm>
ChangetheSizeandPlacementofaControl
Tomoveacontrol,simplyselectitanddragittoitsnewpositionontheform.
Toresizeacontrol,firstselectthecontrolbyclickingonitonce.Whenyouselectacontrol,itsborderbecomesvisible.Toresizethecontrol,simplyselectoneofthesizinggripsnowvisibleontheborderanddragthegriptoanewposition.Whenyoureleasethegrip,thecontrolisresizedtothatlocation.(Youcanresizetheforminthesamemanner.)
Tomoveorresizeseveralcontrolsatonce,selecteachcontrolwhileholdingdowntheSHIFTkey.Thiswillhighlightallthecontrols.Youcannowmoveorresizethecontrolsasagroup.
Tosizeacontrolasyouplaceit
1. Selectthedesiredcontrolinthecontroltoolbox.
2. Ontheform,press,drag,andreleasethemousebutton.Theselectedcontrolwillbeplacedontheform.Thesizeofthecontroldependsonhowfaryoudragthemouse.
Toplaceseveralinstancesofthesamecontrol
1. Inthecontroltoolbox,double-clickonthecontrolyouwanttoplace.
2. Ontheform,clickatthelocationyouwantacopyofthecontrolplaced.Movetoanotherlocationontheformandclickagain.Anothercopyofthecontrolwillappear.Youcanaddasmanycopiesofthecontrolasyouneed.
3. Whenyouarefinishedwiththecontrol,returntothecontroltoolboxandclickthecontrolonemoretimetodeselectit.
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>FormsinVBA>AddControlstoaForm>
UseFormattingControls
VBAprovidesseveralformattingcontrolstohelpyoulayoutyourform.ThesecontrolscanbefoundontheFormatmenuoftheVBAIDE.Thesecontrolsallowyoutoaligncontrolstoeachother,maketwoormorecontrolsthesamesize,changethespacingbetweencontrols,andcentercontrolsontheform.
RememberwhenusingtheformattingcontrolsthatseveralcontrolscanbeselectedatoncebyusingSHIFT.
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>FormsinVBA>AddControlstoaForm>
ChangethePropertiesofaControl
Propertiescontrolvariouscharacteristicsofacontrolsuchasitssize,shape,color,label,anddefaultvalues.YoucansetthepropertiesofacontrolindesignmodebyusingthePropertieswindow.
Tochangethepropertyofacontrol
1. Ontheform,selectthedesiredcontrol.
2. OpenthePropertieswindowusingF4ifitisnotalreadyopen.
3. InthePropertieswindow,findthepropertyyouwanttochangeandselectthecurrentvalueforthatproperty.
4. Changethevaluetothenewdesiredvaluefortheproperty.
Youcanalsochangethepropertyofacontrolatruntimebywritingcodetoaccessthatproperty.SeetheMicrosoftdocumentationformoreinformationonchangingthepropertyofacontrolatruntime.
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>FormsinVBA>AddControlstoaForm>
AddCodetoaControl
Nowthatyouhaveyourformlookingthewayyouwant,it'stimetoaddsomecodebehindyourcontrols.ToopentheCodewindowforacontrolsimplydouble-clickonthecontrolintheFormwindow.TheCodewindowwillopen,withasubroutinecreatedforthatcontrolanditsdefaultevent.
Youcanaddcodetothedefaultevent,orchooseadifferenteventfromtheeventdrop-downlistatthetop-rightcorneroftheCodewindow.
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>FormsinVBA>
DisplayandHideForms
Nowyouhaveabeautifullydesignedformwithfullyfunctionalcodebehindallthecontrols.Thelaststepisgettingtheformdisplayedtotheuseratrun-time.DisplayingtheformisaccomplishedthroughtheVBAShowmethod.TheShowmethodcanbecalledfromanycodemoduleinyourapplication.
Theformyoucreatedismodalbydefault,sotheuserwillnotbeabletointeractwithAutoCADdirectlywhiletheformisdisplayed.Forexample,theusercannotselectapointorobjectinthedrawingwiththeformdisplayed.ToallowtheuseraccesstotheAutoCADdrawing,usetheVBAHidemethod.TheHidemethodhidestheformandallowstheuserlimitedaccesstoAutoCAD.WhenusingtheHidemethoditisimportanttorememberthattheformisnotunloadedfrommemory.Itwillretainallcurrentvalueswhilehidden.
TheHidemethodiscalledinthesamemannerastheShowmethod.
Displayaform
Thisexamplewilldisplaytheformnamed“UserForm1”:
PublicSubMyApplication()
UserForm1.Show
EndSub
Thesubroutine(andconsequentlythedisplayofyourform)isnowcallableasamacrofromtheVBARUNcommandorfromanAutoCADmenu.
Hideaform
Thisexamplehidestheformnamed“UserForm1”:
PublicSubMyAppHide()
UserForm1.Hide
EndSub
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>FormsinVBA>
LoadandUnloadForms
Theremaybetimeswhenyouwanttoloadaformintomemoryduringruntime,butnotshowtheform.Youmaychoosetodothistobettercontrolwhentheloadtimeoccursinyourapplication,orwhenyouneedprogrammaticaccesstotheformbutdonotwanttodisplaytheformtotheuser.
Toloadaform,butnotdisplayit,usetheVBALoadmethod.TheShowmethodcanthenbeusedtomaketheformvisibleattheappropriatetimeinyourapplication'sexecution.Remember,theusercan'tinteractwithyourformuntilitisvisible.
IftheShowmethodiscalledandtheformhasnotbeenloaded,itwillbeloadedautomatically.
Theremayalsobetimeswhenyouwillwanttounloadaformspecifically.Unloadingaformremovesthatformfrommemoryandallthememoryassociatedwiththeformisreclaimed.UntiltheformisloadedagainbyusingeithertheLoadorShowmethod,ausercan'tinteractwiththeform,andtheformcan'tbemanipulatedprogrammatically.Youmaychoosetounloadaformwhenyouknowtheformwillnotbeusedagainintheapplicationandyouwanttoreclaimthememory.
TheHidemethoddoesnotperformanunload.Ifyourapplicationendsandaformhasnotbeenunloaded,itwillbeunloadedautomatically.ThefollowingtablecomparestheVBAShow,Hide,Load,andUnloadmethods:
VBAShow,Hide,Load,andUnloadmethods
Method Use
Show Displaysaform.Iftheformhasnotbeenloaded,itisloadedautomatically.
Hide Hidesaform.Theformisnotunloadedfrommemory.
Load Loadsaformintomemorybutdoesnotdisplayit.
Unload Unloadsaformfrommemory.ThiscanbedoneexplicitlyfromtheUnloadmethod,orautomaticallyattheterminationoftheapplication.
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>FormsinVBA>
ModalForms
WhenyoudefineadialogboxasmodalinAutoCADVBA,theusermustrespondtothedialogboxbeforeanyotherpartoftheapplicationisallowedtocontinue.NosubsequentcodeisexecuteduntilthemodaldialogboxisclosedthrougheithertheHideorUnloadmethod.Thisrequiresthatyou,asthedeveloperoftheapplication,thinkcarefullyabouthowandwhenyouimplementdialogboxes.
Forexample,youmayhaveadialogboxthatrequirestheusertoselectanobjectintheAutoCADdrawing.FortheusertobeabletopicktheobjectfromtheAutoCADApplicationwindow,youmusthidetheformbycallingtheHidemethod.OncetheobjecthasbeenselectedyouusetheShowmethodtoredisplaytheform,withallofitsdatastillcurrent,andcontinuewiththeapplication.
Note Althoughotherformsintheapplicationaredisabledwhenamodaldialogboxisdisplayed,otherapplicationsarenot.
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>
HandleErrors
Mostdevelopmentenvironmentsprovidedefaulterrorhandling.ForVBandVBA,thedefaultreactiontoanerroristodisplayanerrormessageandterminatetheapplication.Whilethisbehaviorisadequateduringthedevelopmentphaseofyourapplication,itisnotproductiveforyourenduser.Theremaybeerrorsthatyouwanttoignore,orthatyouwanttoprovidespecialresponsesto.Theremaybeerrorsthatyouwillwanttosuppresstheerrormessagedisplayfor,orsimplycontrolthemessagethatgetsdisplayedtotheuser.Inaddition,automaticallyterminatingtheapplicationishardlyeveracceptabletotheenduser.
Ingeneral,errorhandlingisnecessarywheneveruserinputisrequiredandwheneverworkingwithfileI/O.Remember,evenifyouaresureaneededfileisthereandavailableforprocessing,theremaybeconditionsyouhaven'tthoughtofthatcouldcauseerrors.
Note MostofthecodeexamplesprovidedintheAutoCADdocumentationdonotuseerrortrapping.Thiskeepstheexamplessimpleandtothepoint.However,aswithallprogramminglanguages,propererrortrappingandhandlingisessentialforarobustapplication.
Topicsinthissection
DefineApplicationErrorTypesTrapRuntimeErrorsRespondtoTrappedErrorsRespondtoAutoCADUserInputErrors
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>HandleErrors>
DefineApplicationErrorTypes
Therearethreedifferenttypesoferrorsyoucanencounterinyourapplications:compile-timeerrors,runtimeerrors,andlogicerrors.
Compile-timeerrorsoccurduringtheconstructionofyourapplication.Theseerrorsconsistmostlyofsyntaxmistakes,variablescopingproblems,ordatatypingproblems.InVBA,thesetypesoferrorsarecaughtbythedevelopmentenvironment.Whenyouenteranincorrectlineofcode,thelineishighlightedandanerrormessageappearstellingyoutheproblem.Compile-timeerrorsmustbecorrectedbeforetheapplicationcanrun.
Runtimeerrorsarealittlemoredifficulttofindandcorrect.Theyoccurduringtheexecutionofyourcode,andofteninvolvereceivinginformationfromtheuser.Forexample,ifyourapplicationrequirestheusertoenterthenameofadrawingandtheuserentersanameforadrawingthatdidn'texist,aruntimeerroroccurs.Tohandleruntimeerrorseffectively,youmustpredictwhatkindsofproblemscouldhappen,trapthem,andthenwritecodetohandlethesesituations.
Logicerrorsarethemostdifficulttofindandcorrect.Symptomsoflogicerrorsincludesituationsinwhichtherearenocompile-timeerrorsandnoruntimeerrors,buttheoutcomeofyourprogramisstillincorrect.Thisiswhatprogrammersrefertoasabug—andabugcanbeveryeasyorverydifficulttotrackdown.
Informationonfindingandcorrectingallthreetypesoferrorscanbefoundindocumentationforyourdevelopmentenvironment.AutoCAD-specificerrorsfallintotheruntimeerrorcategory,sothesetypesoferrorswillbecoveredmorefullyinthisdocumentation.
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>HandleErrors>
TrapRuntimeErrors
InVBandVBA,runtimeerrorsaretrappedusingtheOnErrorstatement.Thisstatementliterallysetsatrapforthesystem.Whenanerroroccurs,thisstatementautomaticallydetoursprocessingtoyourspeciallywrittenerrorhandler.Thedefaulterrorhandlingforthesystemisbypassed.
TheOnErrorstatementhasthreeforms:
OnErrorResumeNext
OnErrorGoToLabel
OnErrorGoTo0
TheOnErrorResumeNextstatementisusedwhenyouwanttoignoreerrors.Thisstatementtrapstheerrorandinsteadofdisplayinganerrormessageandterminatingtheprogram,itsimplymovesontothenextlineofcodeandcontinuesprocessing.Forexample,ifyouwantedtocreateasubroutinetoiteratethroughmodelspaceandchangethecolorofeachentity,youknowthatAutoCADwillthrowanerrorifyoutrytocoloranentityonalockedlayer.Insteadofterminatingtheprogram,simplyskiptheentityonthelockedlayerandcontinueprocessingtheremainingentities.TheOnErrorResumeNextstatementletsyoudojustthat.
TheOnErrorGoToLabelstatementisusedwhenyouwanttowriteanexpliciterrorhandler.Thisstatementtrapstheerrorandinsteadofdisplayinganerrormessageandterminatingtheprogram,itjumpstoaspecificlocationinyourcode.Yourcodecanthenrespondtotheerrorinwhatevermannerisappropriateforyourapplication.Forexample,youcanexpandtheexampleabovetodisplayamessagecontainingthehandleforeachentityonthelockedlayer.
HandleerrorswiththeOnErrorResumeNextstatement
Thefollowingsubroutineiteratesmodelspaceandchangesthecolorofeachentitytored.Tryrunningthissubroutineonadrawingwithseveralentities,someofwhichareonalockedlayer.Next,commentouttheOnErrorResumeNextstatementandrunthesubroutineagain.Youwillnoticethesubroutineterminatesatthefirstentityonthelockedlayer.
SubCh11_ColorEntities()
DimentryAsObject
OnErrorResumeNext
ForEachentryInThisDrawing.ModelSpace
entry.Color=acRed
Nextentry
EndSub
HandleerrorswiththeOnErrorGoTostatement
Thefollowingsubroutineiteratesmodelspaceandchangesthecolorofeachentitytored.Foreachentityonthelockedlayer,theerrorhandlerdisplaysacustomerrormessageandthehandleoftheentity.Tryrunningthissubroutineonadrawingwithseveralentities,someofwhichareonalockedlayer.Next,commentouttheOnErrorGoToMyErrorHandlingstatementandrunthesubroutineagain.Youwillnoticethesubroutineterminatesatthefirstentityonthelockedlayer.
SubCh11_ColorEntities2()
DimentryAsObject
OnErrorGoToMyErrorHandler
ForEachentryInThisDrawing.ModelSpace
entry.Color=acRed
Nextentry
'Important!Exitthesubroutinebeforetheerrorhandler
ExitSub
MyErrorHandler:
Msgboxentry.EntityName+"isonalockedlayer."+_
"Thehandleis:"+entry.Handle
ResumeNext
EndSub
TheOnErrorGoTo0statementcancelsthecurrenterrorhandler.TheOnErrorResumeNextandOnErrorGoToLabelstatementsremainineffectuntilthesubroutineends,anothererrorhandlerisdeclared,ortheerrorhandleriscanceledwiththeOnErrorGoTo0statement.
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>HandleErrors>
RespondtoTrappedErrors
Nowthatyouhavetrappedanerror,whatdoyoudowithit?Theanswerdependsonthenatureofyourapplicationandthenatureoftheerror.
VBandVBAprovideinformationonthetypeoferrorthathasbeentrappedbyusingtheErrobject.Thisobjecthasseveralproperties:Number,Description,Source,HelpFile,HelpContext,andLastDLLError.ThepropertiesoftheErrobjectgetfilledinwiththeinformationforthemostcurrenterror.ThemostimportantpropertiesaretheNumberandDescriptionproperties.TheNumberpropertycontainstheuniqueerrorcodeassociatedwiththeerror,andtheDescriptionpropertycontainstheerrormessagethatwouldnormallybedisplayed.
InyourerrorhandleryoucancomparetheNumberpropertyoftheerrortoanexpectedvalue.Thiswillhelpyoudeterminethenatureoftheerrorthathasoccurred.Onceyouknowwhatkindoferroryouaredealingwith,youcantaketheappropriateaction.
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>HandleErrors>
RespondtoAutoCADUserInputErrors
Theuser-inputmethodsprovideacertainamountofinherenterrortrappinginthattheyrequiretheusertoenteracertaintypeofdata.Iftheusertriestoentersomeotherdata,AutoCADrejectstheinputandrepromptstheuser.UsingtheInitializeUserInputmethodwiththeuserinputfunctionsprovidesadditionalcontroloftheuserinputbutcanalsointroduceadditionalconditionsthatmustbeverifiedthrougherrortrapping.Foranexampleoferrortrappingthatisrequiredwithcertaintypesofuser-input,seePromptforUserInput.
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>
EncryptVBACodeModules
AlthoughVBAdoesnotsupportcreationofexecutables,itdoesofferpasswordprotectionforthevisibilityoftheprojectforms,classes,andmodulesonaprojectbasis.YoucanfindthisProjectProtectionfacilityintheVBAIDEmenu.ChooseTools ProjectProperties Protection.
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>
RunaVBAMacrofromaToolbarorMenu
YoucanrunaVBAmacrofromanAutoCADtoolbarormenubysimplychangingtheMacropropertyforthattoolbarormenu.TheMacropropertymustbesetequalto
-VBARUNfilename.dvb!modulename.macroname
wherefilenameisthenameoftheprojectfile,modulenameisthenameofthemodulecontainingthemacrotoberun,andmacronameisthenameofthemacro.ThefilenameisonlyrequiredwhenthefileisnotloadedinthecurrentsessionofAutoCAD.Ifthefilenameisprovided,thefilewillbeloaded.
Formoreinformationoneditingmenusandtoolbars,seeCustomizeToolbarsandMenus.
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>
AutomaticallyLoadaVBAProject
TherearetwodifferentwaystoloadaVBAprojectautomatically:
WhenVBAisloadeditwilllookintheAutoCADdirectoryforaprojectnamedacad.dvb.Thisfileisautomaticallyloadedasthedefaultproject
Anyprojectotherthanthedefault,acad.dvb,canbeusedbyexplicitlyloadingthatprojectatstartupusingtheVBALOADcommand.ThefollowingcodesampleusestheAutoLISPstartupfiletoloadVBAandaVBAprojectnamedmyproj.dvbwhenAutoCADisstarted.Startnotepad.exeandcreate(orappendto)acad.lspthefollowinglines:(defunS::STARTUP()
(command"_VBALOAD""myproj.dvb")
)
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>
AutomaticallyRunaVBAMacro
Youcanautomaticallyrunanymacrointheacad.dvbfilebycallingitwiththecommandlineversionofVBARUNfromanAutoCADstartupfacilitylikeacad.lsp.Forexample,toautomaticallyrunthemacronameddrawline,firstsavethedrawlinemacrointheacad.dvbfile.Next,invokenotepad.exeandcreate(orappendto)acad.lspthefollowinglines:
(defunS::STARTUP()
(command"_-vbarun""drawline")
)
YoucancauseamacrotorunautomaticallywhenVBAloadsbynamingthemacroAcadStartup.Anymacroinyouracad.dvbfilecalledAcadStartupwillautomaticallygetexecutedwhenVBAloads.
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>
AutomaticallyOpentheVBAIDEWheneveraProjectIsLoaded
ThereisanoptionontheOpenVBAProjectdialogboxthatallowsyoutoopentheinteractivedevelopmentenvironmentautomatically.SimplyselecttheOpenVisualBasicEditorcheckboxfoundinthelower-leftsideofthedialogboxandtheVBAIDEwillopenautomaticallywheneveraVBAprojectisloaded.Thisoptionwillremainsetuntilyouturnitoffagain.
Note ToaccesstheOpenVBAProjectdialogbox,enterVBALOADatthecommandline.Thedialogboxwillopenandallowyoutochooseaprojecttoload.IfyoudonotseetheOpenVBAProjectdialogbox,itismostlikelybecausethesystemvariableFILEDIAisturnedoff.Thissystemvariableturnsonandoffthedisplayofdialogboxes.ToturnFILEDIAbackon,setitto1.
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>
WorkinaZeroDocumentState
AzerodocumentstateiswhentherearenoopendrawingsinAutoCAD.ThereareseveralimportantconsiderationstokeepinmindwhenyouareworkingwithVBAinazerodocumentstate:
TheThisDrawingobjectisundefinedinazerodocumentstate.AnyattempttouseThisDrawingwillresultinanerror.
Objectsthataredocumentdependentarealsonotdefinedinazerodocumentstate.DocumentdependentobjectsarethoseobjectsthatfallbelowtheDocumentobjectintheAutoCADobjectmodel.Workingwithnondocument-dependentobject,suchastheApplicationorMenuBarobjects,isallowed.
AutoCADdoesnothaveacommandlineinazerodocumentstate.AnyattempttoaccesstheAutoCADcommandlinewhileAutoCADisinazerodocumentstatewillresultinanerror.
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>
DistributeYourApplication
VBAapplicationscanbedistributedtwodifferentways:
EmbeddedinanAutoCADdrawingfile
StoredinaVBAprojectfile
Youmustchooseadistributionoptionthatisappropriateforyourapplication.Applicationsthatareapplicabletothecurrentdrawing,anddonotaccessotherdrawings,areoftenembeddedinthedrawing.Byembeddingtheapplicationinthedrawing,youcanalwaysbesuretheapplicationisloaded,andthereforeavailabletotheuserwheneverthedrawingisopen.
Applicationsthatareusedbymanypeople,areupdatedfrequently,needtoopenandcloseotherdrawings,orarenotusedfrequentlyyoumaywanttostoreinaVBAprojectfile.Inthisway,thereisonecentrallocationfortheapplication,andeveryonecanbesuretousethelatestversion.
FormoreinformationonembeddedprojectsandVBAprojectfiles,seeUnderstandEmbeddedandGlobalVBAProjects.
Topicsinthissection
DistributeVisualBasic6Applications
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>DistributeYourApplication>
DistributeVisualBasic6Applications
VisualBasic6applications,oranyotherout-of-processapplications,cannotbestoredwithinanAutoCADdrawing.Theseapplicationsarecompiledintostandaloneexecutables(EXEs).
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>
64-bitMigration
Microsoftisnotprovidinga64-bitversionofVBAfordevelopers;therefore,the32-bitapplicationsyoudevelopwillneedtobeportedfor64-bitAutoCADreleases.In64-bit,VBAwillrunasanout-of-processcomponent,accessedthrougha32-bit-to-64-bit“thunking”layer.
ThebehaviorofVBAinthe64-bitversionofAutoCADisnotguaranteedtobeidenticaltothatofVBAin32-bitAutoCAD.Forexample,whentheVBAIDEisactiveorwhenitisdisplayingamodalwindow,theremightbeaslightdelayduringtherepaintofanAutoCADwindow.
Topicsinthissection
AutoCADObjectInstantiationinVBAHandlingObjectIdAppendixof32-bitMethods
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>64-bitMigration>
AutoCADObjectInstantiationinVBA
64-bitoperatingsystemscanexecuteboth32-bitand64-bitapplications,buttheycannotmixthesetypeswithinaprocess.Forexample,youcannotload32-bitDLLsintoa64-bitprocess,orviceversa.Allexecutablecomponents(EXEandDLLfiles)thatareloadedintoaprocessmustmatchthebinarytypeoftheprocess.In-processcomponentsforyour64-bitapplicationsshouldbeportedto64-bitprocessesasmuchaspossible.
Oneerrorcouldoccurwhenattemptingtocreateanewobject.VB’sNewkeywordwillattempttoload64-bitAutoCADCOMDLLs.SinceVBAisa32-bitapplication,itcannotload64-bitDLLs.Forexample,codesuchas
DimcolorAsAcadAcCmColor
Setcolor=NewAcadAcCmColor
or
DimcolorAsNewAcadAcCmColor
color.SomeMethod()
needstobemodifiedandportedto
DimcolorAsAcadAcCmColor
Setcolor=AcadApplication.GetInterfaceObject(“Autocad.AcCmColor.17”).
TheaboveissueshouldberesolvedusingAcadApplication.GetInterfaceObject(“ProgIdOfAcAnyObject”)
foranyobjectthatisderivedfromIDispatch.ClassesderivedfromIUnknown(e.g.AcSmSheetSet,AcSmSheetMgretc)arenotexpectedtohavea64-BitVBAmigration.ItisrecommendedthatyouportsuchprocessestoVB.Net.
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>64-bitMigration>
HandlingObjectId
BeginningwithAutoCAD200964-bit,objectIDsarerepresentedbya64-bitintegerdatatype(__int64).Accessingthesevaluesin32-bitVBAwillresultinacompilationerror.Asaresolution,anewsetofmethodnamessuffixedwith“32”correspondingtotheoldmethodsareused(e.g.ObjectID32(),OwnerID32()).ThesemethodsusetheLONGdatatype,whichinternallymapstothe64-bitintegerdatatype.
Tobemoreprecise,a32-bitobjectIDiscreatedinternallyforeachobjectIDrequiredinVBA.ThisIDismappedtoits64-bitactualID,sothatifthe32-bitIDispassedbacktoAutoCADfromVBAcode,thenthe64-bitobjectIDisreturnedandusedinternallyforallpurposes.
Thefollowingsamplegivesanexampleofported32-bitObjectIDcode:
Originalcode:
DimsplineObjAsAcadSpline
DimobjectIDAsLong
objectID=splineObj.objectID
DimtempObjAsAcadObject
SettempObj=ThisDrawing.ObjectIdToObject(objectID)
Codeportedfor64-bitcompatibility:
DimsplineObjAsAcadSpline
DimobjectIDAsLong
objectID=splineObj.objectID32
DimtempObjAsAcadObject
SettempObj=ThisDrawing.ObjectIdToObject32(objectID)
VBAapplicationscanalsouseanobject’shandleinsteadofitsobjectID.ThefollowingsampleshowshowtousethehandleinsteadoftheobjectID:
Originalcode:
DimsplineObjAsAcadSpline
DimobjectIDAsLong
objectID=splineObj.objectID
DimtempObjAsAcadObject
SettempObj=ThisDrawing.ObjectIdToObject(objectID)
Codeportedfor64-bitcompatibility:
DimsplineObjAsAcadSpline
DimobjectHandleAsString
objectHandle=splineObj.Handle
DimtempObjAsAcadObject
SettempObj=ThisDrawing.HandleToObject(objectHandle)
Note :SupportforVBAwillbedeprecatedinfutureversionsofAutoCAD.VBAdevelopersshouldpreparetoporttheirVBAcodetoVB.Net.
Pleasesendusyourcommentaboutthispage
DevelopApplicationswithVBA>64-bitMigration>
Appendixof32-bitMethods
ThefollowingtableliststhenewmethodsaddedinAutoCAD2009for32-bitsubstitutions:
VBAtablemethodsfora64-bitsystem
Method Use
GetBlockAttributeValue32 Returnstheattributevaluefromthespecifiedblockcellfortheattributedefinitionobjectcontainedintheblockusingits32-bitobjectID.
GetBlockTableRecordId32 Getsthe32-bitobjectIDoftheblocktablerecordassociatedtotheblock-typecellandnContent.
GetFieldId32 Returnsthe32-bitobjectIDofthefieldobjectassociatedtothespecifedcell.
GetGridLinetype32 Returnsthe32-bitobjectIDofthegridlinetypeobject.
Key32 SpecifiestheobjectIDofthesourceobjectintheCopyObjectsoperationfora64-bitsystem.
ObjectID32 GetstheobjectIDfora64-bitsystem.
ObjectIDtoObject32 GetstheobjectthatcorrespondstothegivenobjectIDfora64-bitsystem.
OwnerID32 GetstheobjectIDoftheowner(parent)objectfora64-bitsystem.
SetBlockAttributeValue32 SetstheattributevaluefromthespecifiedblockcellfortheattributedefinitionobjectcontainedintheblockandnContentusingits32-bitobjectID.
SetBlockTableRecordId32 Setsthe32-bitobjectIDblocktablerecordassociatedtotheblock-typecellandnContent.
SetFieldId32 Setsthe32-bitobjectIDofthefieldobjectassociatedtothespecifedcellandnContent.
SetGridLinetype32 Setsthe32-bitobjectIDofthegridlinetypeobject.
Value32 Specifiesthecurrentvaluefortheproperty,ortheobjectIDofthenewlycreatedclonedobject,fora64-bitsystem.
Pleasesendusyourcommentaboutthispage
InteractwithOtherApplicationsandWindowsAPIs
ActiveXtechnologyallowsyoutoexchangeinformationeasilywithotherAutoCADapplicationsandotherActiveX-enabledapplicationssuchasMicrosoftExcelorMicrosoftWord.Thischapterexaminessomeofthebasicproceduresforinteractingwithotherapplications.
Topicsinthissection
InteractwithVisualLISPApplicationsInteractwithOtherWindowsApplicationsAccessWindowsAPIsfromVBA
Pleasesendusyourcommentaboutthispage
InteractwithOtherApplicationsandWindowsAPIs>
InteractwithVisualLISPApplications
VisualLISP®applicationshaveaccesstotheentirerangeofActiveX®objects.TheycancallActiveXmethods,andsetandretrieveActiveXproperties.Inaddition,VisualLISPapplicationscanalsorunVBAmacrosthroughtheVBARUNcommand.
ActiveXandVBAapplicationscanexecuteVisualLISPapplicationsthroughtheSendCommandmethod.ThismethodallowsActiveXandVBAapplicationstosendacommandtotheAutoCADcommandline.
FormoreinformationaboutaccessingActiveXobjectsthroughVisualLISP,seetheAutoLISPDeveloper'sGuide.
Pleasesendusyourcommentaboutthispage
InteractwithOtherApplicationsandWindowsAPIs>
InteractwithOtherWindowsApplications
AutoCAD®ActiveXtechnologyallowsyoutoexchangeinformationeasilywithotherActiveX-enabledapplicationssuchasMicrosoftExcelorMicrosoftWord.Thiscapabilityallowsyoutocollect,store,andpresentAutoCADinformationinformatsotherthantheAutoCADdrawing.YoucanalsoreadinformationfromtheseapplicationsbackintoAutoCADtodirectthecreationormanipulationofAutoCADobjects.AnexampleofusingthistechnologyistocreateabillofmaterialsasaMicrosoftExcelspreadsheetfromtheobjectsinanAutoCADdrawing.
YouhavealreadylearnedhowtowritecodeusingtheAutoCADActiveXObjectModel.ExchanginginformationwithotherActiveX-enabledapplicationsinvolvessimplyreferencingtheotherapplications'ActiveXObjectModelandwritingthecodenecessarytoutilizetheirobjects.
Note Thischapterprovidesonlyabriefintroductiontothecapabilitiesofcross-applicationprogramming.ThismaterialisnotAutoCAD-specific,andassuchitisdiscussedinbothMicrosoftdocumentationandindependentprogrammingguides.
ToexchangeinformationacrossActiveXObjectModels
1. Referencetheotherapplications'ActiveXObjectModel.ThiswillmakeyourcodeawareofthenamesandrelationshipsoftheobjectsintheotherObjectModel.
2. Createaninstanceoftheotherapplication.Thiswillcreate(instantiate)validobjectsforthebasicobjectsintheotherObjectModel.
3. WriteyourcodeutilizingboththeAutoCADObjectModelandtheotherapplications'ObjectModel.
Thisiswheretheexchangeofdatatakesplace.
Topicsinthissection
ReferencetheActiveXObjectLibraryofOtherApplicationsCreateanInstanceoftheOtherApplicationProgramwithObjectsfromOtherApplications
Pleasesendusyourcommentaboutthispage
InteractwithOtherApplicationsandWindowsAPIs>InteractwithOtherWindowsApplications>
ReferencetheActiveXObjectLibraryofOtherApplications
Towritecodethataccessesanotherapplication,youmustinstructVBAtomaketheobjectsintheotherapplicationavailabletoyou.Youdothisbysettingareferenceintheotherapplication'sobjectlibrary.Thisisafileonyourcomputerwherealltheobjects,methods,properties,constants,andeventsforthatapplicationaredefined.
YoumakeareferencetoanobjectlibrarythroughtheVBAIDE.IntheVBAIDE,undertheToolsmenu,thereisamenuoptioncalledReferences.ThismenuoptionwillbringupadialogboxthatlistsalloftheobjectlibrariesVBAfindsonyoursystem.Tomakeareferencetoalibrary,simplyselectthelibraryfromthelist.Librarieswithcheckboxesthatareselectedarealreadyreferencedinthecurrentproject.Forexample,toaddtheMicrosoftExcelobjectlibrary,selecttheMicrosoftExcelobjectlibraryentryinthelist.
Onceyouhavecreatedareferencetoanotherapplication'sobjectlibrary,youcanusetheVBAObjectBrowsertoviewalistoftheapplication'sobjects.
Note YoumustsetthereferenceforeachVBAprojectthatwillusethisObjectModel.Settingthereferenceforoneprojectwon'tautomaticallysetitforanotherproject.Thisisforperformancereasons.
Tomakeareferencetoanotherapplication'sobjectlibrary
1. IntheVBAIDE,opentheToolsmenuandselecttheReferencesmenuoption.
2. FindandselecttheentryinthelistofAvailableReferencesfortheapplicationyouwanttoaccess.
3. SelectOKtoclosethedialogboxwithyourchanges.
Pleasesendusyourcommentaboutthispage
InteractwithOtherApplicationsandWindowsAPIs>InteractwithOtherWindowsApplications>
CreateanInstanceoftheOtherApplication
Onceyouhavereferencedanapplication'sobjectlibraryyoumustcreateaninstanceoftheapplication.Thisisjustafancywayofsayingyouneedtostarttheotherapplicationprogrammaticallysoyourcodewillhavevalidobjectstoworkwith.
Todothis,firstdeclareavariablethatwillrepresenttheotherapplication.Youdothisthesamewayasbuilt-inobjects,byusingaDimstatement.YoushouldqualifythetypeofapplicationinyourDimstatement.Forexample,thisDimstatementdeclaresanobjectvariableoftypeExcel.Application:
DimExcelAppObjasExcel.Application
Afteryoudeclarethevariable,usetheSetstatementwiththeNewkeywordtosetthevariableequaltoarunninginstanceoftheapplication.Forexample,thefollowingSetstatementsetsthevariabledeclaredaboveequaltotheExcelapplication.TheNewkeywordstartsanewsessionofExcel.
SetExcelAppObj=NewExcel.Application
Note Someapplicationsallowonlyonerunninginstanceoftheapplicationatatime.UsingtheNewkeywordonsuchanapplicationwillestablishareferencetotheexistinginstanceandwillnotlaunchanewsessionoftheapplication.
Pleasesendusyourcommentaboutthispage
InteractwithOtherApplicationsandWindowsAPIs>InteractwithOtherWindowsApplications>
ProgramwithObjectsfromOtherApplications
Nowthatyouhavereferencedtheobjectlibraryandcreatedanewinstanceoftheapplication,youcancreateandmanipulateobjectsinthatapplication.Alltheobjects,methods,andpropertiesdefinedbytheObjectModelareavailabletoyou.Forexample,usingthevariabledeclarationsfromtheprevioussection,thefollowinglineofcodemakestheExcelsessionvisibletotheuser:
ExcelAppObj.Visible=TRUE
YoushouldfamiliarizeyourselfwiththeObjectModeloftheapplicationyouarewritingcodefor.YoucanusetheVBAObjectBrowserortheapplication'shelpfiletolearnaboutanyObjectModelyouarereferencing.
Topicsinthissection
QuittheOtherApplication
Pleasesendusyourcommentaboutthispage
InteractwithOtherApplicationsandWindowsAPIs>InteractwithOtherWindowsApplications>ProgramwithObjectsfromOtherApplications>
QuittheOtherApplication
Whenyoustartanapplicationprogrammaticallyittakesupmemoryinthecomputer.Youshouldquittheapplicationwhenyouhavefinishedusingitsosystemresourcescanbefreedup.
AlthougheachObjectModelisdifferent,mosthaveaQuitmethodfromtheApplicationobjectthatcanbeusedtoclosetheapplicationcleanly.Forexample,usingthevariabledeclarationsfromtheprevioussection,thefollowinglineofcodewillquitExcel:
ExcelAppObj.Application.Quit
Note Destroyingorgoingbeyondthescopeoftheobjectvariabledoesnotnecessarilycausetheapplicationtoterminate.Youshouldalwaysquittheapplicationusingtheappropriatemethodtoassurepropermemorycleanup.
ListAutoCADattributesonanExcelspreadsheet
Thissubroutinefindsalltheblockreferencesinthecurrentdrawing.ItthenfindstheattributesattachedtothoseblockreferencesandliststheminanExcelspreadsheet.Torunthisexample,dothefollowing:
1. Openadrawingcontainingblockreferenceswithattributes.(Thesampledrawingsample/activeX/attrib.dwgcontainssuchblockreferences.)
2. OpentheVBAIDEusingtheAutoCADVBAIDEcommand.
3. UsingtheTools ReferencesmenuoptionintheVBAIDE,selectMicrosoftExcel8.0ObjectModel.
4. CopythissubroutineintoaVBACodewindowandrunit.
SubCh12_Extract()
DimExcelAsExcel.Application
DimExcelSheetAsObject
DimExcelWorkbookAsObject
DimRowNumAsInteger
DimHeaderAsBoolean
DimelemAsAcadEntity
DimArray1AsVariant
DimCountAsInteger
'LaunchExcel.
SetExcel=NewExcel.Application
'Createanewworkbookandfindtheactivesheet.
SetExcelWorkbook=Excel.Workbooks.Add
SetExcelSheet=Excel.ActiveSheet
ExcelWorkbook.SaveAs"Attribute.xls"
RowNum=1
Header=False
'Iteratethroughmodelspacefinding
'allblockreferences.
ForEachelemInThisDrawing.ModelSpace
Withelem
'Whenablockreferencehasbeenfound,
'checkitforattributes
IfStrComp(.EntityName,"AcDbBlockReference",1)_
=0Then
If.HasAttributesThen
'Gettheattributes
Array1=.GetAttributes
'CopytheTagstringsforthe
'AttributesintoExcel
ForCount=LBound(Array1)ToUBound(Array1)
IfHeader=FalseThen
IfStrComp(Array1(Count).EntityName,_
"AcDbAttribute",1)=0Then
ExcelSheet.Cells(RowNum,_
Count+1).value=_
Array1(Count).TagString
EndIf
EndIf
NextCount
RowNum=RowNum+1
ForCount=LBound(Array1)ToUBound(Array1)
ExcelSheet.Cells(RowNum,Count+1).value_
=Array1(Count).textString
NextCount
Header=True
EndIf
EndIf
EndWith
Nextelem
Excel.Application.Quit
EndSub
Pleasesendusyourcommentaboutthispage
InteractwithOtherApplicationsandWindowsAPIs>
AccessWindowsAPIsfromVBA
TheWindows®APIproceduresareavailabletomostWindowsapplications.Theseproceduresallowyoutoexpandthecapabilitiesofyourapplication.
ThroughtheWindowsAPIsyoucanobtaininformationaboutthecurrentsystem,suchaswhichotherprogramsareinstalledorrunningonthesystem,whereinformationislocatedonasystem,andwhatthecurrentcontrolsettingsareforthesystem.Youcanalsoaccessjoystick,multimedia,andsoundcontrols.ThesetasksrepresentbutafewofthemanycapabilitiesprovidedbytheWindowsAPIs.
TouseaWindowsAPI,youmustfirstdeclaretheAPIinyourapplication.ThisisdonewiththeDeclarestatement.TheDeclarestatementrequiresseveralpiecesofinformation:
Thenameofthedynamiclinklibrary(DLL)containingtheprocedureyouwanttouse
ThenameoftheprocedureasitappearsintheDLL
Thenameoftheprocedureasyouwanttouseitinyourapplication
Theparameterstheprocedureexpectstoreceive
Thereturnvaluedatatype(iftheprocedureyouarecallingisafunction)
YoucanplacetheDeclarestatementinanyofyourVBAmodules.Ifyouplaceitinastandardmodule,theprocedurewillbeavailabletoanymoduleinyourapplication,unlessyoulimititsscopebyusingthekeywordPrivate.IfyouplacetheDeclarestatementinaclassorformmodule,theprocedurewillonlybeavailableinthatmodule.Onceaprocedurehasbeendeclared,youcancallthatprocedureasyouwouldanyotherprocedureinyourapplication.
GettingaDeclarestatementjustrightisadifficultskilltolearn.GettingaDeclarestatementwrongiseasy,butitoftencomeswithdireconsequences.
BesuretosaveanyinformationinactiveapplicationsbeforeyoutryoutanewDeclarestatement.
TohelpyouwithyourDeclarestatements,Microsoftprovidesafilelistingofmanyofthedeclarationsmostcommonlyused.ThefileiscalledWin32api.txtandcomeswithVisualBasic6andOffice.YoucansearchthisfilefortheprocedureyouneedandcopytheDeclarestatementprovidedintoyourcode.
TheMicrosoftVBAdocumentationcontainsmoreinformationontheDeclarestatementandanexampleofitsuse.TheMicrosoftWindowsAPIReferenceisavailableaspartoftheMicrosoftDeveloperNetworkCDsubscriptionandprovidesareferencetoalltheavailableproceduresintheWindowsAPIs.DanAppleman'sbookVisualBasicProgrammer'sGuidetotheWin32APIisalsoanexcellentresourcedirectedattheVisualBasic6programmer.
Pleasesendusyourcommentaboutthispage
<$nopage>tutorial:
ActiveX/VBATutorial:DesigntheGardenPath
ThistutorialdemonstrateshowtouseActiveXandVisualBasicforApplications(VBA)andhowtoaddamacrotoAutoCAD.Thetutorialisorientedtowardlandscapearchitecture,buttheconceptsinthetutorialarerelevanttoanyapplicationarea.
ThistutorialisdesignedfortheproficientAutoCADuserwhoisanoviceVBAprogrammer.
Topicsinthissection
CheckYourEnvironmentDefinetheGoalWritetheFirstFunctionGetInputDrawthePathOutlineDrawtheTilesTieItAllTogetherStepThroughtheCodeExecutetheMacroAddaDialogBoxInterface
Pleasesendusyourcommentaboutthispage
<$nopage>tutorial:
ActiveX/VBATutorial:DesigntheGardenPath>
CheckYourEnvironment
Forthetutorial,youneedtheAutoCAD®VBAintegrateddevelopmentenvironment(VBAIDE).TheVBAIDEisinstalledautomaticallywiththeFulloptionoftheAutoCADinstallationprogram.IfyouselectedtheCustomoptionwhenyouinstalledAutoCAD,theVBAIDEmightnotbeinstalled;youmightneedtoinstallitbyrunningtheAutoCADinstallationprogramagain.
TotestiftheVBAIDEisinstalled
1. StartAutoCAD.
2. Onthecommandline,entervbaide,andpressENTER.IftheVBAIDEopens,theVBAIDEisinstalled.Ifyoureceivethemessage“AutoCADVBAisnotcurrentlyinstalled,”theVBAIDEisnotinstalled.
Pleasesendusyourcommentaboutthispage
ActiveX/VBATutorial:DesigntheGardenPath>
DefinetheGoal
YourgoalinthistutorialistodevelopanewmacroforAutoCADthatdrawsagardenpathandfillsitwithcircularconcretetiles.Yournewmacrowillhavethefollowingpromptsequence:
Command: gardenpath
Startpointofpath: Theuserwillspecifythestartpoint
Endpointofpath: Theuserwillspecifytheendpoint
Halfwidthofpath: Theuserwillspecifyanumber
Radiusoftiles: Theuserwillspecifyanumber
Spacingbetweentiles: Theuserwillspecifyanumber
Yourmacrowillfirstprompttheusertoenterthestartpointandendpointtospecifythecenterlineofapath.Next,itwillprompttheusertoenterthehalfwidthofthepathandtheradiusofthecirculartiles.Finally,theuserwillenterthespacingbetweenthetiles.Youareusingthehalfwidthofthepathratherthanthefullwidthbecauseitiseasiertovisualizethehalfwidthfromthecenterlineofthepath.
Pleasesendusyourcommentaboutthispage
ActiveX/VBATutorial:DesigntheGardenPath>
WritetheFirstFunction
YoudeveloptheGardenpathmacrousingaseriesoffunctionsandsubroutines.Manysubroutinesrequirethemanipulationofangles.BecauseActiveXspecifiesanglesinradians,butmostusersthinkofanglesintermsofdegrees,beginbycreatingafunctionthatconvertsdegreestoradians.
Toconvertdegreestoradians
1. Onthecommandline,entervbaide,andpressENTER.
2. IntheVBAIDE,ontheViewmenu,clickCodetoopentheCodewindow.
3. EnterthefollowingcodeintheCodewindow:
Constpi=3.14159
'Convertangleindegreestoradians
Functiondtr(aAsDouble)AsDouble
dtr=(a/180)*pi
EndFunction
NoticethatassoonasyoupressENTERafterenteringthelineFunctiondtr(aAsDouble)AsDouble,EndFunction
isaddedautomatically.ThisensuresthatallsubroutinesandfunctionshaveanassociatedEndstatement.Nowlookatthecode.First,theconstantpiisdefinedasthevalue3.14159.Thisallowsyoutousethewordpiinsteadoftyping3.14159eachtimeyouneedtousethevalue.Next,youaredefiningafunctioncalleddtr(shortfordegreestoradians).Thefunctiondtrtakesoneargument,a,whichistheangleindegrees.Theresultisobtainedbydividingtheangleindegreesby180,andthenmultiplyingthisvaluebypi.Thelinethatbeginswithasinglequoteisacomment;VBAignoresalltextonalineafterasinglequote.
Thisfunctioncannowbeusedinothersubroutinesthroughoutyourproject.
4. Saveyourwork.ClickFile SaveGlobal1.Nametheprojectgardenpath.dvb.
Next,addafunctiontocalculatethedistancebetweenpoints.
Tocalculatethedistancebetweentwopoints
1. Enterthefollowingcodeafterthedtrfunction:
'Calculatedistancebetweentwopoints
Functiondistance(spAsVariant,epAsVariant)_
AsDouble
DimxAsDouble
DimyAsDouble
DimzAsDouble
x=sp(0)-ep(0)
y=sp(1)-ep(1)
z=sp(2)-ep(2)
distance=Sqr((Sqr((x^2)+(y^2))^2)+(z^2))
EndFunction
2. Saveyourwork.
Pleasesendusyourcommentaboutthispage
ActiveX/VBATutorial:DesigntheGardenPath>
GetInput
TheGardenpathmacroaskstheuserwheretodrawthepath,howwidetomakethepath,howlargetheconcretetilesare,andhowcloselytospacethosetiles.Youdefineasubroutinethataskstheuserforalloftheseitemsandthencomputesvariousnumberstouseintherestofthemacro.
Inthissubroutine,youusetheuserinputmethodsfoundintheUtilityobject.
Topicsinthissection
DeclareVariablesEnterthegpuserSubroutine
Pleasesendusyourcommentaboutthispage
ActiveX/VBATutorial:DesigntheGardenPath>GetInput>
DeclareVariables
Thenextsubroutineusesseveralvariables.Allvariablesmustbedeclaredbeforethesubroutinecanaccessthem.
IntheVBAIDE,enterthefollowingcodeintheCodewindow,immediatelyafterthelineConstpi=3.14159:
Privatesp(0To2)AsDouble
Privateep(0To2)AsDouble
PrivatehwidthAsDouble
PrivatetradAsDouble
PrivatetspacAsDouble
PrivatepangleAsDouble
PrivateplengthAsDouble
PrivatetotalwidthAsDouble
Privateangp90AsDouble
Privateangm90AsDouble
Nowlookatthetwodrop-downlistsatthetopoftheCodewindow.TheselistsarecalledtheObjectBoxandtheProcedure/EventBoxandcurrentlydisplaytheterms(General)and(Declarations),respectively.Theselistsdisplaythecurrentsectionofthecodeyouareworkingin,andenableyoutomovequicklytoadifferentsectionbysimplyselectingonefromthelist.The(Declarations)sectionistheappropriateplacetodeclarevariablesthatyouwilluseinmorethanonesubroutine.
Pleasesendusyourcommentaboutthispage
ActiveX/VBATutorial:DesigntheGardenPath>GetInput>
EnterthegpuserSubroutine
Thegpusersubroutinepromptstheuserforinformationnecessaryfordrawingagardenpath.Enterthefollowingcodeafterthedistancefunction:
'Acquireinformationforgardenpath
PrivateSubgpuser()
DimvarRetAsVariant
varRet=ThisDrawing.Utility.GetPoint(_
,"Startpointofpath:")
sp(0)=varRet(0)
sp(1)=varRet(1)
sp(2)=varRet(2)
varRet=ThisDrawing.Utility.GetPoint(_
,"Endpointofpath:")
ep(0)=varRet(0)
ep(1)=varRet(1)
ep(2)=varRet(2)
hwidth=ThisDrawing.Utility._
GetDistance(sp,"Halfwidthofpath:")
trad=ThisDrawing.Utility._
GetDistance(sp,"Radiusoftiles:")
tspac=ThisDrawing.Utility._
GetDistance(sp,"Spacingbetweentiles:")
pangle=ThisDrawing.Utility.AngleFromXAxis(_
sp,ep)
totalwidth=2*hwidth
plength=distance(sp,ep)
angp90=pangle+dtr(90)
angm90=pangle-dtr(90)
EndSub
Inthegpusersubroutine,thelineDimvarRetAsVariantdeclaresthevariablevarRet.Becausethisvariableisusedonlyinthissubroutine,itcanbedeclaredherelocally,insteadofinthe(Declarations)section.
Thenextline,varRet=ThisDrawing.Utility.GetPoint(,"Startpointofpath:"),callstheGetPointmethod.Theunderscore
inthelineisintendedtomakealonglineeasiertoread,andtellsVBAtoreadthenextlineasifitwereonthesameline.Youcanremovetheunderscorebyplacingthecodeallononeline.
ToaccesstheGetPointmethod,youmustfirstgothroughtheThisDrawingobjectthatrepresentsthecurrentdrawing.AfterenteringThisDrawingyouenteraperiod(.),whichmeansthatyouaregoingtoaccesssomethingwithinthatobject.Afteryoutypetheperiod,youenterUtilityandanotherperiod.Onceagain,youaregoingtoaccesssomethingwithintheUtilityobject.Finally,enterGetPoint,whichisthenameofthemethodyouarecalling.
TheGetPointmethodtakestwoparameters.Thefirstparameterisoptionalandwon'tbeused.Leavetheparameterblankandsimplytypeacommatomarkitsspot.Thesecondparameteristheprompt,whichisalsooptional.Forthisparameter,youenteredastringpromptingtheusertoenterthestartpoint.ThepointtheuserentersisputintothevarRetvariable.Thenextthreelinesofthesubroutinecopythepointreturnedbytheuserintothesparray.
Theendpointisreturnedinthesamemanner.
TheGetDistancemethodisusedtoobtainthehalfwidthofthepath(hwidth),thetileradius(trad),andthespacingbetweenthetiles(tspac).TheGetDistancemethodtakestwoparameters.Thefirstparameterisabasepoint.Forthisvalue,yousupplythestartpoint.Thesecondparameteristheprompt,forwhichyouprovideastringpromptingtheuserfortheappropriateinput.TheinterestingthingabouttheGetDistancemethodisthatitcanreturneitheravalueenteredonthecommandlineorthedistancebetweenapointselectedinAutoCADandthestartpoint.
Thesubroutinegoesontocalculateseveralvariablesusedlaterinthemacro.ThepanglevariableissettotheanglefromthestartpointtotheendpointandisfoundbyusingtheAngleFromXAxismethod.Thewidthofthepathisfoundbymultiplyingthehalfwidthbytwo.Theplengthvariableissettothelengthofthepathandisfoundusingthedistancefunctionyouenteredearlier.Finally,calculateandsavetheangleofthepathplusandminus90degreesinangp90andangm90,respectively.
Thefollowingillustrationshowshowthevariablesobtainedbygpuserspecifythedimensionsofthepath.
Saveyourwork.
Pleasesendusyourcommentaboutthispage
ActiveX/VBATutorial:DesigntheGardenPath>
DrawthePathOutline
Nowthatyouhaveacquiredthelocationandwidthofthepath,youcandrawitsoutline.Addthefollowingcodebelowthegpusersubroutine:
'Drawoutlineofpath
PrivateSubdrawout()
Dimpoints(0To9)AsDouble
DimplineAsAcadLWPolyline
DimvarRetAsVariant
varRet=ThisDrawing.Utility.PolarPoint(_
sp,angm90,hwidth)
points(0)=varRet(0)
points(1)=varRet(1)
points(8)=varRet(0)
points(9)=varRet(1)
varRet=ThisDrawing.Utility.PolarPoint(_
varRet,pangle,plength)
points(2)=varRet(0)
points(3)=varRet(1)
varRet=ThisDrawing.Utility.PolarPoint(_
varRet,angp90,totalwidth)
points(4)=varRet(0)
points(5)=varRet(1)
varRet=ThisDrawing.Utility.PolarPoint(_
varRet,pangle+dtr(180),plength)
points(6)=varRet(0)
points(7)=varRet(1)
Setpline=ThisDrawing.ModelSpace._
AddLightWeightPolyline(points)
EndSub
ThissubroutinedrawstheoutlineofthepathusingtheAddLightweightPolylinemethod.Thismethodtakesoneparameter:anarrayofpointsthatmakeupthepolyline.Youmustfindallthepointsthatmakeupthepolylineobjectandplacethemintoanarrayintheordertheyaretobedrawn.Forthispolyline,thepointsneededarethecornersofthepath.
Tofindthecornersofthepath,usethePolarPointmethod.Thismethodfindsapointthatisagivenangleanddistancefromabasepoint.Beginwiththestartpoint(sp)andfindthefirstcornerofthepath,workinginacounterclockwisedirection.Thiscornerwillbeatadistanceofhalfthewidthofthepath(hwidth)andat-90degreesfromthepathangle.Becauseyouwanttodrawaclosedrectangleforthepath,thispointbecomesthefirstandlastpointinthearray.Hence,theXandYcoordinatesreturnedfromthePolarPointmethodaremovedintothefirstandlastpositionsinthepointsarray.
Theremainingcornersofthepatharefoundinthesamemannerusingthelengthandwidthofthepath(plengthandwidth),andtheangleofthepath.EverytimethePolarPointmethodiscalled,thecoordinatesreturned(varRet)arecopiedintothepointsarray.
Onceallthecornershavebeenidentifiedinthepointsarray,theAddLightweightPolylinemethodiscalled.NoticethatthismethodiscalledfromtheModelSpaceobject.Ifyouweretorunthismacro,youwouldalsonoticethatthepolylineisnotyetvisibleinAutoCAD.Thepolylinewillnotbecomevisibleuntilyouupdatethedisplay,whichyouwilldolater.
Pleasesendusyourcommentaboutthispage
ActiveX/VBATutorial:DesigntheGardenPath>
DrawtheTiles
Nowthatyouhavedevelopedtheuserinputsubroutine,alongwiththesubroutinetodrawtheoutline,youarereadytofillthepathwithcirculartiles.Thistaskrequiressomegeometry.
IntheVBAIDE,enterthefollowingcodeintheCodewindow,afterthedrawoutsubroutine:
'Placeonerowoftilesthegivendistancealongpath
'andpossiblyoffsetit
PrivateSubdrow(pdAsDouble,offsetAsDouble)
Dimpfirst(0To2)AsDouble
Dimpctile(0To2)AsDouble
Dimpltile(0To2)AsDouble
DimcirAsAcadCircle
DimvarRetAsVariant
varRet=ThisDrawing.Utility.PolarPoint(_
sp,pangle,pd)
pfirst(0)=varRet(0)
pfirst(1)=varRet(1)
pfirst(2)=varRet(2)
varRet=ThisDrawing.Utility.PolarPoint(_
pfirst,angp90,offset)
pctile(0)=varRet(0)
pctile(1)=varRet(1)
pctile(2)=varRet(2)
pltile(0)=pctile(0)
pltile(1)=pctile(1)
pltile(2)=pctile(2)
DoWhiledistance(pfirst,pltile)<(hwidth-trad)
Setcir=ThisDrawing.ModelSpace.AddCircle(_
pltile,trad)
varRet=ThisDrawing.Utility.PolarPoint(_
pltile,angp90,(tspac+trad+trad))
pltile(0)=varRet(0)
pltile(1)=varRet(1)
pltile(2)=varRet(2)
Loop
varRet=ThisDrawing.Utility.PolarPoint(_
pctile,angm90,tspac+trad+trad)
pltile(0)=varRet(0)
pltile(1)=varRet(1)
pltile(2)=varRet(2)
DoWhiledistance(pfirst,pltile)<(hwidth-trad)
Setcir=ThisDrawing.ModelSpace.AddCircle(_
pltile,trad)
varRet=ThisDrawing.Utility.PolarPoint(_
pltile,angm90,(tspac+trad+trad))
pltile(0)=varRet(0)
pltile(1)=varRet(1)
pltile(2)=varRet(2)
Loop
EndSub
'Drawtherowsoftiles
PrivateSubdrawtiles()
DimpdistAsDouble
DimoffsetAsDouble
pdist=trad+tspac
offset=0
DoWhilepdist<=(plength-trad)
drowpdist,offset
pdist=pdist+((tspac+trad+trad)*Sin(dtr(60)))
Ifoffset=0Then
offset=(tspac+trad+trad)*Cos(dtr(60))
Else
offset=0
EndIf
Loop
EndSub
Tounderstandhowthesesubroutineswork,refertothefollowingillustration.Thesubroutinedrowdrawsarowoftilesatagivendistancealongthepathspecifiedbyitsfirstargument,andoffsetstherowperpendiculartothepathbyadistancespecifiedbyitssecondargument.Youwanttooffsetthetilesonalternaterowstocovermorespaceandmakeamorepleasingarrangement.
ThedrowsubroutinefindsthelocationforthefirstrowbyusingthePolarPointmethodtomovealongthepathbythedistancespecifiedbythefirstargument.ThesubroutinethenusesthePolarPointmethodagaintomoveperpendicularlytothepathfortheoffset.ThesubroutineusestheWhilestatementtocontinuetodrawcirclesuntiltheedgeofthepathisencountered.ThePolarPointmethodinthefirstWhilestatementmovesontothenexttilelocationbyspacingadistanceoftwotileradii(trad)andoneintertilespace(tspac).Asecondwhileloopthendrawsthetilesintherowintheotherdirectionuntiltheotheredgeisencountered.
Thedrawtilessubroutinecallsdrowrepeatedlytodrawallthetilerows.ThesubroutineWhileloopstepsalongthepath,callingdrowforeachrow.Tilesinadjacentrowsformequilateraltriangles,asshowninthepreviousillustration.Theedgesofthesetrianglesareequaltotwicethetileradiusplusthespacingbetweenthetiles.Therefore,bytrigonometry,thedistancealongthepathbetweenrowsisthesineof60degreesmultipliedbythisquantity,andtheoffsetforoddrowsisthecosineof60degreesmultipliedbythisquantity.
TheIfstatementisusedindrawtilestooffseteveryotherrow.Iftheoffsetisequalto0,setittothespacingbetweenthecentersoftilesmultipliedbythecosineof60degrees,asexplainedearlier.Iftheoffsetisnotequalto0,setitto0.Thisalternatestheoffsetontherowsasyouwant.
Saveyourwork.
Pleasesendusyourcommentaboutthispage
ActiveX/VBATutorial:DesigntheGardenPath>
TieItAllTogether
YouarereadytocombinethesubroutinesintotheGardenpathmacro.IntheVBAIDE,enterthefollowingcodeintheCodewindow,afterthedrawtilessubroutine:
'Executecommand,callingconstituentfunctions
Subgardenpath()
DimsblipAsVariant
DimscmdeAsVariant
gpuser
sblip=ThisDrawing.GetVariable("blipmode")
scmde=ThisDrawing.GetVariable("cmdecho")
ThisDrawing.SetVariable"blipmode",0
ThisDrawing.SetVariable"cmdecho",0
drawout
drawtiles
ThisDrawing.SetVariable"blipmode",sblip
ThisDrawing.SetVariable"cmdecho",scmde
EndSub
Thepathsubroutinecallsgpusertogatherthenecessaryinput.TheGetVariablemethodisthenusedtoobtainthecurrentvaluesoftheBLIPMODEandCMDECHOsystemvariables,andsavesthesevaluesassblipandscmde.ThesubroutinethenusestheSetVariablemethodtosetbothofthesesystemvariablesto0,therebydisablingblipsandcommandechoing.Next,thepathisdrawnusingthedrawoutanddrawtilessubroutines.Finally,theSetVariablemethodisusedtoresetthesystemvariablestotheiroriginalvalues.
YoumaynoticethatthisistheonlysubroutineyouhaveenteredthatdidnotbeginwithaPrivatekeyword,whichensuresthesubroutinecanonlybecalledfromwithinthecurrentmodule.Becausethegardenpathsubroutinemustbeavailabletotheuser,youshouldomitthePrivatekeyword.
Saveyourwork.
Pleasesendusyourcommentaboutthispage
ActiveX/VBATutorial:DesigntheGardenPath>
StepThroughtheCode
Nowrunthemacro,steppingthroughthecodeasitexecutes.
FromtheAutoCADToolsmenu,clickMacro Macros.FromtheMacrosdialogboxselectThisDrawing.gardenpathandclickStepInto.
TheVBAIDEisbroughttothefrontofthescreen,withthefirstlineofthegardenpathmacrohighlighted.Thehighlightedlineisthelineofcodethatisabouttobeexecuted.Toexecutetheline,pressF8.Thenextlineofcodetobeexecutedisthegpusersubroutine.Tostepintothegpusersubroutine,pressF8again.
Nowyouareatthebeginningofthegpuserroutine.PressF8onemoretimetohighlightthefirstGetPointmethod.Beforeyouexecutethisline,opentheLocalswindowbyclickingView LocalsWindow.ThiswindowisdisplayedatthebottomoftheVBAIDE.AllthelocalvariablesandtheirvaluesaredisplayedintheLocalswindowwhilethemacroisexecuting.
NowpressF8toexecutetheGetPointmethod.Noticethatthehighlightdisappearsandnonewcodeispresented.ThisisbecausetheGetPointmethodiswaitingfortheusertoenterapointinAutoCAD.SwitchbacktotheAutoCADwindow.YouseethepromptyouspecifiedintheGetPointcallonthecommandline.Enterapoint.
Controlnowreturnstothemacro.ThelinefollowingthecalltotheGetPointmethodishighlighted.ContinuesteppingthroughthecodebypressingF8.RemembertoswitchbacktotheAutoCADwindowwhenyouareenteringinformation.
Pleasesendusyourcommentaboutthispage
ActiveX/VBATutorial:DesigntheGardenPath>
ExecutetheMacro
Youdon'tneedtostepthroughthecodewheneveryourunthemacro.YoucanrunthemacrofromtheToolsmenubyclickingMacro Macros,selectingamacro,andthenclickingRun.Thisallowsyoutoseetheflowofexecutionthewayauserwouldseeit.RunthemacrofromAutoCAD,enteringthefollowingvalues:
Startpointofthepath: 2,2
Endpointofthepath: 9,8
Halfwidthofthepath: 2
Radiusoftiles: .2
Spacingbetweentiles: .1
Thisexampleshoulddrawagardenpathasshowninthefollowingfigure:
YoucanexperimentwiththeGardenpathmacrobyspecifyingthevariousinputs.
Pleasesendusyourcommentaboutthispage
ActiveX/VBATutorial:DesigntheGardenPath>
AddaDialogBoxInterface
TheGardenpathmacrohasbeenwrittentoacceptcommandlineinput.Toadddialogboxes,youuseformsintheVBAIDE.
First,copythefinishedversionofgardenpath.dvbtoanotherfile,gpdialog.dvb.Thendraggpdialog.dvbintoAutoCAD.
Topicsinthissection
CreatetheDialogBoxUsetheProjectWindowtoNavigateYourProjectUpdatetheExistingCodeAddCodetotheDialogBox
Pleasesendusyourcommentaboutthispage
ActiveX/VBATutorial:DesigntheGardenPath>AddaDialogBoxInterface>
CreatetheDialogBox
Thedialogboxyoucreatecontainstwooptionbuttons(ifyouselectone,theotheriscleared)forchoosingthetileshape:circleorpolygon.Thedialogboxalsocontainsthreetextboxesforenteringthefollowingnumericvalues:theradiusofthetiles,thespacingbetweenthetiles,andthenumberofsidesonthetile(whichisavailableonlyifthePolygonoptionbuttonisselected).
TocreateadialogboxfromtheVBAIDE
1. OntheInsertmenu,clickUserFormtoopenanewform.Twowindows,atoolbox,andablankuserformaredisplayed.
2. Onebyone,selectanddragthefollowingcontrolsfromthetoolboxandplacethemontheuserform.Youshouldplacetwooptionbuttons(
),threelabels(
),threetextboxes(
),andtwocommandbuttons(
),asillustratedonthefollowingform:
3. Closethetoolbox.
Tosetthepropertiesfortheradiobuttoncontrols
1. Ontheuserform,selecttheOptionButton1control.OntheViewmenu,clickPropertiesWindow,andchangethefollowingpropertiesforOptionButton1:(Name)=gp_polyCaption=PolygonControlTipText=PolygonTileShapeAccelerator=P
2. Ontheuserform,selecttheOptionButton2control.InthePropertieswindow,changethefollowingpropertiesforOptionButton2:(Name)=gp_circCaption=CircleControlTipText=CircleTileShapeAccelerator=I
Tosetthepropertiesforthelabelcontrols
1. Ontheuserform,selecttheLabel1control.InthePropertieswindow,changethefollowingpropertiesforLabel1:
(Name)=label_tradCaption=RadiusoftilesTabStop=True
2. Ontheuserform,selecttheLabel2control.InthePropertieswindow,changethefollowingpropertiesforLabel2:(Name)=label_tspacCaption=SpacebetweentilesTabStop=True
3. Ontheuserform,selecttheLabel3control.InthePropertieswindow,changethefollowingpropertiesforLabel3:(Name)=label_tsidesCaption=NumberofsidesTabStop=True
Tosetthepropertiesforthetextboxcontrols
1. Ontheuserform,selecttheTextBox1control.InthePropertieswindow,changethefollowingpropertyforTextBox1:(Name)=gp_trad
2. Ontheuserform,selecttheTextBox2control.InthePropertieswindow,changethefollowingpropertyforTextBox2:(Name)=gp_tspac
3. Ontheuserform,selecttheTextBox3control.InthePropertieswindow,changethefollowingpropertyforTextBox3:(Name)=gp_tsides
Tosetthepropertiesforthecommandbuttoncontrolsandtheformwindow
1. Ontheuserform,selecttheCommandButton1control.InthePropertieswindow,changethefollowingpropertiesforCommandButton1:(Name)=accept
Caption=OKControlTipText=AccepttheoptionsAccelerator=ODefault=True
2. Ontheuserform,selecttheCommandButton2control.InthePropertieswindowchangethefollowingpropertiesforCommandButton2:(Name)=cancelCaption=CancelControlTipText=CanceltheoperationAccelerator=C
3. Selecttheuserformitselfbyclickingonthebackgroundoftheform,awayfromanycontrol.InthePropertieswindow,changethefollowingpropertiesfortheform:(Name)=gpDialogCaption=GardenPathYourformshouldnowlooklikethis:
4. Saveyourwork.
Pleasesendusyourcommentaboutthispage
ActiveX/VBATutorial:DesigntheGardenPath>AddaDialogBoxInterface>
UsetheProjectWindowtoNavigateYourProject
IntheVBAIDE,theProjectwindowcontainsthenameandlocationoftheproject,afoldernamedAutoCADObjects,andafoldernamedForms.(YoumightneedtoclickToggleFolderstoseethefolders.)WhenyouopentheAutoCADObjectsfolder(itmayalreadybeopen),youseeadrawingiconandthenameThisDrawing.WhenyouopentheFormsfolder(itmayalreadybeopen),youseeaformiconandthenamegpDialog,theformyoucreated.
YoucanusetheProjectwindowtonavigatethroughcodeandhelpyouidentifywhereyouareworking.Forexample,toviewthecodeassociatedwiththeformyoucreated,highlightgpDialogintheProjectwindowandclickViewCode.
TheCodewindowfortheformisdisplayed.
NowhighlightThisDrawingintheProjectwindow.YoucanviewthecodebyclickingViewCode.Allthecodeyouhavealreadyenteredisinthiswindow.
Pleasesendusyourcommentaboutthispage
ActiveX/VBATutorial:DesigntheGardenPath>AddaDialogBoxInterface>
UpdatetheExistingCode
Nowthatyouhavecreatedadialogbox,youcanmodifyandaddcode.
Tomodifytheexistingcode
1. OpenthecodeforThisDrawing,ifitisnotalreadyopen.
2. UpdatethefollowinglinesintheDeclarationssection:
PublictradAsDouble'Updated
PublictspacAsDouble'Updated
PublictsidesAsInteger'Add
PublictshapeAsString'Add
Becausethecodeintheformaccessestradandtspac,youupdatetheirdefinitionstomakethempublic.Privatevariablesareavailableonlyinthemoduleinwhichtheyaredefined,sothevariablesneedtobechangedtopublic.Additionally,youhaveaddedtsidesforthenumberofpolygontilesidesandtshapefortheuser'schoiceoftileshape,whichiseithercircleorpolygon.
3. Gotothegpusersubroutine.Removethetwolinesthatobtaintheradiusofthetilesandthespacingbetweenthetiles,becausethisinformationcomesfromtheform.Specifically,removethefollowing:
trad=ThisDrawing.Utility._
GetDistance(sp,"Radiusoftiles:")
tspac=ThisDrawing.Utility._
GetDistance(sp,"Spacingbetweentiles:")
4. Addthelinesthatloadanddisplaytheform.Addthefollowinglinesinplaceofthelinesremovedinstep3:
LoadgpDialog
gpDialog.Show
5. Addasubroutinetotheendofthecodefilethatdrawseitherthecirculartilesorthepolygontiles:
'Drawthetilewiththedesignatedshape
SubDrawShape(pltile)
DimangleSegmentAsDouble
DimcurrentAngleAsDouble
DimangleInRadiansAsDouble
DimcurrentSideAsInteger
DimvarRetAsVariant
DimaCircleAsAcadCircle
DimaPolygonAsAcadLWPolyline
ReDimpoints(1Totsides*2)AsDouble
'Branchbasedonthetypeofshapetodraw
SelectCasetshape
Case"Circle"
SetaCircle=ThisDrawing.ModelSpace._
AddCircle(pltile,trad)
Case"Polygon"
angleSegment=360/tsides
currentAngle=0
ForcurrentSide=0To(tsides-1)
angleInRadians=dtr(currentAngle)
varRet=ThisDrawing.Utility.PolarPoint(pltile,_
angleInRadians,trad)
points((currentSide*2)+1)=varRet(0)
points((currentSide*2)+2)=varRet(1)
currentAngle=currentAngle+angleSegment
NextcurrentSide
SetaPolygon=ThisDrawing.ModelSpace._
AddLightWeightPolyline(points)
aPolygon.Closed=True
EndSelect
EndSub
ThissubroutineusesaSelectCasestatementtobranchcontroloftheprogrambasedonthetypeofshapetodraw.Thetshapevariableisusedtodeterminethetypeofshape.
6. Next,gotothedrowsubroutine.Findthetwooccurrencesofthefollowingline:
Setcir=ThisDrawing.ModelSpace.AddCircle(pltile,trad)
Changetheselinestodrawtheappropriateshapetile,asfollows:
DrawShape(pltile)'Updated
Pleasesendusyourcommentaboutthispage
ActiveX/VBATutorial:DesigntheGardenPath>AddaDialogBoxInterface>
AddCodetotheDialogBox
NowyouremovethecodeforthecirculartilecreationandcalltheDrawShapesubroutinetodrawtheappropriateshapeinstead.
Toaddeventhandlersforthedialogbox
1. OpentheCodewindowforgpDialog.
2. Enterthefollowingcodeatthetopofthewindow:
PrivateSubgp_poly_Click()
gp_tsides.Enabled=True
ThisDrawing.tshape="Polygon"
EndSub
PrivateSubgp_circ_Click()
gp_tsides.Enabled=False
ThisDrawing.tshape="Circle"
EndSub
Noticethatthesubroutinesgp_poly_Click()andgp_circ_Click()arenamedafterthetwooptioncontrolsyouaddedearlier,withtheadditionof_Click.Thesesubroutinesareautomaticallyexecutedwhentheuserclickstherespectivecontrol.AlsonoticethattheObjectBoxliststhecontrolsontheform,sortedalphabeticallybyNameproperty.
3. PlaceyourcursoronthePrivateSubgp_poly_Click()lineandopentheProcedure/EventBox.Youseealistofalltheeventsthatyoucanrespondtoforthegp_polyoptioncontrol.ThetwosubroutinesyouenteredhandletheClickevent.YoucanalsoaddcodetorespondtotheDblClickeventthatwouldautomaticallybeexecutedwhentheuserdouble-clickedthecontrol.Youcanaddcodeforanyoftheeventslisted.Thesetypesofsubroutinesarecalledeventhandlers.Lookatthecodeyouenteredforthesetwoeventhandlers.ThefirsteventhandlerrespondstotheClickeventforthegp_polyoptioncontrol.Thefirstlineofcodeenablesthetextboxforthenumberofsides.Thistextboxisavailableonlyforpolygons,soitisnotenabledunlessyouselectthePolygoncontrol.ThenextlineofcodesetsthetshapevariabletoPolygon.ThesecondeventhandlerrespondstotheClickeventforthegp_circoptioncontrol.ThishandlerdisablesthetextboxforthenumberofsidesandsetsthetshapevariabletoCircle.
4. AddthefollowingeventhandlerfortheOKbutton:
PrivateSubaccept_Click()
IfThisDrawing.tshape="Polygon"Then
ThisDrawing.tsides=CInt(gp_tsides.text)
If(ThisDrawing.tsides<3#)Or_
(ThisDrawing.tsides>1024#)Then
MsgBox"Enteravaluebetween3and"&_
"1024forthenumberofsides."
ExitSub
EndIf
EndIf
ThisDrawing.trad=CDbl(gp_trad.text)
ThisDrawing.tspac=CDbl(gp_tspac.text)
IfThisDrawing.trad<0#Then
MsgBox"Enterapositivevaluefortheradius."
ExitSub
EndIf
If(ThisDrawing.tspac<0#)Then
MsgBox"Enterapositivevalueforthespacing."
ExitSub
EndIf
GPDialog.Hide
EndSub
Thiscodetestswhetherthefinalchoiceofshapewaspolygon.Ifso,thecoderetrievesthenumberofsidesfromthegp_tsidescontrol.ThevaluetheuserentersisstoredintheTextproperty.Becauseitisstoredasatextstring,youconvertthestringtotheintegerequivalentusingtheCIntfunction.Onceobtained,theeventhandlerteststherangeofthevaluetomakesureitisbetween3and1024.Ifitisnot,amessageisdisplayedandtheeventhandlerisexitedwithoutfurtherprocessing.Theresultisthatamessageisdisplayedandtheuserisgivenanopportunitytochangethevalue.AftertheOKbuttonisclickedagain,thiseventhandlertriggersandteststhevalueagain.Themacroobtainsradiusandspacingvalues,butthesevaluesaredoubles,notintegers,andareobtainedusingtheCDblfunction.Thesevaluesarealsotestedtomakesuretheyarepositive.Afterthevaluesareobtainedandverified,thegpDialog.Hidestatementhidestheform,passingcontrolbacktothesubroutinethatfirstcalledtheform.
5. AddthefollowingeventhandlerfortheCancelbutton:
PrivateSubcancel_Click()
UnloadMe
End
EndSub
Thissimpleeventhandlerunloadstheformandendstheentiremacro.Theonlythingyouhaven'tdoneisaddtheinitialvaluesfortheform.ThereisaneventcalledInitializethatappliestotheform.Itisexecutedwhentheformisfirstloaded.
6. Addthefollowingeventhandlerfortheforminitialization:
PrivateSubUserForm_Initialize()
gp_circ.Value=True
gp_trad.Text=".2"
gp_tspac.Text=".1"
gp_tsides.Text="5"
gp_tsides.Enabled=False
ThisDrawing.tsides=5
EndSub
Thiscodesetstheinitialvaluesfortheformandforthetsidesvariable.Thetsidesvariablemustbesettoapositivenumbergreaterthan3,eveniftheuserselectsacircle.Tounderstandthis,lookintheDrawShapesubroutinethatyouenteredearlier.Thereisavariabletherecalledpointsthatisdefinedusingthenumberofsidesforthepolygon.Thatvariablegetsmemoryallocatedtoitwhetherornotapolygonshapehasbeenrequested.Becauseofthis,tsidesmusthaveavalidrangedefinedforit.Theuserisfreetochangethisvalueduringmacroexecution.
YoucannowsaveandrunthemacrofromAutoCAD.
Pleasesendusyourcommentaboutthispage
VisualLISPandActiveX/VBAComparison
MostofthecapabilitiesfoundintheVisualLISPinterfacecanalsobefoundintheActiveXandVBAinterface.ThisappendixservesasareferencetohelpdevelopersfamiliarwithVisualLISPfindtheequivalentActiveXandVBAfunctionality.
Topicsinthissection
VisualLISPandActiveX/VBAComparison
Pleasesendusyourcommentaboutthispage
VisualLISPandActiveX/VBAComparison>
VisualLISPandActiveX/VBAComparison
ThefollowingtablecomparesVisualLISPfunctionswiththesimilarActiveX®,VBA,andVisualBasic6functionsandoperators.TheActiveXAutomationequivalentsareindicatedby“AutoCAD.Application.”andtheVisualBasic6equivalentsarelistedasafunctionoroperator.
VisualLISPandActiveX/VBAComparison
AutoLISPfunction ActiveX,VBA,orVisualBasic6equivalent
+(addition) +(additionoperator)
-(subtraction) -(subtractionoperator)
*(multiplication)
*(multiplicationoperator)
/(division) /(divisionoperator)
=(equalto) =(equaltocomparisonoperator)
/=(notequalto)
<>(notequaltocomparisonoperator)
<(lessthan) <(lessthancomparisonoperator)
<=(lessthanorequalto)
<=(lessthanorequaltocomparisonoperator)
/=(notequalto)
<>(notequaltocomparisonoperator)
>(greaterthan) >(greaterthancomparisonoperator)
>=(greaterthanorequalto)
>=(greaterthanorequaltocomparisonoperator)
~(bitwisenot) Notoperator
1+(increment) Use+(additionoperator)
1-(decrement) Use-(subtractionoperator)
abs Absfunction
acad_colordlg Notprovided
acad_helpdlg SearchforHELPintheonlineHelpindex
acad_strlsort SearchforSORTintheonlineHelpindex
action_tile UsetheDialogEditor
add_list UsetheDialogEditor
ads AutoCAD.Application.ListADSmethod
alert MsgBoxfunction
and Andoperator
angle AutoCAD.Application.ActiveDocument.Utility.AngleFromXAxismethod
angtof AutoCAD.Application.ActiveDocument.Utility.AngleToRealmethod
angtos AutoCAD.Application.ActiveDocument.Utility.AngleToStringmethod
append Usearraymanipulationfunctions
apply Notprovided
arx AutoCAD.Application.ListARXmethod
arxload AutoCAD.Application.LoadARXmethod
arxunload AutoCAD.Application.UnloadARXmethod
ascii Ascfunction
assoc Notprovided
atan Atnfunction
atof CDblFunction
atoi CIntFunction
atom SearchforISintheonlineHelpindex
atoms-family Notprovided
autoarxload Notprovided
autoload Notprovided
Boole Uselogicaloperators
boundp SearchforISintheonlineHelpindex
car/cdr Usearraymanipulationfunctions
chr Chrfunction
client_data_tile UsetheDialogEditor
close AutoCAD.Application.Documents.Closemethod
command AutoCAD.ActiveDocument.SendCommandmethod
cond SelectCasestatement
cons UsearraymanipulationfunctionsorAutoCAD.Application.collection.Add<entityname>method
cos Cosfunction
cvunit Usetheconversionfunctions
defun ThekeywordsFunctionandEndFunction
dictadd AutoCAD.Application.ActiveDocument.Dictionaries.Addmethod
dictnext AutoCAD.Application.ActiveDocument.Dictionaries.Itemmethod
dictremove AutoCAD.Application.ActiveDocument.Dictionaries.Dictionary.Deletemethod
dictrename AutoCAD.Application.ActiveDocument.Dictionaries.Dictionary.Renamemethod
dictsearch AutoCAD.Application.ActiveDocument.Dictionaries.Dictionary.GetNameandGetObjectmethods
dimx_tileanddimy_tile
UsetheDialogEditor
distance AutoCAD.Application.Utility.GetDistanceforinteractivemethod.
distof Notprovided
done_dialog UsetheDialogEditor
end_image UsetheDialogEditor
end_list UsetheDialogEditor
entdel AutoCAD.Application.ActiveDocument.collection_object.Deletemethod
entget AutoCAD.Application.ActiveDocument.collection_object.propertyproperties
entlast AutoCAD.Application.ActiveDocument.Modelspace.Item(count-1)
entmake AutoCAD.Application.ActiveDocument.Modelspace.Add<entityname>method
entmakex AutoCAD.Application.ActiveDocument.Modelspace.Add<entityname>method
entmod Useanyoftheread-writepropertiesfortheobject
entnext AutoCAD.Application.ActiveDocument.collection.Itemmethod
entsel AutoCAD.Application.ActiveDocument.SelectionSetsobject/methods/properties
entupd AutoCAD.Application.ActiveDocument.Modelspace.object.Updatemethod
eq Notprovided
equal Eqvoperator
*error* Errorobject/method/properties
eval Notprovided
exit AutoCAD.Application.Quitmethod
exp Expfunction
expand Notprovided
expt ^(exponentiationoperator)
fill_image UsetheDialogEditor
findfile Dirfunction
fix Fix,Int,Cintfunctions
float CDblFunction
foreach ForEach...Nextstatement
gc AutoCAD.Application.ActiveDocument.PurgeAll
gcd Notprovided
get_attr UsetheDialogEditor
get_tile UsetheDialogEditor
getangle AutoCAD.Application.ActiveDocument.Utility.GetAnglemethod
getcfg AutoCAD.Application.Preferences.propertyproperty
getcname Notprovided
getcorner AutoCAD.Application.ActiveDocument.Utility.GetCornermethod
getdist AutoCAD.Application.ActiveDocument.Utility.GetDistancemethod
getenv AutoCAD.Application.Preferences.propertyproperty
getfiled Usethefiledialog
getint AutoCAD.Application.ActiveDocument.Utility.GetIntegermethod
getkword AutoCAD.Application.ActiveDocument.Utility.GetKeywordmethod
getorient AutoCAD.Application.ActiveDocument.Utility.GetOrientationmethod
getpoint AutoCAD.Application.ActiveDocument.Utility.GetPointmethod
getreal AutoCAD.Application.ActiveDocument.Utility.GetRealmethod
getstring AutoCAD.Application.ActiveDocument.Utility.GetStringmethod
getvar AutoCAD.Application.GetVariablemethod
graphscr AppActivateAutoCAD.Application.Caption
grclear Obsoletefunction
grdraw Notprovided
grread Notprovided
grtext AutoCAD.Application.ActiveDocument.Utility.Prompt
grvecs Notprovided
handent AutoCAD.Application.ActiveDocument.ModelSpace.object.Handleproperty
help SearchforHELPintheonlineHelpindex
if If…Then…Elsestatement
initget AutoCAD.Application.ActiveDocument.Utility.InitializeUserInput
inters AutoCAD.Application.ActiveDocument.Modelspace.object.IntersectWith
itoa Strfunction
lambda Notprovided
last arrayname(UBound(arrayname))
length UBoundfunction
list ReDimstatement
listp IsArrayfunction
load_dialog UsetheDialogEditor
load AutoLISPisnotsupportedthroughAutomation
log Logfunction
logand Andfunction
logior Orfunction
lsh Impfunction
mapcar Notprovided
max Maxfunction
mem Notprovided
member Usecollection
menucmd AutoCAD.Application.MenuBarobject
menugroup AutoCAD.Application.MenuGroupobject
min Minfunction
minusp Use<0syntax
mode_tile UsetheDialogEditor
namedobjdict AutoCAD.Application.ActiveDocument.Dictionariescollection
nentsel AutoCAD.Application.ActiveDocument.SelectionSets.SelectionSet.SelectAtPointmethod
nentselp AutoCAD.Application.ActiveDocument.SelectionSets.SelectionSet.SelectAtPointmethod
new_dialog UsetheDialogEditor
not Usethelogicaloperators
nth Useobject(n)syntax
null IsNullfunction
numberp TypeNamefunction
open Openfunction
or Usethelogicaloperators
osnap Notprovided(YoucanusetheSetVariablemethodtocontroltheOSMODEsystemvariable.)
polar AutoCAD.Application.ActiveDocument.Utility.PolarPointmethod
prin1 AutoCAD.Application.ActiveDocument.Utility.Prompt
princ AutoCAD.Application.ActiveDocument.Utility.Prompt
print AutoCAD.Application.ActiveDocument.Utility.Prompt
progn Notprovided
prompt AutoCAD.Application.ActiveDocument.Utility.Prompt
quit AutoCAD.Application.Quitmethod
quote Notprovided
read Notprovided
read-char Inputfunction
read-line LineInputfunction
redraw AutoCAD.Application.ActiveDocument.Modelspace.object.Updatemethod
regapp AutoCAD.Application.ActiveDocument.RegisteredApplications.Addmethod
rem Modfunction
repeat For… Each,While,
reverse Notprovided
rtos AutoCAD.Application.ActiveDocument.Utility.RealToStringmethod
set Setfunction
set_tile UsetheDialogEditor
setcfg AutoCAD.Application.Preferences.propertyproperty
setfunhelp Notprovided
setq Setfunction
setvar AutoCAD.Application.SetVariablemethod
sin Sinfunction
setview AutoCAD.Application.ActiveDocument.Viewports.Viewport.SetViewmethod
slide_image UsetheDialogEditor
snvalid Notprovided
sqrt Sqrfunction
ssadd AutoCAD.Application.ActiveDocument.SelectionSets.Addmethod
ssdel AutoCAD.Application.ActiveDocument.SelectionSets.SelectionSet.Deletemethod
ssget AutoCAD.Application.ActiveDocument.SelectionSets.SelectionSet.SelectOnScreenmethod
ssgetfirst Notprovided
sslength AutoCAD.Application.ActiveDocument.SelectionSets.SelectionSet.Countmethod
ssmemb CompareIDofobjectwiththeSelectionSetmembers
ssname AutoCAD.Application.ActiveDocument.SelectionSets.SelectionSet.Nameproperty
ssnamex Notprovided
sssetfirst AutoCAD.Application.ActiveDocument.PickfirstSelectionSet
startapp Shellfunction
start_dialog UsetheDialogEditor
start_image UsetheDialogEditor
start_list UsetheDialogEditor
strcase StrConvfunction
strcat &operator
strlen Lenfunction
subst Notprovided
substr Midfunction
tablet Notprovided
tblnext AutoCAD.Application.ActiveDocument.collection_object.Itemmethod
tblobjname AutoCAD.Application.ActiveDocument.collection_object.Namemethod
tblsearch AutoCAD.Application.ActiveDocument.collection_object.Namemethod
term_dialog UsetheDialogEditor
terpri Notprovided
textbox AutoCAD.Application.ActiveDocument.space.object.GetBoundingBoxmethod
textpage Notprovided
textscr Notprovided
trace Notprovided
trans AutoCAD.Application.ActiveDocument.Utility.TranslateCoordinatesmethod
type TypeNamefunction
unload_dialog UsetheDialogEditor
untrace Notprovided
vector_image UsetheDialogEditor
ver AutoCAD.Application.Versionproperty
vports AutoCAD.Application.ActiveDocument.Viewportscollection
wcmatch Likeoperator
while While… Wend
write-char Printfunction
write-line Printfunction
xdroom Notprovided
xdsize Notprovided
zerop Use=0syntax
Pleasesendusyourcommentaboutthispage