Chuong Trinh VBA Cad_ đại học xây dưungj
description
Transcript of Chuong Trinh VBA Cad_ đại học xây dưungj
1. T×m thùc thÓ tån t¹i ®Çu tiªn trong kh«ng gian m« h×nh cña b¶n vÏ
Sub Ch2_FindFirstEntity()' This example returns the first entity in model spaceOn Error Resume NextDim entity As AcadEntity
If ThisDrawing.ModelSpace.count <> 0 ThenSet entity = ThisDrawing.ModelSpace.Item(0)MsgBox entity.ObjectName + _" is the first entity in model space."
ElseMsgBox "There are no objects in model space."
End IfEnd Sub
2. T×m vµ hiÓn thÞ danh s¸ch Layer
Sub Ch2_IterateLayer()' Iterate through the collectionOn Error Resume Next
Dim I As IntegerDim msg As Stringmsg = ""For I = 0 To ThisDrawing.Layers.count - 1
msg = msg + ThisDrawing.Layers.Item(I).Name + vbCrLfNextMsgBox msg
End Sub
3. T×m Layer cã tªn lµ “Mylayer” cã hay kh«ng trong b¶n vÏ
Sub Ch2_FindLayer()' Use the Item method to find a layer named MyLayerOn Error Resume NextDim ABCLayer As AcadLayer
Set ABCLayer = ThisDrawing.Layers("MyLayer")If Err <> 0 Then
MsgBox "The layer 'MyLayer' does not exist."End If
End Sub
4. T¹o mét OBJ trong collection
Dim newLayer as AcadLayerSet newLayer = ThisDrawing.Layers.Add("MyNewLayer")
5. Xo¸ mét OBJ trong collection
Dim ABCLayer as AcadLayerSet ABCLayer = ThisDrawing.Layers.Item("ABC")ABCLayer.Delete
6. T¹o Spline
Sub Ch2_CreateSplineUsingTypedArray()' This example creates a spline object in model space' using the CreateTypedArray method.Dim splineObj As AcadSplineDim startTan As VariantDim endTan As VariantDim fitPoints As VariantDim utilObj As Object ' late bind the Utility objectSet utilObj = ThisDrawing.Utility' Define the Spline ObjectutilObj.CreateTypedArray _startTan, vbDouble, 0.5, 0.5, 0utilObj.CreateTypedArray _endTan, vbDouble, 0.5, 0.5, 0utilObj.CreateTypedArray _
fitPoints, vbDouble, 0, 0, 0, 5, 5, 0, 10, 0, 0
Set splineObj = ThisDrawing.ModelSpace.AddSpline _(fitPoints, startTan, endTan)
' Zoom in on the newly created splineZoomAll
End Sub
7. TÝnh kho¶ng c¸ch gi÷a 2 ®iÓm
Sub Ch2_CalculateDistance()Dim point1 As VariantDim point2 As Variant' Get the points from the userpoint1 = ThisDrawing.Utility.GetPoint _(, vbCrLf & "First point: ")point2 = ThisDrawing.Utility.GetPoint _(point1, vbCrLf & "Second point: ")' Calculate the distance between point1 and point2Dim x As Double, y As Double, z As DoubleDim dist As Double
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))'Display the resulting distanceMsgBox "The distance between the points is: " _& dist, , "Calculate Distance"
End Sub
8. KÕt nèi VB víi AutoCad
Sub Ch2_ConnectToAcad()Dim acadApp As AcadApplicationOn Error Resume NextSet acadApp = GetObject(, "AutoCAD.Application.16")If Err Then
Err.ClearSet acadApp = CreateObject("AutoCAD.Application.16")If Err Then
MsgBox Err.DescriptionExit Sub
End IfEnd IfMsgBox "Now running " + acadApp.Name + _" version " + acadApp.Version
End Sub
9. T¹o line b»ng VBA
Sub Ch2_AddLineVBA()' This example adds a line' in model spaceDim lineObj As AcadLineDim startPoint(0 To 2) As DoubleDim endPoint(0 To 2) As Double' Define the start and end' points for the line
startPoint(0) = 1startPoint(1) = 1startPoint(2) = 0endPoint(0) = 5endPoint(1) = 5endPoint(2) = 0
' Create the line in model spaceSet lineObj = ThisDrawing. _
ModelSpace.AddLine _(startPoint, endPoint)
' Zoom in on the newly created lineZoomAll
End Sub
10. T¹o line b»ng VB
Sub Ch2_AddLineVB()On Error Resume Next' Connect to the AutoCAD applicationDim acadApp As AcadApplicationSet acadApp = GetObject _(, "AutoCAD.Application.16")If Err Then
Err.ClearSet acadApp = CreateObject _("AutoCAD.Application.16")If Err Then
MsgBox Err.DescriptionExit Sub
End IfEnd If' Connect to the AutoCAD drawingDim acadDoc As AcadDocumentSet acadDoc = acadApp.ActiveDocument' Establish the endpoints of the lineDim lineObj As AcadLineDim startPoint(0 To 2) As DoubleDim endPoint(0 To 2) As Double
startPoint(0) = 1startPoint(1) = 1startPoint(2) = 0endPoint(0) = 5endPoint(1) = 5endPoint(2) = 0
' Create a Line object in model spaceSet lineObj = acadDoc.ModelSpace.AddLine _(startPoint, endPoint)ZoomAllacadApp.visible = True
End Sub
11. Më b¶n vÏ
Sub Ch3_OpenDrawing()Dim dwgName As StringdwgName = "c:\campus.dwg"If Dir(dwgName) <> "" Then
ThisDrawing.Application.Documents.Open dwgNameElseMsgBox "File " & dwgName & " does not exist."
End IfEnd Sub
12. T¹o b¶n vÏ míi
Sub Ch3_NewDrawing()Dim docObj As AcadDocumentSet docObj = ThisDrawing.Application.Documents.Add
End Sub
13. Ghi b¶n vÏ hiÖn hµnh
Sub Ch3_SaveActiveDrawing()' Save the active drawing under the current nameThisDrawing.Save' Save the active drawing under a new nameThisDrawing.SaveAs "MyDrawing.dwg"
End Sub
14. KiÓm tra viÖc ghi b¶n vÏ
Sub Ch3_TestIfSaved()If Not (ThisDrawing.Saved) Then
If MsgBox("Do you wish to save this drawing?", _vbYesNo) = vbYes ThenThisDrawing.Save
End IfEnd If
End Sub
15. Cµi ®Æt crosshairs cho b¶n vÏ
Sub Ch2_PrefsSetCursor()' This example sets the crosshairs of the AutoCAD drawing cursor' to full screen.' Access the Preferences objectDim acadPref As AcadPreferencesSet acadPref = ThisDrawing.Application.Preferences' Use the CursorSize property to set the size of the crosshairsacadPref.Display.CursorSize = 100
End Sub
16. HiÓn thÞ thanh cuén cña cö sæ
Sub Ch2_PrefsSetDisplay()' This example enables the screen menu and disables the scroll' bars with the DisplayScreenMenu and DisplayScrollBars' properties.' Access the Preferences objectDim acadPref As AcadPreferencesSet acadPref = ThisDrawing.Application.Preferences' Display the screen menu and disable scroll barsacadPref.Display.DisplayScreenMenu = TrueacadPref.Display.DisplayScrollBars = False
End Sub
17. Cµi ®Æt kÝch thíc cña sæ tr×nh øng dông
Sub Ch3_PositionApplicationWindow()ThisDrawing.Application.WindowTop = 0ThisDrawing.Application.WindowLeft = 0ThisDrawing.Application.width = 400ThisDrawing.Application.height = 400
End Sub
18. Cùc ®¹i cña sæ tr×nh øng dông
Sub Ch3_MaximizeApplicationWindow()ThisDrawing.Application.WindowState = acMax
End Sub
19. Cùc tiÓu cña sæ tr×nh øng dông
Sub Ch3_MinimizeApplicationWindow()ThisDrawing.Application.WindowState = acMin
End Sub
20. KiÓm tra tr¹ng th¸I cña cöa sæ tr×nh øng dông
Sub Ch3_CurrentWindowState()Dim CurrWindowState As IntegerDim msg As StringCurrWindowState = ThisDrawing.Application.WindowStatemsg = Choose(CurrWindowState, "normal", _
"minimized", "maximized")
MsgBox "The application window is " + msgEnd Sub
21. Èn cña sæ tr×nh øng dông hiÖn hµnh
Sub Ch3_HideWindowState()ThisDrawing.Application.Visible = False
End Sub
22. §Æt cña sæ b¶n vÏ
Sub Ch3_SizeDocumentWindow()ThisDrawing.Width = 400ThisDrawing.Height = 400
End Sub
23. Cùc ®¹i ca sæ b¶n vÏ hiÖn hµnh
Sub Ch3_MaximizeDocumentWindow()ThisDrawing.WindowState = acMax
End Sub
24. Cùc tiÓu cña sæ b¶n vÏ hiÖn hµnh
Sub Ch3_MinimizeDocumentWindow()ThisDrawing.WindowState = acMin
End Sub
24. Check tr¹ng th¸I cña sæ b¶n vÏ hiÖn hµnh
Sub Ch3_CurrentWindowState()Dim CurrWindowState As IntegerDim msg As StringCurrWindowState = ThisDrawing.WindowStatemsg = Choose(CurrWindowState, "normal", _"minimized", "maximized")MsgBox "The document window is " + msg
End Sub
25. Zoom cña sæ ®Þnh nghÜa tõ 2 ®iÓm
Sub Ch3_ZoomWindow()' ZoomWindowMsgBox "Perform a ZoomWindow with:" & vbCrLf & _
"1.3, 7.8, 0" & vbCrLf & _"13.7, -2.6, 0", , "ZoomWindow"
Dim point1(0 To 2) As DoubleDim point2(0 To 2) As Doublepoint1(0) = 1.3: point1(1) = 7.8: point1(2) = 0point2(0) = 13.7: point2(1) = -2.6: point2(2) = 0ThisDrawing.Application.ZoomWindow point1, point2' ZoomPickWindowMsgBox "Perform a ZoomPickWindow", , "ZoomPickWindow"ThisDrawing.Application.ZoomPickWindow
End Sub
26. Zoom tû lÖ
Sub Ch3_ZoomScaled()MsgBox "Perform a ZoomScaled using:" & vbCrLf & _"Scale Type: acZoomScaledRelative" & vbCrLf & _"Scale Factor: 2", , "ZoomScaled"Dim scalefactor As DoubleDim scaletype As Integerscalefactor = 2scaletype = acZoomScaledRelativeThisDrawing.Application.ZoomScaled scalefactor, scaletype
End Sub
27. Zoom center – T©m
Sub Ch3_ZoomCenter()MsgBox "Perform a ZoomCenter using:" & vbCrLf & _"Center 3, 3, 0" & vbCrLf & _"Magnification: 10", , "ZoomCenter"Dim Center(0 To 2) As DoubleDim magnification As DoubleCenter(0) = 3: Center(1) = 3: Center(2) = 0magnification = 10ThisDrawing.Application.ZoomCenter Center, magnification
End Sub
28. Zoom ALL-Extents
Sub Ch3_ZoomAll()' ZoomAllMsgBox "Perform a ZoomAll", , "ZoomAll"ThisDrawing.Application.ZoomAll' ZoomExtentsMsgBox "Perform a ZoomExtents", , "ZoomExtents"ThisDrawing.Application.ZoomExtents
End Sub
29. T¹o View mãi
Sub Ch3_AddView()' Add a named view to the views collectionDim viewObj As AcadViewSet viewObj = ThisDrawing.Views.Add("View1")
End Sub
30. Xãa View
Sub Ch3_DeleteView()Dim viewObj As AcadViewSet viewObj = ThisDrawing.Views("View1")' Delete the viewviewObj.Delete
End Sub
31. Xãa tªn View trong collection
Sub Ch3_DeleteViewFromCollection()ThisDrawing.Views("View1").Delete
End Sub
32. Chi ®«I View theo chiÒu ngang
Sub SplitAViewport()' Create a new viewportDim vportObj As AcadViewportSet vportObj = ThisDrawing.Viewports.Add("TEST_VIEWPORT")' Split vportObj into 2 horizontal windowsvportObj.Split acViewport2Horizontal' Now set vportObj to be the active viewportThisDrawing.ActiveViewport = vportObj
End Sub
33. DuyÖt c¸c view port
Sub Ch3_IteratingViewportWindows()' Create a new viewport and make it activeDim vportObj As AcadViewportSet vportObj = ThisDrawing.Viewports.Add("TEST_VIEWPORT")ThisDrawing.ActiveViewport = vportObj' Split vport into 4 windowsvportObj.Split acViewport4' Iterate through the viewports,' highlighting each viewport and displaying' the upper right and lower left corners' for each.Dim vport As AcadViewport
Dim LLCorner As VariantDim URCorner As VariantFor Each vport In ThisDrawing.Viewports
ThisDrawing.ActiveViewport = vportLLCorner = vport.LowerLeftCornerURCorner = vport.UpperRightCornerMsgBox "Viewport: " & vport.Name & " is now active." & _vbCrLf & "Lower left corner: " & _LLCorner(0) & ", " & LLCorner(1) & vbCrLf & _"Upper right corner: " & _URCorner(0) & ", " & URCorner(1)
Next vportEnd Sub
34. Apdate ®å häa lªn mµn h×nh
Sub Ch3_UpdateDisplay()Dim circleObj As AcadCircleDim center(0 To 2) As DoubleDim radius As Doublecenter(0) = 1: center(1) = 1: center(2) = 0radius = 1' Create the circle and then color it redSet circleObj = ThisDrawing.ModelSpace.AddCircle(center, radius)circleObj.Color = acRed' Update the circlecircleObj.Update
End Sub
35. ®Æt view hiÖn hµnh
Sub Ch3_ResetActiveViewport()' Toggle the setting of the grid display' for the active viewportThisDrawing.ActiveViewport.GridOn = _Not (ThisDrawing.ActiveViewport.GridOn)' Reset the active viewportThisDrawing.ActiveViewport = ThisDrawing.ActiveViewport
End Sub
36. §æi ®iÓm chuÈn trong lÖnh xoay
Sub Ch3_ChangeSnapBasePoint()' Turn on the grid for the active viewportThisDrawing.ActiveViewport.GridOn = True' Change the snap base point to 1, 1Dim newBasePoint(0 To 1) As DoublenewBasePoint(0) = 1: newBasePoint(1) = 1ThisDrawing.ActiveViewport.SnapBasePoint = newBasePoint' Change the snap rotation angle to 30 degrees (0.575 radians)Dim rotationAngle As DoublerotationAngle = 0.575ThisDrawing.ActiveViewport.SnapRotationAngle = rotationAngle' reset the viewportThisDrawing.ActiveViewport = ThisDrawing.ActiveViewport
End Sub
37. T¹o Xline trong kh«ng gian m« h×nh
Sub Ch3_AddXLine()Dim xlineObj As AcadXlineDim basePoint(0 To 2) As DoubleDim directionVec(0 To 2) As Double Define the xlinebasePoint(0) = 2#: basePoint(1) = 2#: basePoint(2) = 0#directionVec(0) = 1#: directionVec(1) = 1#: directionVec(2) = 0#' Create the xline in model spaceSet xlineObj = ThisDrawing.ModelSpace.AddXLine _(basePoint, directionVec)ThisDrawing.Application.ZoomAll
End Sub
38. Editer ray line
Sub Ch3_EditRay()Dim rayObj As AcadRayDim basePoint(0 To 2) As DoubleDim secondPoint(0 To 2) As Double' Define the raybasePoint(0) = 3#: basePoint(1) = 3#: basePoint(2) = 0#secondPoint(0) = 4#: secondPoint(1) = 4#: secondPoint(2) = 0#' Creates a Ray object in model spaceSet rayObj = ThisDrawing.ModelSpace.AddRay _(basePoint, secondPoint)ThisDrawing.Application.ZoomAll' Find the current status of the RayMsgBox "The base point of the ray is: " & _rayObj.basePoint(0) & ", " & _rayObj.basePoint(1) & ", " & _rayObj.basePoint(2) & vbCrLf & _"The directional vector for the ray is: " & _rayObj.DirectionVector(0) & ", " & _rayObj.DirectionVector(1) & ", " & _rayObj.DirectionVector(2), , "Edit Ray"' Change the directional vector for the rayDim newVector(0 To 2) As DoublenewVector(0) = -1newVector(1) = 1newVector(2) = 0rayObj.DirectionVector = newVectorThisDrawing.Regen FalseMsgBox "The base point of the ray is: " & _rayObj.basePoint(0) & ", " & _rayObj.basePoint(1) & ", " & _rayObj.basePoint(2) & vbCrLf & _"The directional vector for the ray is: " & _rayObj.DirectionVector(0) & ", " & _rayObj.DirectionVector(1) & ", " & _rayObj.DirectionVector(2), , "Edit Ray"
End Sub
39. §äc kho¶ng c¸ch g÷a 2 ®iÓm
Sub Ch3_GetDistanceBetweenTwoPoints()Dim returnDist As Double' Return the value entered by user. A prompt is provided.returnDist = ThisDrawing.Utility.GetDistance _(, "Pick two points.")MsgBox "The distance between the two points is: " & returnDist
End Sub
40. TÝnh diÖn tÝch
Sub Ch3_CalculateDefinedArea()Dim p1 As VariantDim p2 As VariantDim p3 As VariantDim p4 As VariantDim p5 As Variant' Get the points from the userp1 = ThisDrawing.Utility.GetPoint(, vbCrLf & "First point: ")p2 = ThisDrawing.Utility.GetPoint(p1, vbCrLf & "Second point: ")p3 = ThisDrawing.Utility.GetPoint(p2, vbCrLf & "Third point: ")p4 = ThisDrawing.Utility.GetPoint(p3, vbCrLf & "Fourth point: ")p5 = ThisDrawing.Utility.GetPoint(p4, vbCrLf & "Fifth point: ")' Create the 2D polyline from the pointsDim polyObj As AcadLWPolylineDim vertices(0 To 9) As Doublevertices(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)Set polyObj = ThisDrawing.ModelSpace.AddLightWeightPolyline _(vertices)polyObj.Closed = TrueThisDrawing.Application.ZoomAll' Display the area for the polylineMsgBox "The area defined by the points is " & _polyObj.Area, , "Calculate Defined Area"
End Sub
41. Däc d÷ x©u ký hiÖu
Sub Ch3_GetStringFromUser()Dim retVal As StringretVal = ThisDrawing.Utility.GetString _(1, vbCrLf & "Enter your name: ")MsgBox "The name entered was: " & retVal
End Sub
42. §äc to¹ ®é ®iÓm
Sub Ch3_GetPointsFromUser()Dim startPnt As VariantDim endPnt As VariantDim prompt1 As StringDim prompt2 As Stringprompt1 = vbCrLf & "Enter the start point of the line: "prompt2 = vbCrLf & "Enter the end point of the line: "' Get the first point without entering a base pointstartPnt = ThisDrawing.Utility.GetPoint(, prompt1)' Use the point entered above as the base pointendPnt = ThisDrawing.Utility.GetPoint(startPnt, prompt2)' Create a line using the two points enteredThisDrawing.ModelSpace.AddLine startPnt, endPntThisDrawing.Application.ZoomAll
End Sub
43. §äc tõ khãa lÖnh CAD
Sub Ch3_KeyWord()Dim keyWord As StringThisDrawing.Utility.InitializeUserInput 1, "Line Circle Arc"keyWord = ThisDrawing.Utility.GetKeyword _(vbCrLf & "Enter an option (Line/Circle/Arc): ")MsgBox keyWord, , "GetKeyword Example"
End Sub
44. §äc tõ khãa lÖnh CAD – b¶n 2
Sub Ch3_KeyWord2()Dim keyWord As StringThisDrawing.Utility.InitializeUserInput 0, "Line Circle Arc"keyWord = ThisDrawing.Utility.GetKeyword _(vbCrLf & "Enter an option (Line/Circle/<Arc>): ")If keyWord = "" Then keyWord = "Arc"MsgBox keyWord, , "GetKeyword Example"
End Sub
45. Vµo d÷ liÖu t ngêi dïng
Sub Ch3_UserInput()' The first parameter of InitializeUserInput (6)' restricts input to positive and non-negative' values. The second parameter is the list of' valid keywords.ThisDrawing.Utility.InitializeUserInput 6, "Big Small Regular"' Set the prompt string variableDim promptStr As StringpromptStr = vbCrLf & "Enter the size or (Big/Small/<Regular>):"' At the GetInteger prompt, entering a keyword or pressing
' ENTER without entering a value results in an error. To allow' your application to continue and check for the error' description, you must set the error handler to resume on error.On Error Resume Next' Get the value entered by the userDim returnInteger As IntegerreturnInteger = ThisDrawing.Utility.GetInteger(promptStr)' Check for an error. If the error number matches the' one shown below, then use GetInput to get the returned' string; otherwise, use the value of returnInteger.If Err.Number = -2145320928 Then
Dim returnString As StringDebug.Print Err.DescriptionreturnString = ThisDrawing.Utility.GetInput()If returnString = "" Then 'ENTER returns null string
returnString = "Regular" 'Set to defaultEnd If
Err.ClearElse 'Otherwise,
returnString = returnInteger 'Use the value enteredEnd If' Display the resultMsgBox returnString, , "InitializeUserInput Example"
End Sub
46. T¹o ®èi tîng ®å häa b»ng lÖnh Send
Sub Ch3_SendACommandToAutoCAD()ThisDrawing.SendCommand "_Circle 2,2,0 4 "ThisDrawing.SendCommand "_zoom a "
End Sub
47. Import vµ Exporting
Sub Ch3_ImportingAndExporting()' Create the circle for visual representationDim circleObj As AcadCircleDim centerPt(0 To 2) As DoubleDim radius As DoublecenterPt(0) = 2: centerPt(1) = 2: centerPt(2) = 0radius = 1Set circleObj = ThisDrawing.ModelSpace.AddCircle _(centerPt, radius)ThisDrawing.Application.ZoomAll' Create an empty selection setDim sset As AcadSelectionSetSet sset = ThisDrawing.SelectionSets.Add("NEWSSET")'Export the current drawing to a DXF file in the' AutoCAD temporary file directoryDim tempPath As StringDim exportFile As StringConst dxfname As String = "DXFExprt"tempPath = _ThisDrawing.Application.preferences.Files.TempFilePathexportFile = tempPath & dxfnameThisDrawing.Export exportFile, "DXF", sset' Delete the empty selection setThisDrawing.SelectionSets.Item("NEWSSET").Delete' Open a new drawingThisDrawing.Application.Documents.Add "acad.dwt"' Define the importDim importFile As StringDim insertPoint(0 To 2) As DoubleDim scalefactor As DoubleimportFile = tempPath & dxfname & ".dxf"insertPoint(0) = 0: insertPoint(1) = 0: insertPoint(2) = 0scalefactor = 2#' Import the fileThisDrawing.Import importFile, insertPoint, scalefactorThisDrawing.Application.ZoomAll
End Sub
48. T¹o §êng Polyline trong kh«ng gian m« h×nh
Sub Ch4_AddLightWeightPolyline()Dim plineObj As AcadLWPolylineDim points(0 To 5) As Double' Define the 2D polyline pointspoints(0) = 2: points(1) = 4points(2) = 4: points(3) = 2points(4) = 6: points(5) = 4' Create a light weight Polyline object in model spaceSet plineObj = ThisDrawing.ModelSpace. _AddLightWeightPolyline(points)ThisDrawing.Application.ZoomAll
End Sub
49. T¹o ®êng Spline
Sub Ch4_CreateSpline()' This example creates a spline object in model space.' Declare the variables neededDim splineObj As AcadSplineDim startTan(0 To 2) As DoubleDim endTan(0 To 2) As DoubleDim fitPoints(0 To 8) As Double' Define the variablesstartTan(0) = 0.5: startTan(1) = 0.5: startTan(2) = 0endTan(0) = 0.5: endTan(1) = 0.5: endTan(2) = 0fitPoints(0) = 1: fitPoints(1) = 1: fitPoints(2) = 0fitPoints(3) = 5: fitPoints(4) = 5: fitPoints(5) = 0fitPoints(6) = 10: fitPoints(7) = 0: fitPoints(8) = 0' Create the splineSet splineObj = ThisDrawing.ModelSpace.AddSpline _(fitPoints, startTan, endTan)ZoomAll
End Sub
50. Khëi t¹o ®iÓm
Sub Ch4_CreatePoint()Dim pointObj As AcadPointDim location(0 To 2) As Double' Define the location of the pointlocation(0) = 5#: location(1) = 5#: location(2) = 0#' Create the pointSet pointObj = ThisDrawing.ModelSpace.AddPoint(location)ThisDrawing.SetVariable "PDMODE", 34ThisDrawing.SetVariable "PDSIZE", 1ZoomAll
End Sub
51. Khëi t¹o SolidSub Ch4_CreateSolid()
Dim solidObj As AcadSolidDim point1(0 To 2) As DoubleDim point2(0 To 2) As DoubleDim point3(0 To 2) As DoubleDim point4(0 To 2) As Double' Define the solidpoint1(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#' Create the solid object in model spaceSet solidObj = ThisDrawing.ModelSpace.AddSolid _(point1, point2, point3, point4)
ZoomAllEnd Sub
52. Khëi t¹o Region
Sub Ch4_CreateRegion()' Define an array to hold the' boundaries of the region.Dim curves(0 To 0) As AcadCircle' Create a circle to become a' boundary for the region.Dim center(0 To 2) As DoubleDim radius As Doublecenter(0) = 2center(1) = 2center(2) = 0radius = 5#Set curves(0) = ThisDrawing.ModelSpace.AddCircle _(center, radius)' Create the regionDim regionObj As VariantregionObj = ThisDrawing.ModelSpace.AddRegion(curves)ZoomAll
End Sub
53. Khëi t¹o Composite Region
Sub Ch4_CreateCompositeRegions()' Create two circles, one representing a room,' the other a pillar in the center of the roomDim RoomObjects(0 To 1) As AcadCircleDim center(0 To 2) As DoubleDim radius As Doublecenter(0) = 4center(1) = 4center(2) = 0radius = 2#Set RoomObjects(0) = ThisDrawing.ModelSpace. _AddCircle(center, radius)radius = 1#Set RoomObjects(1) = ThisDrawing.ModelSpace. _AddCircle(center, radius)' Create a region from the two circlesDim regions As Variantregions = ThisDrawing.ModelSpace.AddRegion(RoomObjects)' Copy the regions into the region variables for ease of useDim RoundRoomObj As AcadRegionDim PillarObj As AcadRegionIf regions(0).Area > regions(1).Area Then
' The first region is the roomSet RoundRoomObj = regions(0)Set PillarObj = regions(1)
Else' The first region is the pillarSet PillarObj = regions(0)Set RoundRoomObj = regions(1)
End If' Subtract the pillar space from the floor space to' get a region that represents the total carpet area.RoundRoomObj.Boolean acSubtraction, PillarObj' Use the Area property to determine the total carpet areaMsgBox "The carpet area is: " & RoundRoomObj.Area
End Sub
54. T¹o Hatch
Sub Ch4_CreateHatch()Dim hatchObj As AcadHatchDim patternName As StringDim PatternType As Long
Dim bAssociativity As Boolean' Define the hatchpatternName = "ANSI31"PatternType = 0bAssociativity = True' Create the associative Hatch objectSet hatchObj = ThisDrawing.ModelSpace.AddHatch _(PatternType, patternName, bAssociativity)' Create the outer boundary for the hatch. (a circle)Dim outerLoop(0 To 0) As AcadEntityDim center(0 To 2) As DoubleDim radius As Doublecenter(0) = 3: center(1) = 3: center(2) = 0radius = 1Set outerLoop(0) = ThisDrawing.ModelSpace. _AddCircle(center, radius)' Append the outerboundary to the hatch' object, and display the hatchhatchObj.AppendOuterLoop (outerLoop)hatchObj.EvaluateThisDrawing.Regen True
End Sub
55. T¹o Selection
Sub Ch4_CreateSelectionSet()Dim selectionSet1 As AcadSelectionSetSet selectionSet1 = ThisDrawing.SelectionSets. _Add("NewSelectionSet")
End Sub
56. Chän ®èi tîng ®å häa ®a vµo Selection set
Sub Ch4_AddToASelectionSet()' Create a new selection setDim sset As AcadSelectionSetSet sset = ThisDrawing.SelectionSets.Add("SS1")' Prompt the user to select objects' and add them to the selection set.' To finish selecting, press ENTER.sset.SelectOnScreen
End Sub
57. T×m läc Mtext
Sub Ch4_FilterMtext()Dim sstext As AcadSelectionSetDim FilterType(0) As IntegerDim FilterData(0) As VariantSet sstext = ThisDrawing.SelectionSets.Add("SS2")FilterType(0) = 0FilterData(0) = "Circle"sstext.SelectOnScreen FilterType, FilterData
End Sub
58. Läc t×m ®êng trßn mÇu xanh t¹i layer 0
Sub Ch4_FilterBlueCircleOnLayer0()Dim sstext As AcadSelectionSetDim FilterType(2) As IntegerDim FilterData(2) As VariantSet sstext = ThisDrawing.SelectionSets.Add("SS4")FilterType(0) = 0FilterData(0) = "Circle"FilterType(1) = 62FilterData(1) = acBlueFilterType(2) = 8FilterData(2) = "0"sstext.SelectOnScreen FilterType, FilterData
End Sub
59. Läc theo Relationnal
Sub Ch4_FilterRelational()Dim sstext As AcadSelectionSetDim FilterType(2) As IntegerDim FilterData(2) As VariantSet sstext = ThisDrawing.SelectionSets.Add("SS5")FilterType(0) = 0FilterData(0) = "Circle"FilterType(1) = -4FilterData(1) = ">="FilterType(2) = 40FilterData(2) = 5#sstext.SelectOnScreen FilterType, FilterData
End Sub
60. Läc theo Text , Mtext
Sub Ch4_FilterOrTest()Dim sstext As AcadSelectionSetDim FilterType(3) As IntegerDim FilterData(3) As VariantSet sstext = ThisDrawing.SelectionSets.Add("SS6")FilterType(0) = -4FilterData(0) = "<or"FilterType(1) = 0FilterData(1) = "TEXT"FilterType(2) = 0FilterData(2) = "MTEXT"FilterType(3) = -4FilterData(3) = "or>"sstext.SelectOnScreen FilterType, FilterData
End Sub
61. Läc theo Polygon
Sub Ch4_FilterPolygonWildcard()Dim sstext As AcadSelectionSetDim FilterType(1) As IntegerDim FilterData(1) As VariantDim pointsArray(0 To 11) As DoubleDim mode As Integermode = acSelectionSetWindowPolygonpointsArray(0) = -12#: pointsArray(1) = -7#: pointsArray(2) = 0pointsArray(3) = -12#: pointsArray(4) = 10#: pointsArray(5) = 0pointsArray(6) = 10#: pointsArray(7) = 10#: pointsArray(8) = 0pointsArray(9) = 10#: pointsArray(10) = -7#: pointsArray(11) = 0Set sstext = ThisDrawing.SelectionSets.Add("SS10")FilterType(0) = 0FilterData(0) = "MTEXT"FilterType(1) = 1FilterData(1) = "*The*"sstext.SelectByPolygon mode, pointsArray, FilterType, FilterData
End Sub
62. Läc theo Xdata
Sub Ch4_FilterXdata()Dim sstext As AcadSelectionSetDim mode As IntegerDim pointsArray(0 To 11) As Doublemode = acSelectionSetWindowPolygonpointsArray(0) = -12#: pointsArray(1) = -7#: pointsArray(2) = 0pointsArray(3) = -12#: pointsArray(4) = 10#: pointsArray(5) = 0pointsArray(6) = 10#: pointsArray(7) = 10#: pointsArray(8) = 0pointsArray(9) = 10#: pointsArray(10) = -7#: pointsArray(11) = 0Dim FilterType(1) As IntegerDim FilterData(1) As VariantSet sstext = ThisDrawing.SelectionSets.Add("SS9")FilterType(0) = 0FilterData(0) = "Circle"
FilterType(1) = 1001FilterData(1) = "MY_APP"sstext.SelectByPolygon mode, pointsArray, FilterType, FilterData
End Sub
63. List danh s¸ch ®èi tîng chän trong Selection Set
Sub GetObjInSet()Dim selset As AcadSelectionSetSet selset = ThisDrawing.SelectionSets("SS10")MsgBox ("Selection set " & selset.Name & " contains " & _selset.Count & " items")
End Sub
64. List danh s¸ch Selection Set trong b¶n vÏ
Sub ListSelectionSets()Dim selsetCollection As AcadSelectionSetsDim selset As AcadSelectionSetDim ent As ObjectDim i, j As IntegerSet selsetCollection = ThisDrawing.SelectionSets' Find each selection set in the drawingi = 0For Each selset In selsetCollection
MsgBox "Selection set " & CStr(i) & " is: " & selset.Name' Now find each object in the selection set, and say what it isj = 0
For Each ent In selsetMsgBox "Item " & CStr(j + 1) & " in " & selset.Name _& "is: " & ent.EntityNamej = j + 1
Nexti = i + 1
NextEnd Sub
65. §æi tªn layer
Sub Ch4_RenamingLayer()' Create a layerDim layerObj As AcadLayerSet layerObj = ThisDrawing.Layers.Add("NewLayer")' Change the name of the layerlayerObj.Name = "MyLayer"
End Sub
66. Copy ®êng trßn
Sub Ch4_CopyCircleObjects()Dim DOC1 As AcadDocumentDim circleObj1 As AcadCircleDim circleObj2 As AcadCircleDim circleObj1Copy As AcadCircleDim circleObj2Copy As AcadCircleDim centerPoint(0 To 2) As DoubleDim radius1 As DoubleDim radius2 As DoubleDim radius1Copy As DoubleDim radius2Copy As DoubleDim objCollection(0 To 1) As ObjectDim retObjects As Variant' Define the Circle objectcenterPoint(0) = 0: centerPoint(1) = 0: centerPoint(2) = 0radius1 = 5#: radius2 = 7#radius1Copy = 1#: radius2Copy = 2#' Create a new drawingSet DOC1 = ThisDrawing.Application.Documents.Add' Add two circles to the drawingSet circleObj1 = DOC1.ModelSpace.AddCircle _(centerPoint, radius1)
Set circleObj2 = DOC1.ModelSpace.AddCircle _(centerPoint, radius2)ZoomAll' Put the objects to be copied into a form' compatible with CopyObjectsSet objCollection(0) = circleObj1Set objCollection(1) = circleObj2' Copy object and get back a collection of' the new objects (copies)retObjects = DOC1.CopyObjects(objCollection)' Get newly created object and apply' new properties to the copiesSet circleObj1Copy = retObjects(0)Set circleObj2Copy = retObjects(1)circleObj1Copy.radius = radius1CopycircleObj1Copy.Color = acRedcircleObj2Copy.radius = radius2CopycircleObj2Copy.Color = acRedZoomAll
End Sub
67. Copy sang b¶n vÏ míi
Sub Ch4_Copy_to_New_Drawing()Dim DOC0 As AcadDocumentDim circleObj1 As AcadCircle, circleObj2 As AcadCircleDim centerPoint(0 To 2) As DoubleDim radius1 As Double, radius2 As DoubleDim radius1Copy As Double, radius2Copy As DoubleDim objCollection(0 To 1) As ObjectDim retObjects As Variant' Define the Circle objectcenterPoint(0) = 0: centerPoint(1) = 0: centerPoint(2) = 0radius1 = 5#: radius2 = 7#radius1Copy = 1#: radius2Copy = 2#' Add two circles to the current drawingSet circleObj1 = ThisDrawing.ModelSpace.AddCircle _(centerPoint, radius1)Set circleObj2 = ThisDrawing.ModelSpace.AddCircle _(centerPoint, radius2)ThisDrawing.Application.ZoomAll' Save pointer to the current drawingSet DOC0 = ThisDrawing.Application.ActiveDocument' Copy objects' First put the objects to be copied into a form compatible' with CopyObjectsSet objCollection(0) = circleObj1Set objCollection(1) = circleObj2' Create a new drawing and point to its model spaceDim Doc1MSpace As AcadModelSpaceDim DOC1 As AcadDocumentSet DOC1 = Documents.AddSet Doc1MSpace = DOC1.ModelSpace' Copy the objects into the model space of the new drawing. A' collection of the new (copied) objects is returned.retObjects = DOC0.CopyObjects(objCollection, Doc1MSpace)Dim circleObj1Copy As AcadCircle, circleObj2Copy As AcadCircle' Get the newly created object collection and apply new' properties to the copies.Set circleObj1Copy = retObjects(0)Set circleObj2Copy = retObjects(1)circleObj1Copy.radius = radius1CopycircleObj1Copy.Color = acRedcircleObj2Copy.radius = radius2CopycircleObj2Copy.Color = acRedThisDrawing.Application.ZoomAllMsgBox "Circles copied."
End Sub
68. OffsetPolyline
Sub Ch4_OffsetPolyline()' Create the polylineDim plineObj As AcadLWPolylineDim points(0 To 11) As Doublepoints(0) = 1: points(1) = 1points(2) = 1: points(3) = 2points(4) = 2: points(5) = 2points(6) = 3: points(7) = 2points(8) = 4: points(9) = 4points(10) = 4: points(11) = 1Set plineObj = ThisDrawing.ModelSpace. _AddLightWeightPolyline(points)plineObj.Closed = TrueZoomAll' Offset the polylineDim offsetObj As VariantoffsetObj = plineObj.Offset(0.25)ZoomAll
End Sub
69. Lay ®èi xøng ®êng Polyline
Sub Ch4_MirrorPolyline()' Create the polylineDim plineObj As AcadLWPolylineDim points(0 To 11) As Doublepoints(0) = 1: points(1) = 1points(2) = 1: points(3) = 2points(4) = 2: points(5) = 2points(6) = 3: points(7) = 2points(8) = 4: points(9) = 4points(10) = 4: points(11) = 1Set plineObj = ThisDrawing.ModelSpace. _AddLightWeightPolyline(points)plineObj.Closed = TrueZoomAll' Define the mirror axisDim point1(0 To 2) As DoubleDim point2(0 To 2) As Doublepoint1(0) = 0: point1(1) = 4.25: point1(2) = 0point2(0) = 4: point2(1) = 4.25: point2(2) = 0' Mirror the polylineDim mirrorObj As AcadLWPolylineSet mirrorObj = plineObj.Mirror(point1, point2)Dim col As New AcadAcCmColorCall col.SetRGB(125, 175, 235)mirrorObj.TrueColor = colZoomAll
End Sub
70. ARRAY POLA
Sub Ch4_ArrayingACircle()' Create the circleDim circleObj As AcadCircleDim center(0 To 2) As DoubleDim radius As Doublecenter(0) = 2#: center(1) = 2#: center(2) = 0#radius = 1Set circleObj = ThisDrawing.ModelSpace. _AddCircle(center, radius)ZoomAll' Define the polar arrayDim noOfObjects As IntegerDim angleToFill As DoubleDim basePnt(0 To 2) As DoublenoOfObjects = 4angleToFill = 3.14 ' 180 degreesbasePnt(0) = 4#: basePnt(1) = 4#: basePnt(2) = 0#
' The following example will create 4 copies' of an object by rotating and copying it about' the point (3,3,0).Dim retObj As VariantretObj = circleObj.ArrayPolar _(noOfObjects, angleToFill, basePnt)ZoomAll
End Sub
71. ARRAY rectangular
Sub Ch4_ArrayRectangularExample()' Create the circleDim circleObj As AcadCircleDim center(0 To 2) As DoubleDim radius As Doublecenter(0) = 2#: center(1) = 2#: center(2) = 0#radius = 0.5Set circleObj = ThisDrawing.ModelSpace. _AddCircle(center, radius)ZoomAll' Define the rectangular arrayDim numberOfRows As LongDim numberOfColumns As LongDim numberOfLevels As LongDim distanceBwtnRows As DoubleDim distanceBwtnColumns As DoubleDim distanceBwtnLevels As DoublenumberOfRows = 5numberOfColumns = 5numberOfLevels = 2distanceBwtnRows = 1distanceBwtnColumns = 1distanceBwtnLevels = 1' Create the array of objectsDim retObj As VariantretObj = circleObj.ArrayRectangular _(numberOfRows, numberOfColumns, numberOfLevels, _distanceBwtnRows, distanceBwtnColumns, distanceBwtnLevels)ZoomAll
End Sub
72. Move ®êng trßn
Sub Ch4_MoveCircle()' Create the circleDim circleObj As AcadCircleDim center(0 To 2) As DoubleDim radius As Doublecenter(0) = 2#: center(1) = 2#: center(2) = 0#radius = 0.5Set circleObj = ThisDrawing.ModelSpace. _AddCircle(center, radius)ZoomAll' Define the points that make up the move vector.' The move vector will move the circle 2 units' along the x axis.Dim point1(0 To 2) As DoubleDim point2(0 To 2) As Doublepoint1(0) = 0: point1(1) = 0: point1(2) = 0point2(0) = 2: point2(1) = 0: point2(2) = 0' Move the circlecircleObj.Move point1, point2circleObj.Update
End Sub
73. Xoay Polyline
Sub Ch4_RotatePolyline()' Create the polylineDim plineObj As AcadLWPolyline
Dim points(0 To 11) As Doublepoints(0) = 1: points(1) = 2points(2) = 1: points(3) = 3points(4) = 2: points(5) = 3points(6) = 3: points(7) = 3points(8) = 4: points(9) = 4points(10) = 4: points(11) = 2Set plineObj = ThisDrawing.ModelSpace. _AddLightWeightPolyline(points)plineObj.Closed = TrueZoomAll' Define the rotation of 45 degrees about a' base point of (4, 4.25, 0)Dim basePoint(0 To 2) As DoubleDim rotationAngle As DoublebasePoint(0) = 4: basePoint(1) = 4.25: basePoint(2) = 0rotationAngle = 0.7853981 ' 45 degrees' Rotate the polylineplineObj.Rotate basePoint, rotationAngleplineObj.Update
End Sub
74. Xo¸ Polyline
Sub Ch4_DeletePolyline()' Create the polylineDim lwpolyObj As AcadLWPolylineDim vertices(0 To 5) As Doublevertices(0) = 2: vertices(1) = 4vertices(2) = 4: vertices(3) = 2vertices(4) = 6: vertices(5) = 4Set lwpolyObj = ThisDrawing.ModelSpace. _AddLightWeightPolyline(vertices)ZoomAll' Erase the polylinelwpolyObj.DeleteThisDrawing.Regen acActiveViewport
End Sub
75. Tû lÖ Polyline
Sub Ch4_ScalePolyline()' Create the polylineDim plineObj As AcadLWPolylineDim points(0 To 11) As Doublepoints(0) = 1: points(1) = 2points(2) = 1: points(3) = 3points(4) = 2: points(5) = 3points(6) = 3: points(7) = 3points(8) = 4: points(9) = 4points(10) = 4: points(11) = 2Set plineObj = ThisDrawing.ModelSpace. _AddLightWeightPolyline(points)plineObj.Closed = TrueZoomAll' Define the scaleDim basePoint(0 To 2) As DoubleDim scalefactor As DoublebasePoint(0) = 4: basePoint(1) = 4.25: basePoint(2) = 0scalefactor = 0.5' Scale the polylineplineObj.ScaleEntity basePoint, scalefactorplineObj.Update
End Sub
76. Transform
Sub Ch4_TransformBy()' Create a line
Dim lineObj As AcadLineDim startPt(0 To 2) As DoubleDim endPt(0 To 2) As DoublestartPt(0) = 2startPt(1) = 1startPt(2) = 0endPt(0) = 5endPt(1) = 1endPt(2) = 0Set lineObj = ThisDrawing.ModelSpace. _AddLine(startPt, endPt)ZoomAll' Initialize the transMat variable with a' transformation matrix that will rotate' an object by 90 degrees about the point(0,0,0)Dim transMat(0 To 3, 0 To 3) As DoubletransMat(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#' Transform the line using the defined transformation matrixlineObj.TransformBy transMatlineObj.Update
End Sub
77. LengthenLine
Sub Ch4_LengthenLine()' Define and create the lineDim lineObj As AcadLineDim startPoint(0 To 2) As DoubleDim endPoint(0 To 2) As DoublestartPoint(0) = 0startPoint(1) = 0startPoint(2) = 0endPoint(0) = 1endPoint(1) = 1endPoint(2) = 1Set lineObj = ThisDrawing.ModelSpace. _AddLine(startPoint, endPoint)lineObj.Update' Lengthen the line by changing the' endpoint to 4, 4, 4endPoint(0) = 4endPoint(1) = 4endPoint(2) = 4lineObj.endPoint = endPointlineObj.Update
End Sub
78. Tëi Polyline
Sub Ch4_ExplodePolyline()Dim plineObj As AcadLWPolylineDim points(0 To 11) As Double' Define the 2D polyline pointspoints(0) = 1: points(1) = 1points(2) = 1: points(3) = 2points(4) = 2: points(5) = 2points(6) = 3: points(7) = 2points(8) = 4: points(9) = 4points(10) = 4: points(11) = 1' Create a light weight Polyline objectSet plineObj = ThisDrawing.ModelSpace. _AddLightWeightPolyline(points)
' Set the bulge on one segment to vary the' type of objects in the polylineplineObj.SetBulge 3, -0.5plineObj.Update' Explode the polylineDim explodedObjects As VariantexplodedObjects = plineObj.Explode' Loop through the exploded objects' and display a message box with' the type of each objectDim I As IntegerFor I = 0 To UBound(explodedObjects)
explodedObjects(I).Color = acRedexplodedObjects(I).UpdateMsgBox "Exploded Object " & I & ": " & _explodedObjects(I).ObjectNameexplodedObjects(I).Color = acByLayerexplodedObjects(I).Update
NextEnd Sub
79. Edite Polyline
Sub Ch4_EditPolyline()Dim plineObj As AcadLWPolylineDim points(0 To 9) As Double' Define the 2D polyline pointspoints(0) = 1: points(1) = 1points(2) = 1: points(3) = 2points(4) = 2: points(5) = 2points(6) = 3: points(7) = 2points(8) = 4: points(9) = 4' Create a light weight Polyline objectSet plineObj = ThisDrawing.ModelSpace. _AddLightWeightPolyline(points)' Add a bulge to segment 3plineObj.SetBulge 3, -0.5' Define the new vertexDim newVertex(0 To 1) As DoublenewVertex(0) = 4: newVertex(1) = 1' Add the vertex to the polylineplineObj.AddVertex 5, newVertex' Set the width of the new segmentplineObj.SetWidth 4, 0.1, 0.5' Close the polylineplineObj.Closed = TrueplineObj.Update
End Sub
80. Thay doi diem khong che Spline
Sub Ch4_ChangeSplineControlPoint()' Create the splineDim splineObj As AcadSplineDim startTan(0 To 2) As DoubleDim endTan(0 To 2) As DoubleDim fitPoints(0 To 8) As DoublestartTan(0) = 0.5: startTan(1) = 0.5: startTan(2) = 0endTan(0) = 0.5: endTan(1) = 0.5: endTan(2) = 0fitPoints(0) = 1: fitPoints(1) = 1: fitPoints(2) = 0fitPoints(3) = 5: fitPoints(4) = 5: fitPoints(5) = 0fitPoints(6) = 10: fitPoints(7) = 0: fitPoints(8) = 0Set splineObj = ThisDrawing.ModelSpace. _AddSpline(fitPoints, startTan, endTan)splineObj.Update' Change the coordinate of the first fit pointDim controlPoint(0 To 2) As DoublecontrolPoint(0) = 0controlPoint(1) = 3controlPoint(2) = 0
splineObj.SetControlPoint 0, controlPointsplineObj.Update
End Sub
81. Dieu chinh Hatch
Sub Ch4_AppendInnerLoopToHatch()Dim hatchObj As AcadHatchDim patternName As StringDim PatternType As LongDim bAssociativity As Boolean' Define and create the hatchpatternName = "ANSI31"PatternType = 0bAssociativity = TrueSet hatchObj = ThisDrawing.ModelSpace. _AddHatch(PatternType, patternName, bAssociativity)' Create the outer loop for the hatch.Dim outerLoop(0 To 1) As AcadEntityDim center(0 To 2) As DoubleDim radius As DoubleDim startAngle As DoubleDim endAngle As Doublecenter(0) = 5: center(1) = 3: center(2) = 0radius = 3startAngle = 0endAngle = 3.141592Set outerLoop(0) = ThisDrawing.ModelSpace. _AddArc(center, radius, startAngle, endAngle)Set outerLoop(1) = ThisDrawing.ModelSpace. _AddLine(outerLoop(0).startPoint, outerLoop(0).endPoint)' Append the outer loop to the hatch objecthatchObj.AppendOuterLoop (outerLoop)' Create a circle as the inner loop for the hatch.Dim innerLoop(0) As AcadEntitycenter(0) = 5: center(1) = 4.5: center(2) = 0radius = 1Set innerLoop(0) = ThisDrawing.ModelSpace. _AddCircle(center, radius)' Append the circle as an inner loop to the hatchhatchObj.AppendInnerLoop (innerLoop)' Evaluate and display the hatchhatchObj.EvaluateThisDrawing.Regen True
End Sub
82. Thay doi chinh Hatch
Sub Ch4_ChangeHatchPatternSpace()Dim hatchObj As AcadHatchDim patternName As StringDim PatternType As LongDim bAssociativity As Boolean' Define the hatchpatternName = "ANSI31"PatternType = 0bAssociativity = True' Create the associative Hatch objectSet hatchObj = ThisDrawing.ModelSpace. _AddHatch(PatternType, patternName, bAssociativity)' Create the outer loop for the hatch.Dim outerLoop(0 To 0) As AcadEntityDim center(0 To 2) As DoubleDim radius As Doublecenter(0) = 5center(1) = 3center(2) = 0radius = 3Set outerLoop(0) = ThisDrawing.ModelSpace. _AddCircle(center, radius)
hatchObj.AppendOuterLoop (outerLoop)hatchObj.Evaluate' Change the spacing of the hatch pattern by' adding 2 to the current spacinghatchObj.patternSpace = hatchObj.patternSpace + 2hatchObj.EvaluateThisDrawing.Regen True
End Sub
83. Hien thi layer
Sub Ch4_IteratingLayers()Dim layerNames As StringDim entry As AcadLayerlayerNames = ""For Each entry In ThisDrawing.LayerslayerNames = layerNames + entry.Name + vbCrLfNextMsgBox "The layers in this drawing are: " + _vbCrLf + layerNames
End Sub
84. Tao layer moi
Sub Ch4_NewLayer()' Create a circleDim circleObj As AcadCircleDim center(0 To 2) As DoubleDim radius As Doublecenter(0) = 2: center(1) = 2: center(2) = 0radius = 1Set circleObj = ThisDrawing.ModelSpace. _AddCircle(center, radius)' Assign the circle the color "ByLayer" so' that the circle will automatically pick' up the color of the layer on which it residescircleObj.Color = acByLayer' Create a new layer called "ABC"Dim layerObj As AcadLayerSet layerObj = ThisDrawing.Layers.Add("ABC")' Assign the "ABC" layer the color redlayerObj.Color = acRed' Assign the circle to the "ABC" layercircleObj.Layer = "ABC"circleObj.Update
End Sub
85. An hien layer
Sub Ch4_LayerInvisible()' Create a circleDim circleObj As AcadCircleDim center(0 To 2) As DoubleDim radius As Doublecenter(0) = 2: center(1) = 2: center(2) = 0radius = 1Set circleObj = ThisDrawing.ModelSpace. _AddCircle(center, radius)circleObj.Color = acByLayer' Create a new layer called "ABC"Dim layerObj As AcadLayerSet layerObj = ThisDrawing.Layers.Add("ABC")layerObj.Color = acRed' Assign the circle to the "ABC" layercircleObj.Layer = "ABC"circleObj.Update' Turn off layer "ABC"layerObj.LayerOn = FalseThisDrawing.Regen acActiveViewport
End Sub
86. Dong dac layer
Sub Ch4_LayerFreeze()' Create a new layer called "ABC"Dim layerObj As AcadLayerSet layerObj = ThisDrawing.Layers.Add("ABC")' Freeze layer "ABC"layerObj.Freeze = True
End Sub
87. Khoa layer
Sub Ch4_LayerLock()' Create a new layer called "ABC"Dim layerObj As AcadLayerSet layerObj = ThisDrawing.Layers.Add("ABC")' Lock layer "ABC"layerObj.Lock = True
End Sub
88. Load dang net
Sub Ch4_LoadLinetype()On Error GoTo ERRORHANDLERDim linetypeName As StringlinetypeName = "CENTER"' Load "CENTER" line type from acad.lin fileThisDrawing.Linetypes.Load linetypeName, "acad.lin"Exit Sub
ERRORHANDLER:MsgBox Err.Description
End Sub
89. Thay doi he so ty le dang net
Sub Ch4_ChangeLinetypeScale()' Save the current linetypeSet currLineType = ThisDrawing.ActiveLinetype' Change the active linetype to Border, so the scale change will' be visible.' First see if the Border linetype is already loadedOn Error Resume Next 'Turn on error trappingThisDrawing.ActiveLinetype = ThisDrawing.Linetypes.Item("BORDER")If Err.Number = -2145386476 Then
' Error indicates linetype is not currently loaded, so load it.ThisDrawing.Linetypes.Load "BORDER", "acad.lin"ThisDrawing.ActiveLinetype = _ThisDrawing.Linetypes.Item("BORDER")
End IfOn Error GoTo 0 'Turn off error trapping' Create a circle object in model spaceDim center(0 To 2) As DoubleDim radius As DoubleDim circleObj As AcadCirclecenter(0) = 2center(1) = 2center(2) = 0radius = 4Set circleObj = ThisDrawing.ModelSpace.AddCircle(center, radius)circleObj.UpdateMsgBox ("Here is the circle with the original linetype")' Set the linetype scale of a circle to 3circleObj.LinetypeScale = 3#circleObj.UpdateMsgBox ("Here is the circle with the new linetype")' Restore original active linetypeThisDrawing.ActiveLinetype = currLineType
End Sub
90. G¸n ®èi tîng vµo layer
Sub Ch4_MoveObjectNewLayer()' Create a circleDim circleObj As AcadCircleDim center(0 To 2) As DoubleDim radius As Doublecenter(0) = 2: center(1) = 2: center(2) = 0radius = 1Set circleObj = ThisDrawing.ModelSpace. _AddCircle(center, radius)' Create a new layer called "ABC"Dim layerObj As AcadLayerSet layerObj = ThisDrawing.Layers.Add("ABC")' Assign the circle to the "ABC" layercircleObj.Layer = "ABC"circleObj.Update
End Sub
91. Thay mµu cña ®èi tîng
Sub Ch4_ColorCircle()Dim color As AcadAcCmColorSet color = _AcadApplication.GetInterfaceObject("AutoCAD.AcCmColor.16")Call color.SetRGB(80, 100, 244)Dim circleObj As AcadCircleDim centerPoint(0 To 2) As DoubleDim radius As DoublecenterPoint(0) = 0#: centerPoint(1) = 0#: centerPoint(2) = 0#radius = 5#Set circleObj = _ThisDrawing.ModelSpace.AddCircle(centerPoint, radius)circleObj.TrueColor = colorZoomAll
End Sub
92. Doi dang net
Sub Ch4_ChangeCircleLinetype()On Error Resume Next' Create a circleDim circleObj As AcadCircleDim center(0 To 2) As DoubleDim radius As Doublecenter(0) = 2: center(1) = 2: center(2) = 0radius = 1Set circleObj = ThisDrawing.ModelSpace. _AddCircle(center, radius)Dim linetypeName As StringlinetypeName = "CENTER"' Load "CENTER" line type from acad.lin fileThisDrawing.Linetypes.Load linetypeName, "acad.lin"If Err.Description <> "" Then MsgBox Err.Description' Assign the circle the linetype "CENTER"circleObj.Linetype = "CENTER"circleObj.Update
End Sub
93. List cac Layer tai ban ve
Sub Ch4_ListStates()On Error Resume NextDim oLSMDict As AcadDictionaryDim XRec As ObjectDim layerstateNames As StringlayerstateNames = ""' Get the ACAD_LAYERSTATES dictionary, which is in the
' extension dictionary in the Layers object.Set oLSMDict = ThisDrawing.Layers. _GetExtensionDictionary.Item("ACAD_LAYERSTATES")' List the name of each saved layer setting. Settings are' stored as XRecords in the dictionary.For Each XRec In oLSMDictlayerstateNames = layerstateNames + XRec.Name + vbCrLfNext XRecMsgBox "The saved layer settings in this drawing are: " + _vbCrLf + layerstateNames
End Sub
94. Xac lap trang thai LayerStateManager
Dim oLSM As AcadLayerStateManagerSet oLSM = ThisDrawing.Application. _GetInterfaceObject("AutoCAD.AcadLayerStateManager.16")
95. luu mau, dang net cua Layer
Sub Ch4_SaveLayerColorAndLinetype()Dim oLSM As AcadLayerStateManager' Access the LayerStateManager objectSet oLSM = ThisDrawing.Application. _GetInterfaceObject("AutoCAD.AcadLayerStateManager.16")' Associate the current drawing database with LayerStateManageroLSM.SetDatabase ThisDrawing.DatabaseoLSM.Save "ColorLinetype", acLsColor + acLsLineType
End Sub
96. Doi ten va ghi cac xac lap Layer
Sub Ch4_RenameLayerSettings()Dim oLSM As AcadLayerStateManagerSet oLSM = ThisDrawing.Application. _GetInterfaceObject("AutoCAD.AcadLayerStateManager.16")oLSM.SetDatabase ThisDrawing.DatabaseoLSM.Rename "ColorLinetype", "OldColorLinetype"
End Sub
97. xoa xac lap mau, dang net cua Layer
Sub Ch4_DeleteColorAndLinetype()Dim oLSM As AcadLayerStateManagerSet oLSM = ThisDrawing.Application. _GetInterfaceObject("AutoCAD.AcadLayerStateManager.16")oLSM.SetDatabase ThisDrawing.DatabaseoLSM.Delete "ColorLinetype"
End Sub
98. Khoi dong dang net, mau cua Layer
Sub Ch4_RestoreLayerSettings()Dim oLSM As AcadLayerStateManagerSet oLSM = ThisDrawing.Application. _GetInterfaceObject("AutoCAD.AcadLayerStateManager.16")oLSM.SetDatabase ThisDrawing.DatabaseoLSM.Restore "ColorLinetype"
End Sub
99. Export cac xac lap cua Layer
Sub Ch4_ExportLayerSettings()
Dim oLSM As AcadLayerStateManagerSet oLSM = ThisDrawing.Application. _GetInterfaceObject("AutoCAD.AcadLayerStateManager.16")oLSM.SetDatabase ThisDrawing.DatabaseoLSM.Export "ColorLinetype", "c:\my documents\ColorLType.las"
End Sub
100. Import cac xac lap Layer
Sub Ch4_ImportLayerSettings()Dim oLSM As AcadLayerStateManagerSet oLSM = ThisDrawing.Application. _GetInterfaceObject("AutoCAD.AcadLayerStateManager.16")oLSM.SetDatabase ThisDrawing.Database' If the drawing you're importing to does not contain' all the linetypes referenced in the saved settings,' an error is returned. The import is completed, though,' and the default linetype is used.On Error Resume NextoLSM.Import "c:\my documents\ColorLType.las"If Err.Number = -2145386359 Then
' Error indicates a linetype is not definedMsgBox ("One or more linetypes specified in the imported " + _"settings is not defined in your drawing")
End IfOn Error GoTo 0
End Sub
101. Update Text font
Sub Ch4_UpdateTextFont()MsgBox ("Look at the text now...")Dim typeFace As StringDim SavetypeFace As StringDim Bold As BooleanDim Italic As BooleanDim charSet As LongDim PitchandFamily As Long' Get the current settings to fill in the' default values for the SetFont methodThisDrawing.ActiveTextStyle.GetFont typeFace, _Bold, Italic, charSet, PitchandFamily' Change the typeface for the fontSavetypeFace = typeFacetypeFace = "PlayBill"ThisDrawing.ActiveTextStyle.SetFont typeFace, _Bold, Italic, charSet, PitchandFamilyThisDrawing.Regen acActiveViewportMsgBox ("Now see how it looks after changing the font...")'Restore the original typefaceThisDrawing.ActiveTextStyle.SetFont SavetypeFace, _Bold, Italic, charSet, PitchandFamilyThisDrawing.Regen acActiveViewport
End Sub
102. Thay doi Font
Sub Ch4_ChangeFontFiles()ThisDrawing.ActiveTextStyle.BigFontFile = _"C:/AutoCAD/Fonts/bigfont.shx"ThisDrawing.ActiveTextStyle.fontFile = _"C:/AutoCAD/Fonts/italic.shx"
End Sub
103. Doi chieu cao chu
Sub Ch4_ChangeTextHeight()Dim textObj As AcadText
Dim textString As StringDim insertionPoint(0 To 2) As DoubleDim height As Double' Define the text objecttextString = "Hello, World."insertionPoint(0) = 3insertionPoint(1) = 3insertionPoint(2) = 0height = 0.5' Create the text object in model spaceSet textObj = ThisDrawing.ModelSpace. _AddText(textString, insertionPoint, height)' Change the value of the Height to 1textObj.height = 1textObj.Update
End Sub
104. Xoay nghieng chu
Sub Ch4_ObliqueText()Dim textObj As AcadTextDim textString As StringDim insertionPoint(0 To 2) As DoubleDim height As Double' Define the text objecttextString = "Hello, World."insertionPoint(0) = 3insertionPoint(1) = 3insertionPoint(2) = 0height = 0.5' Create the text object in model spaceSet textObj = ThisDrawing.ModelSpace. _AddText(textString, insertionPoint, height)' Change the value of the ObliqueAngle' to 45 degrees (.707 radians)textObj.ObliqueAngle = 0.707textObj.Update
End Sub
105. ChangingTextGenerationFlag
Sub Ch4_ChangingTextGenerationFlag()Dim textObj As AcadTextDim textString As StringDim insertionPoint(0 To 2) As DoubleDim height As Double' Create the text objecttextString = "Hello, World."insertionPoint(0) = 3insertionPoint(1) = 3insertionPoint(2) = 0height = 0.5Set textObj = ThisDrawing.ModelSpace. _AddText(textString, insertionPoint, height)' Change the value of the TextGenerationFlagtextObj.TextGenerationFlag = acTextFlagBackwardtextObj.Update
End Sub
106. Tao Text
Sub Ch4_CreateText()Dim textObj As AcadTextDim textString As StringDim insertionPoint(0 To 2) As DoubleDim height As Double' Create the text objecttextString = "Hello, World."insertionPoint(0) = 2
insertionPoint(1) = 2insertionPoint(2) = 0height = 0.5Set textObj = ThisDrawing.ModelSpace. _AddText(textString, insertionPoint, height)textObj.Update
End Sub
107. Tua Text
Sub Ch4_TextAlignment()Dim textObj As AcadTextDim textString As StringDim insertionPoint(0 To 2) As DoubleDim height As Double' Define the new Text objecttextString = "Hello, World."insertionPoint(0) = 3insertionPoint(1) = 3insertionPoint(2) = 0height = 0.5' Create the Text object in model spaceSet textObj = ThisDrawing.ModelSpace. _AddText(textString, insertionPoint, height)' Create a point over the text alignment point,' so we can better visualize the alignment processDim pointObj As AcadPointDim alignmentPoint(0 To 2) As DoublealignmentPoint(0) = 3alignmentPoint(1) = 3alignmentPoint(2) = 0Set pointObj = ThisDrawing.ModelSpace. _AddPoint(alignmentPoint)pointObj.Color = acRed' Set the point style to crosshairThisDrawing.SetVariable "PDMODE", 2' Align the text to the LefttextObj.Alignment = acAlignmentLeftThisDrawing.Regen acActiveViewportMsgBox "The Text object is now aligned left"' Align the text to the CentertextObj.Alignment = acAlignmentCenter' Align the text to the point (necessary for' all but left aligned text.)textObj.TextAlignmentPoint = alignmentPointThisDrawing.Regen acActiveViewportMsgBox "The Text object is now centered"' Align the text to the RighttextObj.Alignment = acAlignmentRightThisDrawing.Regen acActiveViewportMsgBox "The Text object is now aligned right"
End Sub
108. Tao MText
Sub Ch4_CreateMText()Dim mtextObj As AcadMTextDim insertPoint(0 To 2) As DoubleDim width As DoubleDim textString As StringinsertPoint(0) = 2insertPoint(1) = 2insertPoint(2) = 0width = 4textString = "This is a text string for the mtext object."' Create a text Object in model spaceSet mtextObj = ThisDrawing.ModelSpace. _AddMText(insertPoint, width, textString)ZoomAll
End Sub
109. FormatMText
Sub Ch4_FormatMText()Dim mtextObj As AcadMTextDim insertPoint(0 To 2) As DoubleDim width As DoubleDim textString As StringinsertPoint(0) = 2insertPoint(1) = 2insertPoint(2) = 0width = 4' Define the ASCII characters for the control charactersDim OB As Long ' Open Bracket {Dim CB As Long ' Close Bracket }Dim BS As Long ' Back Slash \Dim FS As Long ' Forward Slash /Dim SC As Long ' Semicolon ;OB = Asc("{")CB = Asc("}")BS = Asc("\")FS = Asc("/")SC = Asc(";")' Assign the text string the following line of control' characters and text characters:' {{\H1.5x; Big text}\A2; over text\A1;/\A0; under text}textString = Chr(OB) + Chr(OB) + Chr(BS) + "H1.5x" _+ Chr(SC) + "Big text" + Chr(CB) + Chr(BS) + "A2" _+ Chr(SC) + "over text" + Chr(BS) + "A1" + Chr(SC) _+ Chr(FS) + Chr(BS) + "A0" + Chr(SC) + "under text" _+ Chr(CB)' Create a text Object in model spaceSet mtextObj = ThisDrawing.ModelSpace. _AddMText(insertPoint, width, textString)ZoomAll
End Sub
110. Tao RadialDimension
Sub Ch5_CreateRadialDimension()Dim dimObj As AcadDimRadialDim center(0 To 2) As DoubleDim chordPoint(0 To 2) As DoubleDim leaderLen As Integer' Define the dimensioncenter(0) = 0center(1) = 0center(2) = 0chordPoint(0) = 5chordPoint(1) = 5chordPoint(2) = 0leaderLen = 5' Create the radial dimension in model spaceSet dimObj = ThisDrawing.ModelSpace. _AddDimRadial(center, chordPoint, leaderLen)ZoomAll
End Sub
111. Tao AngularDimension
Sub Ch5_CreateAngularDimension()Dim dimObj As AcadDimAngularDim angVert(0 To 2) As DoubleDim FirstPoint(0 To 2) As DoubleDim SecondPoint(0 To 2) As DoubleDim TextPoint(0 To 2) As Double' Define the dimension
angVert(0) = 0angVert(1) = 5angVert(2) = 0FirstPoint(0) = 1FirstPoint(1) = 7FirstPoint(2) = 0SecondPoint(0) = 1SecondPoint(1) = 3SecondPoint(2) = 0TextPoint(0) = 3TextPoint(1) = 5TextPoint(2) = 0' Create the angular dimension in model spaceSet dimObj = ThisDrawing.ModelSpace. _AddDimAngular(angVert, FirstPoint, SecondPoint, TextPoint)ZoomAll
End Sub
112. Tao OrdinateDimension
Sub Ch5_CreatingOrdinateDimension()Dim dimObj As AcadDimOrdinateDim definingPoint(0 To 2) As DoubleDim leaderEndPoint(0 To 2) As DoubleDim useXAxis As Long' Define the dimensiondefiningPoint(0) = 5definingPoint(1) = 5definingPoint(2) = 0leaderEndPoint(0) = 10leaderEndPoint(1) = 5leaderEndPoint(2) = 0useXAxis = 5' Create an ordinate dimension in model spaceSet dimObj = ThisDrawing.ModelSpace. _AddDimOrdinate(definingPoint, _leaderEndPoint, useXAxis)ZoomAll
End Sub
113. Doi DimensionText
Sub Ch5_OverrideDimensionText()Dim dimObj As AcadDimAlignedDim point1(0 To 2) As DoubleDim point2(0 To 2) As DoubleDim location(0 To 2) As Double' Define the dimensionpoint1(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#' Create an aligned dimension object in model spaceSet dimObj = ThisDrawing.ModelSpace. _AddDimAligned(point1, point2, location)' Change the text string for the dimensiondimObj.TextOverride = "The value is <>"dimObj.Update
End Sub
114. CopyDimStyles
Sub Ch5_CopyDimStyles()Dim newStyle1 As AcadDimStyleDim newStyle2 As AcadDimStyleDim newStyle3 As AcadDimStyleSet newStyle1 = ThisDrawing.DimStyles.Add _("Style 1 copied from a dim")Call newStyle1.CopyFrom(ThisDrawing.ModelSpace(0))Set newStyle2 = ThisDrawing.DimStyles.Add _
("Style 2 copied from Style 1")Call newStyle2.CopyFrom(ThisDrawing.DimStyles.Item _("Style 1 copied from a dim"))Set newStyle2 = ThisDrawing.DimStyles.Add _("Style 3 copied from the running drawing values")Call newStyle2.CopyFrom(ThisDrawing)
End Sub
115. AddTextSuffix
Sub Ch5_AddTextSuffix()Dim dimObj As AcadDimAlignedDim point1(0 To 2) As DoubleDim point2(0 To 2) As DoubleDim location(0 To 2) As DoubleDim suffix As String' Define the dimensionpoint1(0) = 0: point1(1) = 5: point1(2) = 0point2(0) = 5: point2(1) = 5: point2(2) = 0location(0) = 5: location(1) = 7: location(2) = 0' Create an aligned dimension object in model spaceSet dimObj = ThisDrawing.ModelSpace. _AddDimAligned(point1, point2, location)ThisDrawing.Application.ZoomAll' Allow the user to change the text suffix for the dimensionsuffix = InputBox("Enter a new text suffix for the dimension" _, "Set Dimension Suffix", ":SUFFIX")' Apply the change to the dimensiondimObj.TextSuffix = suffixThisDrawing.Regen acAllViewports
End Sub
116. Tao CreateLeader
Sub Ch5_CreateLeader()Dim leaderObj As AcadLeaderDim points(0 To 8) As DoubleDim leaderType As IntegerDim annotationObject As AcadObjectpoints(0) = 0: points(1) = 0: points(2) = 0points(3) = 4: points(4) = 4: points(5) = 0points(6) = 4: points(7) = 5: points(8) = 0leaderType = acLineWithArrowSet annotationObject = Nothing' Create the leader object in model spaceSet leaderObj = ThisDrawing.ModelSpace. _AddLeader(points, annotationObject, leaderType)ZoomAll
End Sub
117. AddAnnotation
Sub Ch5_AddAnnotation()Dim leaderObj As AcadLeaderDim mtextObj As AcadMTextDim points(0 To 8) As DoubleDim insertionPoint(0 To 2) As DoubleDim width As DoubleDim leaderType As IntegerDim annotationObject As ObjectDim textString As String, msg As String' Create the MText object in model spacetextString = "Hello, World."insertionPoint(0) = 5insertionPoint(1) = 5insertionPoint(2) = 0width = 2Set mtextObj = ThisDrawing.ModelSpace. _AddMText(insertionPoint, width, textString)
' Data for Leaderpoints(0) = 0: points(1) = 0: points(2) = 0points(3) = 4: points(4) = 4: points(5) = 0points(6) = 4: points(7) = 5: points(8) = 0leaderType = acLineWithArrow' Create the Leader object in model space and associate' the MText object with the leaderSet annotationObject = mtextObjSet leaderObj = ThisDrawing.ModelSpace. _AddLeader(points, annotationObject, leaderType)ZoomAll
End Sub
118. CreateTolerance
Sub Ch5_CreateTolerance()Dim toleranceObj As AcadToleranceDim textString As StringDim insertionPoint(0 To 2) As DoubleDim direction(0 To 2) As Double' Define the tolerance objecttextString = "Here is the Feature Control Frame"insertionPoint(0) = 5insertionPoint(1) = 5insertionPoint(2) = 0direction(0) = 1direction(1) = 1direction(2) = 0' Create the tolerance object in model spaceSet toleranceObj = ThisDrawing.ModelSpace. _AddTolerance(textString, insertionPoint, direction)ZoomAll
End Sub
119. InsertMenu
Sub Ch6_InsertMenu()' Define a variable for the current menu groupDim currMenuGroup As AcadMenuGroupSet currMenuGroup = ThisDrawing.Application. _MenuGroups.Item(0)' Create a new menuDim newMenu As AcadPopupMenuSet newMenu = currMenuGroup.Menus.Add("TestMenu")' Declare the variables for the menu itemDim newMenuItem As AcadPopupMenuItemDim openMacro As String' Assign the macro string the VB equivalent of' "ESC ESC _open " and create the menu itemopenMacro = Chr(vbKeyEscape) + Chr(vbKeyEscape) + "_open "Set newMenuItem = newMenu.AddMenuItem(newMenu.Count + 1, _"Open", openMacro)' Display the menu on the menu barcurrMenuGroup.Menus.InsertMenuInMenuBar "TestMenu", ""
End Sub
120. MoveMenu
Sub Ch6_ ()' Define a variable to hold the menu to be movedDim moveMenu As AcadPopupMenuDim MyMenuBar As AcadMenuBarSet MyMenuBar = ThisDrawing.Application.menuBar' Set moveMenu equal to the first menu displayed' on the menu barSet moveMenu = MyMenuBar.Item(0)' Remove the first menu from the menu barMyMenuBar.Item(0).RemoveFromMenuBar' Add the menu back into the menu bar
' in the last position on the barmoveMenu.InsertInMenuBar (MyMenuBar.count)
End Sub
121. CreateMenu
Sub Ch6_CreateMenu()Dim currMenuGroup As AcadMenuGroupSet currMenuGroup = ThisDrawing.Application.MenuGroups.Item(0)' Create the new menuDim newMenu As AcadPopupMenuSet newMenu = currMenuGroup.Menus.Add("TestMenu")
End Sub
122. AddAMenuItem
Sub Ch6_AddAMenuItem()Dim currMenuGroup As AcadMenuGroupSet currMenuGroup = ThisDrawing.Application.MenuGroups.Item(0)' Create the new menuDim newMenu As AcadPopupMenuSet newMenu = currMenuGroup.Menus.Add("TestMenu")' Add a menu item to the new menuDim newMenuItem As AcadPopupMenuItemDim openMacro As String' Assign the macro the VBA equivalent of "ESC ESC _open "openMacro = Chr(vbKeyEscape) + Chr(vbKeyEscape) + "_open "Set newMenuItem = newMenu.AddMenuItem _(newMenu.count + 1, "Open", openMacro)' Display the menu on the menu barnewMenu.InsertInMenuBar _(ThisDrawing.Application.menuBar.count + 1)
End Sub
123. AddAMenuItem
Sub Ch6_AddAMenuItem()Dim currMenuGroup As AcadMenuGroupSet currMenuGroup = ThisDrawing.Application.MenuGroups.Item(0)' Create the new menuDim newMenu As AcadPopupMenuSet newMenu = currMenuGroup.Menus.Add _("Te" + Chr(Asc("&")) + "stMenu")' Add a menu item to the new menuDim newMenuItem As AcadPopupMenuItemDim openMacro As String' Assign the macro the VBA equivalent of "ESC ESC _open "openMacro = Chr(vbKeyEscape) + Chr(vbKeyEscape) + "_open "Set newMenuItem = newMenu.AddMenuItem _(newMenu.count + 1, Chr(Asc("&")) _+ "Open", openMacro)' Display the menu on the menu barnewMenu.InsertInMenuBar _(ThisDrawing.Application.menuBar.count + 1)
End Sub
124. AddASubMenu
Sub Ch6_AddASubMenu()Dim currMenuGroup As AcadMenuGroupSet currMenuGroup = ThisDrawing.Application.MenuGroups.Item(0)' Create the new menuDim newMenu As AcadPopupMenuSet newMenu = currMenuGroup.Menus.Add("TestMenu")' Add the submenuDim FileSubMenu As AcadPopupMenuSet FileSubMenu = newMenu.AddSubMenu("", "OpenFile")' Add a menu item to the sub menu
Dim newMenuItem As AcadPopupMenuItemDim openMacro As String' Assign the macro the VB equivalent of "ESC ESC _open "openMacro = Chr(vbKeyEscape) + Chr(vbKeyEscape) + "_open "Set newMenuItem = FileSubMenu.AddMenuItem _(newMenu.count + 1, "Open", openMacro)' Display the menu on the menu barnewMenu.InsertInMenuBar _(ThisDrawing.Application.menuBar.count + 1)
End Sub
125. DeleteMenuItem
Sub Ch6_DeleteMenuItem()Dim LastMenu As AcadPopupMenuSet LastMenu = ThisDrawing.Application.menuBar. _Item(ThisDrawing.Application.menuBar.count - 1)' Add a menu itemDim newMenuItem As AcadPopupMenuItemDim openMacro As String' Assign the macro the VB equivalent of "ESC ESC _open "openMacro = Chr(vbKeyEscape) + Chr(vbKeyEscape) + "_open "Set newMenuItem = LastMenu.AddMenuItem _(LastMenu.count + 1, "Open", openMacro)' Remove the menu item from the menunewMenuItem.Delete
End Sub
126. DisableMenuItem
Sub Ch6_DisableMenuItem()Dim currMenuGroup As AcadMenuGroupSet currMenuGroup = ThisDrawing.Application.MenuGroups.Item(0)' Create the new menuDim newMenu As AcadPopupMenuSet newMenu = currMenuGroup.Menus.Add("TestMenu")' Add two menu items and a menu separator to the new menuDim MenuEnable As AcadPopupMenuItemDim MenuDisable As AcadPopupMenuItemDim MenuSeparator As AcadPopupMenuItemDim openMacro As String' Assign the macro the VB equivalent of "ESC ESC _open "openMacro = Chr(vbKeyEscape) + Chr(vbKeyEscape) + "_open "Set MenuEnable = newMenu.AddMenuItem _(newMenu.count + 1, "OpenEnabled", openMacro)Set MenuSeparator = newMenu.AddSeparator("")Set MenuDisable = newMenu.AddMenuItem _(newMenu.count + 1, "OpenDisabled", openMacro)' Disable the second menu itemMenuDisable.Enable = False' Display the menu on the menu barnewMenu.InsertInMenuBar _(ThisDrawing.Application.menuBar.count + 1)
End Sub
127. CreateToolbar
Sub Ch6_CreateToolbar()Dim currMenuGroup As AcadMenuGroupSet currMenuGroup = ThisDrawing.Application.MenuGroups.Item(0)' Create the new toolbarDim newToolbar As AcadToolbarSet newToolbar = currMenuGroup.Toolbars.Add("TestToolbar")
End Sub
128. AddButton
Sub Ch6_AddButton()
Dim currMenuGroup As AcadMenuGroupSet currMenuGroup = ThisDrawing.Application.MenuGroups.Item(0)' Create the new toolbarDim newToolbar As AcadToolbarSet newToolbar = currMenuGroup.Toolbars.Add("TestToolbar")' Add a button to the new toolbarDim newButton As AcadToolbarItemDim openMacro As String' Assign the macro the VB equivalent of "ESC ESC _open "openMacro = Chr(vbKeyEscape) + Chr(vbKeyEscape) + "_open "Set newButton = newToolbar.AddToolbarButton _("", "NewButton", "Open a file.", openMacro)
End Sub
129. GetButtonImages
Sub Ch6_GetButtonImages()Dim Button As AcadToolbarItemDim Toolbar0 As AcadToolbarDim MenuGroup0 As AcadMenuGroupDim SmallButtonName As StringDim LargeButtonName As StringDim msg As StringDim ButtonType As String' Get the first toolbar in the first menu groupSet MenuGroup0 = ThisDrawing.Application. _MenuGroups.Item(0)Set Toolbar0 = MenuGroup0.Toolbars.Item(0)' Clear the string variablesSmallButtonName = ""LargeButtonName = ""' Create a header for the message box and' display the toolbar to be queriedmsg = "Toolbar: " + Toolbar0.Name + vbCrLfToolbar0.Visible = True' Iterate through the toolbar and collect data' for each button in the toolbar. If the toolbar is' a normal button or a flyout, collect the small' and large button names for the button.For Each Button In Toolbar0ButtonType = Choose(Button.Type + 1, "Button", _"Separator", "Control", "Flyout")msg = msg & ButtonType & ": "If Button.Type = acToolbarButton Or _Button.Type = acToolbarFlyout ThenButton.GetBitmaps SmallButtonName, _LargeButtonNamemsg = msg + SmallButtonName + ", " _+ LargeButtonNameEnd Ifmsg = msg + vbCrLfNext Button' Display the resultsMsgBox msg
End Sub
130. AddFlyoutButton
Sub Ch6_AddFlyoutButton()Dim currMenuGroup As AcadMenuGroupSet currMenuGroup = ThisDrawing.Application. _MenuGroups.Item(0)' Create the first toolbarDim FirstToolbar As AcadToolbarSet FirstToolbar = currMenuGroup.Toolbars. _Add("FirstToolbar")' Add a flyout button to the first menu on the menu barDim FlyoutButton As AcadToolbarItemSet FlyoutButton = FirstToolbar.AddToolbarButton _
("", "Flyout", "Demonstrates a flyout button", _"OPEN", True)' Create the second toolbar. This will be attached to' the first toolbar via the flyout button.Dim SecondToolbar As AcadToolbarSet SecondToolbar = currMenuGroup.Toolbars. _Add("SecondToolbar")' Add a button to the next toolbarDim newButton As AcadToolbarItemDim openMacro As String' Assign the macro the VB equivalent of "ESC ESC _open "openMacro = Chr(vbKeyEscape) + Chr(vbKeyEscape) + "_open "Set newButton = SecondToolbar.AddToolbarButton _("", "NewButton", "Open a file.", openMacro)' Attach the second toolbar to the flyout' button on the first toolbarFlyoutButton.AttachToolbarToFlyout currMenuGroup.Name, _SecondToolbar.Name' Display the first toolbar, hide the second toolbarFirstToolbar.Visible = TrueSecondToolbar.Visible = False
End Sub
131. DockToolbar
Sub Ch6_DockToolbar()Dim currMenuGroup As AcadMenuGroupSet currMenuGroup = ThisDrawing.Application. _MenuGroups.Item(0)' Create the new toolbarDim newToolbar As AcadToolbarSet newToolbar = currMenuGroup.Toolbars. _Add("TestToolbar")' Add three buttons to the new toolbar.' All three buttons will have the same macro attached.Dim newButton1 As AcadToolbarItemDim newButton2 As AcadToolbarItemDim newButton3 As AcadToolbarItemDim openMacro As String' Assign the macro the VB equivalent of "ESC ESC _open "openMacro = Chr(vbKeyEscape) + Chr(vbKeyEscape) + "_open "Set newButton1 = newToolbar.AddToolbarButton _("", "NewButton1", "Open a file.", openMacro)Set newButton2 = newToolbar.AddToolbarButton _("", "NewButton2", "Open a file.", openMacro)Set newButton3 = newToolbar.AddToolbarButton _("", "NewButton3", "Open a file.", openMacro)' Display the toolbarnewToolbar.Visible = True' Dock the toolbar to the left of the screen.newToolbar.Dock acToolbarDockLeft
End Sub
132. AddHelp
Sub Ch6_AddHelp()Dim currMenuGroup As AcadMenuGroupSet currMenuGroup = ThisDrawing.Application.MenuGroups.Item(0)' Create the new menuDim newMenu As AcadPopupMenuSet newMenu = currMenuGroup.Menus.Add _("Te" + Chr(Asc("&")) + "stMenu")' Add a menu item to the new menuDim newMenuItem As AcadPopupMenuItemDim openMacro As String' Assign the macro the VBA equivalent of "ESC ESC _open "openMacro = Chr(vbKeyEscape) + Chr(vbKeyEscape) + "_open "' Create the menu item
Set newMenuItem = newMenu.AddMenuItem _(newMenu.count + 1, Chr(Asc("&")) _+ "Open", openMacro)' Add the status line help to the menu itemnewMenuItem.HelpString = "Opens an AutoCAD drawing file."' Display the menu on the menu barnewMenu.InsertInMenuBar _(ThisDrawing.Application.menuBar.count + 1)
End Sub
133. AddMenuItemToshortcutMenu
Sub Ch6_AddMenuItemToshortcutMenu()Dim currMenuGroup As AcadMenuGroupSet currMenuGroup = ThisDrawing.Application.MenuGroups.Item(0)' Find the shortcut menu and assign it to the' shortcutMenu variableDim scMenu As AcadPopupMenuDim entry As AcadPopupMenuFor Each entry In currMenuGroup.MenusIf entry.shortcutMenu = True ThenSet scMenu = entryEnd IfNext entry' Add a menu item to the shortcut menuDim newMenuItem As AcadPopupMenuItemDim openMacro As String' Assign the macro the VBA equivalent of "ESC ESC _open "openMacro = Chr(vbKeyEscape) + Chr(vbKeyEscape) + "_open "Set newMenuItem = scMenu.AddMenuItem _("", Chr(Asc("&")) _+ "OpenDWG", openMacro)
End Sub
134. Prompt to continue when a drawing is dropped into AutoCAD
Public WithEvents ACADApp As AcadApplicationSub Example_AcadApplication_Events()
' This example intializes the public variable (ACADApp)' which will be used to intercept AcadApplication Events'' Run this procedure FIRST!' We could get the application from the ThisDocument' object, but that would require having a drawing open,' so we grab it from the system.Set ACADApp = GetObject(, "AutoCAD.Application.16")
End SubPrivate Sub ACADApp_BeginFileDrop _
(ByVal FileName As String, Cancel As Boolean)' This example intercepts an Application BeginFileDrop event.'' This event is triggered when a drawing file is dragged' into AutoCAD.'' To trigger this example event:' 1) Make sure to run the example that initializes' the public variable (named ACADApp) linked to this event.'' 2) Drag an AutoCAD drawing file into the AutoCAD' application from either the Windows Desktop' or Windows Explorer' Use the "Cancel" variable to stop the loading of the' dragged file, and the "FileName" variable to notify' the user which file is about to be dragged in.If MsgBox("AutoCAD is about to load " & FileName & vbCrLf _
& "Do you want to continue loading this file?", _vbYesNoCancel + vbQuestion) <> vbYes ThenCancel = True
End If
End Sub
135. Prompt to continue when a drawing is dropped into AutoCAD
Public WithEvents ACADApp As AcadApplicationSub Example_AcadApplication_Events()
' This example intializes the public variable (ACADApp)' which will be used to intercept AcadApplication Events'' Run this procedure FIRST!' We could get the application from the ThisDocument' object, but that would require having a drawing open,' so we grab it from the system.Set ACADApp = GetObject(, "AutoCAD.Application.16")
End SubPrivate Sub ACADApp_BeginFileDrop _
(ByVal FileName As String, Cancel As Boolean)' This example intercepts an Application BeginFileDrop event.'' This event is triggered when a drawing file is dragged' into AutoCAD.'' To trigger this example event:' 1) Make sure to run the example that initializes' the public variable (named ACADApp) linked to this event.'' 2) Drag an AutoCAD drawing file into the AutoCAD' application from either the Windows Desktop' or Windows Explorer' Use the "Cancel" variable to stop the loading of the' dragged file, and the "FileName" variable to notify' the user which file is about to be dragged in.If MsgBox("AutoCAD is about to load " & FileName & vbCrLf _
& "Do you want to continue loading this file?", _vbYesNoCancel + vbQuestion) <> vbYes ThenCancel = True
End IfEnd Sub
136. Update the shortcut menu at the BeginShortcutMenuDefault and EndShortcutMenu events
Private Sub AcadDocument_BeginShortcutMenuDefault _(ShortcutMenu As AutoCAD.IAcadPopupMenu)On Error Resume Next' Add a menu item to the cursor menuDim newMenuItem As AcadPopupMenuItemDim openMacro As StringopenMacro = Chr(vbKeyEscape) + Chr(vbKeyEscape) + "_open "Set newMenuItem = ShortcutMenu.AddMenuItem _(0, Chr(Asc("&")) _+ "OpenDWG", openMacro)End SubPrivate Sub AcadDocument_EndShortcutMenu _(ShortcutMenu As AutoCAD.IAcadPopupMenu)On Error Resume NextShortcutMenu.Item("OpenDWG").Delete
End Sub
137. Display the area of a closed polyline whenever the polyline is updated
Public WithEvents PLine As AcadLWPolylineSub CreatePLineWithEvents()
' This example creates a light weight polylineDim points(0 To 9) As Doublepoints(0) = 1: points(1) = 1
points(2) = 1: points(3) = 2points(4) = 2: points(5) = 2points(6) = 3: points(7) = 3points(8) = 3: points(9) = 2Set PLine = ThisDrawing.ModelSpace. _AddLightWeightPolyline(points)PLine.Closed = TrueThisDrawing.Application.ZoomAll
End SubPrivate Sub PLine_Modified _
(ByVal pObject As AutoCAD.IAcadObject)' This event is triggered when the polyline is resized.' If the polyline is deleted the modified event is still' triggered, so we use the error handler to avoid' reading data from a deleted object.On Error GoTo ERRORHANDLER
MsgBox "The area of " & pObject.ObjectName & " is: " _& pObject.AreaExit Sub
ERRORHANDLER:MsgBox Err.Description
End Sub
138. Polyline_2D_3DSub Ch8_Polyline_2D_3D()
Dim pline2DObj As AcadLWPolylineDim pline3DObj As AcadPolylineDim points2D(0 To 5) As DoubleDim points3D(0 To 8) As Double' Define three 2D polyline pointspoints2D(0) = 1: points2D(1) = 1points2D(2) = 1: points2D(3) = 2points2D(4) = 2: points2D(5) = 2' Define three 3D polyline pointspoints3D(0) = 1: points3D(1) = 1: points3D(2) = 0points3D(3) = 2: points3D(4) = 1: points3D(5) = 0points3D(6) = 2: points3D(7) = 2: points3D(8) = 0' Create the 2D light weight PolylineSet pline2DObj = ThisDrawing.ModelSpace. _AddLightWeightPolyline(points2D)pline2DObj.Color = acRedpline2DObj.Update' Create the 3D polylineSet pline3DObj = ThisDrawing.ModelSpace. _AddPolyline(points3D)pline3DObj.Color = acBluepline3DObj.Update' Query the coordinates of the polylinesDim get2Dpts As VariantDim get3Dpts As Variantget2Dpts = pline2DObj.Coordinatesget3Dpts = pline3DObj.Coordinates' Display the coordinatesMsgBox ("2D polyline (red): " & vbCrLf & _
get2Dpts(0) & ", " & get2Dpts(1) & vbCrLf & _get2Dpts(2) & ", " & get2Dpts(3) & vbCrLf & _get2Dpts(4) & ", " & get2Dpts(5))
MsgBox ("3D polyline (blue): " & vbCrLf & _get3Dpts(0) & ", " & get3Dpts(1) & ", " & _get3Dpts(2) & vbCrLf & _get3Dpts(3) & ", " & get3Dpts(4) & ", " & _get3Dpts(5) & vbCrLf & _get3Dpts(6) & ", " & get3Dpts(7) & ", " & _get3Dpts(8))
End Sub
139. NewUCS
Sub Ch8_NewUCS()
' Define the variables we will needDim ucsObj As AcadUCSDim origin(0 To 2) As DoubleDim xAxisPnt(0 To 2) As DoubleDim yAxisPnt(0 To 2) As Double' Define the UCS pointsorigin(0) = 4: origin(1) = 5: origin(2) = 3xAxisPnt(0) = 5: xAxisPnt(1) = 5: xAxisPnt(2) = 3yAxisPnt(0) = 4: yAxisPnt(1) = 6: yAxisPnt(2) = 3' Add the UCS to the' UserCoordinatesSystems collectionSet ucsObj = ThisDrawing.UserCoordinateSystems. _Add(origin, xAxisPnt, yAxisPnt, "New_UCS")' Display the UCS iconThisDrawing.ActiveViewport.UCSIconAtOrigin = TrueThisDrawing.ActiveViewport.UCSIconOn = True' Make the new UCS the active UCSThisDrawing.ActiveUCS = ucsObjMsgBox "The current UCS is : " & ThisDrawing.ActiveUCS.Name _
& vbCrLf & " Pick a point in the drawing."' Find the WCS and UCS coordinate of a pointDim WCSPnt As VariantDim UCSPnt As VariantWCSPnt = ThisDrawing.Utility.GetPoint(, "Enter a point: ")UCSPnt = ThisDrawing.Utility.TranslateCoordinates _(WCSPnt, acWorld, acUCS, False)MsgBox "The WCS coordinates are: " & WCSPnt(0) & ", " _
& WCSPnt(1) & ", " & WCSPnt(2) & vbCrLf & _"The UCS coordinates are: " & UCSPnt(0) & ", " _& UCSPnt(1) & ", " & UCSPnt(2)
End Sub
140. TranslateCoordinates
Sub Ch8_TranslateCoordinates()' Create a polyline in model space.Dim plineObj As AcadPolylineDim points(0 To 14) As Double' Define the 2D polyline pointspoints(0) = 1: points(1) = 1: points(2) = 0points(3) = 1: points(4) = 2: points(5) = 0points(6) = 2: points(7) = 2: points(8) = 0points(9) = 3: points(10) = 2: points(11) = 0points(12) = 4: points(13) = 4: points(14) = 0' Create a light weight Polyline object in model spaceSet plineObj = ThisDrawing.ModelSpace.AddPolyline(points)' Find the X and Y coordinates of the' first vertex of the polylineDim firstVertex As VariantfirstVertex = plineObj.Coordinate(0)' Find the Z coordinate for the polyline' using the elevation propertyfirstVertex(2) = plineObj.Elevation' Change the normal for the pline so that the' difference between the coordinate systems' is obvious.Dim plineNormal(0 To 2) As DoubleplineNormal(0) = 0#plineNormal(1) = 1#plineNormal(2) = 2#plineObj.Normal = plineNormal' Translate the OCS coordinate into WCSDim coordinateWCS As VariantcoordinateWCS = ThisDrawing.Utility.TranslateCoordinates _
(firstVertex, acOCS, acWorld, False, plineNormal)' Display the coordinates of the pointMsgBox "The first vertex has the following coordinates:" _
& vbCrLf & "OCS: " & firstVertex(0) & ", " & _
firstVertex(1) & ", " & firstVertex(2) & vbCrLf & _"WCS: " & coordinateWCS(0) & ", " & _coordinateWCS(1) & ", " & coordinateWCS(2)
End Sub
141. Create3DMesh
Sub Ch8_Create3DMesh()Dim meshObj As AcadPolygonMeshDim mSize, nSize, Count As IntegerDim points(0 To 47) As Double' create the matrix of pointspoints(0) = 0: points(1) = 0: points(2) = 0points(3) = 2: points(4) = 0: points(5) = 1points(6) = 4: points(7) = 0: points(8) = 0points(9) = 6: points(10) = 0: points(11) = 1points(12) = 0: points(13) = 2: points(14) = 0points(15) = 2: points(16) = 2: points(17) = 1points(18) = 4: points(19) = 2: points(20) = 0points(21) = 6: points(22) = 2: points(23) = 1points(24) = 0: points(25) = 4: points(26) = 0points(27) = 2: points(28) = 4: points(29) = 1points(30) = 4: points(31) = 4: points(32) = 0points(33) = 6: points(34) = 4: points(35) = 0points(36) = 0: points(37) = 6: points(38) = 0points(39) = 2: points(40) = 6: points(41) = 1points(42) = 4: points(43) = 6: points(44) = 0points(45) = 6: points(46) = 6: points(47) = 0mSize = 4: nSize = 4' creates a 3Dmesh in model spaceSet meshObj = ThisDrawing.ModelSpace. _Add3DMesh(mSize, nSize, points)' Change the viewing direction of the viewport' to better see the cylinderDim NewDirection(0 To 2) As DoubleNewDirection(0) = -1NewDirection(1) = -1NewDirection(2) = 1ThisDrawing.ActiveViewport.direction = NewDirectionThisDrawing.ActiveViewport = ThisDrawing.ActiveViewportZoomAll
End Sub
142. CreatePolyfaceMesh
Sub Ch8_CreatePolyfaceMesh()'Define the mesh verticesDim vertex(0 To 17) As Doublevertex(0) = 4: vertex(1) = 7: vertex(2) = 0vertex(3) = 5: vertex(4) = 7: vertex(5) = 0vertex(6) = 6: vertex(7) = 7: vertex(8) = 0vertex(9) = 4: vertex(10) = 6: vertex(11) = 0vertex(12) = 5: vertex(13) = 6: vertex(14) = 0vertex(15) = 6: vertex(16) = 6: vertex(17) = 1' Define the face listDim FaceList(0 To 7) As IntegerFaceList(0) = 1FaceList(1) = 2FaceList(2) = 5FaceList(3) = 4FaceList(4) = 2FaceList(5) = 3FaceList(6) = 6FaceList(7) = 5' Create the polyface meshDim polyfaceMeshObj As AcadPolyfaceMeshSet polyfaceMeshObj = ThisDrawing.ModelSpace.AddPolyfaceMesh _
(vertex, FaceList)' Change the viewing direction of the viewport to
' better see the polyface meshDim NewDirection(0 To 2) As DoubleNewDirection(0) = -1NewDirection(1) = -1NewDirection(2) = 1ThisDrawing.ActiveViewport.direction = NewDirectionThisDrawing.ActiveViewport = ThisDrawing.ActiveViewportZoomAll
End Sub
143. CreateWedge
Sub Ch8_CreateWedge()Dim wedgeObj As Acad3DSolidDim center(0 To 2) As DoubleDim length As DoubleDim width As DoubleDim height As Double' Define the wedgecenter(0) = 5#: center(1) = 5#: center(2) = 0length = 10#: width = 15#: height = 20#' Create the wedge in model spaceSet wedgeObj = ThisDrawing.ModelSpace. _AddWedge(center, length, width, height)' Change the viewing direction of the viewportDim NewDirection(0 To 2) As DoubleNewDirection(0) = -1NewDirection(1) = -1NewDirection(2) = 1ThisDrawing.ActiveViewport.direction = NewDirectionThisDrawing.ActiveViewport = ThisDrawing.ActiveViewportZoomAll
End Sub
144. Rotate_3DBox
Sub Ch8_Rotate_3DBox()Dim boxObj As Acad3DSolidDim length As DoubleDim width As DoubleDim height As DoubleDim center(0 To 2) As Double' Define the boxcenter(0) = 5: center(1) = 5: center(2) = 0length = 5width = 7height = 10' Create the box object in model spaceSet boxObj = ThisDrawing.ModelSpace. _AddBox(center, length, width, height)' Define the rotation axis with two pointsDim rotatePt1(0 To 2) As DoubleDim rotatePt2(0 To 2) As DoubleDim rotateAngle As DoublerotatePt1(0) = -3: rotatePt1(1) = 4: rotatePt1(2) = 0rotatePt2(0) = -3: rotatePt2(1) = -4: rotatePt2(2) = 0rotateAngle = 30rotateAngle = rotateAngle * 3.141592 / 180#' Rotate the boxboxObj.Rotate3D rotatePt1, rotatePt2, rotateAngleZoomAll
End Sub
145. CreateRectangularArray
Sub Ch8_CreateRectangularArray()' Create the circleDim circleObj As AcadCircle
Dim center(0 To 2) As DoubleDim radius As Doublecenter(0) = 2: center(1) = 2: center(2) = 0radius = 0.5Set circleObj = ThisDrawing.ModelSpace. _AddCircle(center, radius)' Define the rectangular arrayDim numberOfRows As LongDim numberOfColumns As LongDim numberOfLevels As LongDim distanceBwtnRows As DoubleDim distanceBwtnColumns As DoubleDim distanceBwtnLevels As DoublenumberOfRows = 4numberOfColumns = 4numberOfLevels = 3distanceBwtnRows = 1distanceBwtnColumns = 1distanceBwtnLevels = 4' Create the array of objectsDim retObj As VariantretObj = circleObj.ArrayRectangular _(numberOfRows, numberOfColumns, _numberOfLevels, distanceBwtnRows, _distanceBwtnColumns, distanceBwtnLevels)ZoomAll
End Sub
146. MirrorABox3D
Sub Ch8_MirrorABox3D()' Create the box objectDim boxObj As Acad3DSolidDim length As DoubleDim width As DoubleDim height As DoubleDim center(0 To 2) As Doublecenter(0) = 5#: center(1) = 5#: center(2) = 0length = 5#: width = 7: height = 10#' Create the box (3DSolid) object in model spaceSet boxObj = ThisDrawing.ModelSpace. _AddBox(center, length, width, height)' Define the mirroring plane with three pointsDim mirrorPt1(0 To 2) As DoubleDim mirrorPt2(0 To 2) As DoubleDim mirrorPt3(0 To 2) As DoublemirrorPt1(0) = 1.25: mirrorPt1(1) = 0: mirrorPt1(2) = 0mirrorPt2(0) = 1.25: mirrorPt2(1) = 2: mirrorPt2(2) = 0mirrorPt3(0) = 1.25: mirrorPt3(1) = 2: mirrorPt3(2) = 2' Mirror the boxDim mirrorBoxObj As Acad3DSolidSet mirrorBoxObj = boxObj.Mirror3D _(mirrorPt1, mirrorPt2, mirrorPt3)mirrorBoxObj.Color = acRedZoomAll
End Sub
147. FindInterferenceBetweenSolids
Sub Ch8_FindInterferenceBetweenSolids()' Define the boxDim boxObj As Acad3DSolidDim length As DoubleDim width As DoubleDim height As DoubleDim center(0 To 2) As Doublecenter(0) = 5: center(1) = 5: center(2) = 0length = 5
width = 7height = 10' Create the box object in model space' and color it whiteSet boxObj = ThisDrawing.ModelSpace. _AddBox(center, length, width, height)boxObj.Color = acWhite' Define the cylinderDim cylinderObj As Acad3DSolidDim cylinderRadius As DoubleDim cylinderHeight As Doublecenter(0) = 0: center(1) = 0: center(2) = 0cylinderRadius = 5cylinderHeight = 20' Create the Cylinder and' color it cyanSet cylinderObj = ThisDrawing.ModelSpace.AddCylinder _(center, cylinderRadius, cylinderHeight)cylinderObj.Color = acCyan' Find the interference between the two solids' and create a new solid from it. Color the' new solid red.Dim solidObj As Acad3DSolidSet solidObj = boxObj.CheckInterference(cylinderObj, True)solidObj.Color = acRedZoomAll
End Sub
148. SliceABox
Sub Ch8_SliceABox()' Create the box objectDim boxObj As Acad3DSolidDim length As DoubleDim width As DoubleDim height As DoubleDim center(0 To 2) As Doublecenter(0) = 5#: center(1) = 5#: center(2) = 0length = 5#: width = 7: height = 10#' Create the box (3DSolid) object in model spaceSet boxObj = ThisDrawing.ModelSpace. _AddBox(center, length, width, height)boxObj.Color = acWhite' Define the section plane with three pointsDim slicePt1(0 To 2) As DoubleDim slicePt2(0 To 2) As DoubleDim slicePt3(0 To 2) As DoubleslicePt1(0) = 1.5: slicePt1(1) = 7.5: slicePt1(2) = 0slicePt2(0) = 1.5: slicePt2(1) = 7.5: slicePt2(2) = 10slicePt3(0) = 8.5: slicePt3(1) = 2.5: slicePt3(2) = 10' slice the box and color the new solid redDim sliceObj As Acad3DSolidSet sliceObj = boxObj.SliceSolid _(slicePt1, slicePt2, slicePt3, True)sliceObj.Color = acRedZoomAll
End Sub
149. SwitchToPaperSpace
Sub Ch9_SwitchToPaperSpace()' Set the active space to paper spaceThisDrawing.ActiveSpace = acPaperSpace' Create the paperspace viewportDim newVport As AcadPViewportDim center(0 To 2) As Doublecenter(0) = 3.25center(1) = 3
center(2) = 0Set newVport = ThisDrawing.PaperSpace. _AddPViewport(center, 6, 5)' Change the view direction for the viewportDim viewDir(0 To 2) As DoubleviewDir(0) = 1viewDir(1) = 1viewDir(2) = 1newVport.direction = viewDir' Enable the viewportnewVport.Display True' Switch to model spaceThisDrawing.MSpace = True' Set newVport current' (not always necessary but a good idea)ThisDrawing.ActivePViewport = newVport' Zoom Extents in model spaceZoomExtents' Turn model space editing offThisDrawing.MSpace = False' ZoomExtents in paperspaceZoomExtents
End Sub
150. FourPViewports
Sub Ch9_FourPViewports()Dim topVport, frontVport As AcadPViewportDim rightVport, isoVport As AcadPViewportDim pt(0 To 2) As DoubleDim viewDir(0 To 2) As DoubleThisDrawing.ActiveSpace = acPaperSpaceThisDrawing.MSpace = True' Take the existing PViewport and make it the topVportpt(0) = 2.5: pt(1) = 5.5: pt(2) = 0Set topVport = ThisDrawing.ActivePViewport'No need to set Direction for top viewtopVport.center = pttopVport.width = 2.5topVport.height = 2.5topVport.Display TrueThisDrawing.MSpace = TrueThisDrawing.ActivePViewport = topVportZoomExtentsZoomScaled 0.5, acZoomScaledRelativePSpace'Create and setup frontVportpt(0) = 2.5: pt(1) = 2.5: pt(2) = 0Set frontVport = ThisDrawing.PaperSpace. _AddPViewport(pt, 2.5, 2.5)viewDir(0) = 0: viewDir(1) = 1: viewDir(2) = 0frontVport.direction = viewDirfrontVport.Display acOnThisDrawing.MSpace = TrueThisDrawing.ActivePViewport = frontVportZoomExtentsZoomScaled 0.5, acZoomScaledRelativePSpace'Create and setup rightVportpt(0) = 5.5: pt(1) = 5.5: pt(2) = 0Set rightVport = ThisDrawing.PaperSpace. _AddPViewport(pt, 2.5, 2.5)viewDir(0) = 1: viewDir(1) = 0: viewDir(2) = 0rightVport.direction = viewDirrightVport.Display acOnThisDrawing.MSpace = TrueThisDrawing.ActivePViewport = rightVportZoomExtentsZoomScaled 0.5, acZoomScaledRelativePSpace'Create and set up isoVportpt(0) = 5.5: pt(1) = 2.5: pt(2) = 0
Set isoVport = ThisDrawing.PaperSpace. _AddPViewport(pt, 2.5, 2.5)viewDir(0) = 1: viewDir(1) = 1: viewDir(2) = 1isoVport.direction = viewDirisoVport.Display acOnThisDrawing.MSpace = TrueThisDrawing.ActivePViewport = isoVportZoomExtentsZoomScaled 0.5, acZoomScaledRelativePSpace'Finish: Perform a regen in all viewportsThisDrawing.Regen True
End Sub
151. PrintModelSpace
Sub Ch9_PrintModelSpace()' Verify that the active space is model spaceIf ThisDrawing.ActiveSpace = acPaperSpace ThenThisDrawing.MSpace = TrueThisDrawing.ActiveSpace = acModelSpaceEnd If' Set the extents and scale of the plot areaThisDrawing.ModelSpace.Layout.PlotType = acExtentsThisDrawing.ModelSpace.Layout. _StandardScale = acScaleToFit' Set the number of copies to oneThisDrawing.Plot.NumberOfCopies = 1' Initiate the plotThisDrawing.Plot.PlotToDevice
End Sub
152. PrintPaperSpace
Sub Ch9_PrintPaperSpace()' Establish the paper space layouts to be plottedDim strLayouts(0 To 1) As StringDim varLayouts As VariantstrLayouts(0) = "Layout1"strLayouts(1) = "Layout2"varLayouts = strLayoutsThisDrawing.Plot.SetLayoutsToPlot varLayouts' Set the number of copies to oneThisDrawing.Plot.NumberOfCopies = 1' Initiate the plotThisDrawing.Plot.PlotToDevice
End Sub
153. AttachingARaster
Sub Ch10_AttachingARaster()Dim insertionPoint(0 To 2) As DoubleDim scalefactor As DoubleDim rotationAngle As DoubleDim imageName As StringDim rasterObj As AcadRasterImageimageName = "C:/Program Files/AutoCAD 2004/sample/watch.jpg"insertionPoint(0) = 5insertionPoint(1) = 5insertionPoint(2) = 0scalefactor = 2rotationAngle = 0On Error GoTo ERRORHANDLER
' Attach the raster image in model spaceSet rasterObj = ThisDrawing.ModelSpace.AddRaster _(imageName, insertionPoint, _scalefactor, rotationAngle)ZoomAllExit Sub
ERRORHANDLER:
MsgBox Err.DescriptionEnd Sub
154. ClippingRasterBoundary
Sub Ch10_ClippingRasterBoundary()Dim insertionPoint(0 To 2) As DoubleDim scalefactor As DoubleDim rotationAngle As DoubleDim imageName As StringDim rasterObj As AcadRasterImageimageName = "C:\AutoCAD\sample\downtown.jpg"insertionPoint(0) = 5insertionPoint(1) = 5insertionPoint(2) = 0scalefactor = 2rotationAngle = 0On Error GoTo ERRORHANDLER
' Creates a raster image in model spaceSet rasterObj = ThisDrawing.ModelSpace.AddRaster _(imageName, insertionPoint, _scalefactor, rotationAngle)ZoomAll' Establish the clip boundary with an array of pointsDim clipPoints(0 To 9) As DoubleclipPoints(0) = 6: clipPoints(1) = 6.75clipPoints(2) = 7: clipPoints(3) = 6clipPoints(4) = 6: clipPoints(5) = 5clipPoints(6) = 5: clipPoints(7) = 6clipPoints(8) = 6: clipPoints(9) = 6.75' Clip the imagerasterObj.ClipBoundary clipPoints' Enable the display of the cliprasterObj.ClippingEnabled = TrueThisDrawing.Regen acActiveViewportExit Sub
ERRORHANDLER:MsgBox Err.Description
End Sub
155. InsertingABlock
Sub Ch10_InsertingABlock()' Define the blockDim blockObj As AcadBlockDim insertionPnt(0 To 2) As DoubleinsertionPnt(0) = 0insertionPnt(1) = 0insertionPnt(2) = 0Set blockObj = ThisDrawing.Blocks.Add _(insertionPnt, "CircleBlock")' Add a circle to the blockDim circleObj As AcadCircleDim center(0 To 2) As DoubleDim radius As Doublecenter(0) = 0center(1) = 0center(2) = 0radius = 1Set circleObj = blockObj.AddCircle(center, radius)' Insert the blockDim blockRefObj As AcadBlockReferenceinsertionPnt(0) = 2insertionPnt(1) = 2insertionPnt(2) = 0Set blockRefObj = ThisDrawing.ModelSpace.InsertBlock _(insertionPnt, "CircleBlock", 1#, 1#, 1#, 0)ZoomAllMsgBox "The circle belongs to " & blockRefObj.ObjectName
End Sub
156. ExplodingABlock
Sub Ch10_ExplodingABlock()' Define the blockDim blockObj As AcadBlockDim insertionPnt(0 To 2) As DoubleinsertionPnt(0) = 0insertionPnt(1) = 0insertionPnt(2) = 0Set blockObj = ThisDrawing.Blocks.Add _(insertionPnt, "CircleBlock")' Add a circle to the blockDim circleObj As AcadCircleDim center(0 To 2) As DoubleDim radius As Doublecenter(0) = 0center(1) = 0center(2) = 0radius = 1Set circleObj = blockObj.AddCircle(center, radius)' Insert the blockDim blockRefObj As AcadBlockReferenceinsertionPnt(0) = 2insertionPnt(1) = 2insertionPnt(2) = 0Set blockRefObj = ThisDrawing.ModelSpace.InsertBlock _(insertionPnt, "CircleBlock", 1#, 1#, 1#, 0)ZoomAllMsgBox "The circle belongs to " & blockRefObj.ObjectName' Explode the block referenceDim explodedObjects As VariantexplodedObjects = blockRefObj.Explode' Loop through the exploded objectsDim I As IntegerFor I = 0 To UBound(explodedObjects)
explodedObjects(I).Color = acRedexplodedObjects(I).UpdateMsgBox "Exploded Object " & I & ": " _& explodedObjects(I).ObjectNameexplodedObjects(I).Color = acByLayerexplodedObjects(I).Update
NextEnd Sub
157. RedefiningABlock
Sub Ch10_RedefiningABlock()' Define the blockDim blockObj As AcadBlockDim insertionPnt(0 To 2) As DoubleinsertionPnt(0) = 0insertionPnt(1) = 0insertionPnt(2) = 0Set blockObj = ThisDrawing.Blocks.Add _(insertionPnt, "CircleBlock")' Add a circle to the blockDim circleObj As AcadCircleDim center(0 To 2) As DoubleDim radius As Doublecenter(0) = 0center(1) = 0center(2) = 0radius = 1Set circleObj = blockObj.AddCircle(center, radius)' Insert the blockDim blockRefObj As AcadBlockReferenceinsertionPnt(0) = 2
insertionPnt(1) = 2insertionPnt(2) = 0Set blockRefObj = ThisDrawing.ModelSpace.InsertBlock _(insertionPnt, "CircleBlock", 1#, 1#, 1#, 0)ZoomAll' Redefine the circle in the block,' and update the block referencecircleObj.radius = 3blockRefObj.Update
End Sub
158. CreatingAnAttribute
Sub Ch10_CreatingAnAttribute()' Define the blockDim blockObj As AcadBlockDim insertionPnt(0 To 2) As DoubleinsertionPnt(0) = 0insertionPnt(1) = 0insertionPnt(2) = 0Set blockObj = ThisDrawing.Blocks.Add _(insertionPnt, "BlockWithAttribute")' Add an attribute to the blockDim attributeObj As AcadAttributeDim height As DoubleDim mode As LongDim prompt As StringDim insertionPoint(0 To 2) As DoubleDim tag As StringDim value As Stringheight = 1mode = acAttributeModeVerifyprompt = "New Prompt"insertionPoint(0) = 5insertionPoint(1) = 5insertionPoint(2) = 0tag = "New Tag"value = "New Value"Set attributeObj = blockObj.AddAttribute(height, mode, _
prompt, insertionPoint, tag, value)' Insert the block, creating a block reference' and an attribute referenceDim blockRefObj As AcadBlockReferenceinsertionPnt(0) = 2insertionPnt(1) = 2insertionPnt(2) = 0Set blockRefObj = ThisDrawing.ModelSpace.InsertBlock _
(insertionPnt, "BlockWithAttribute", 1#, 1#, 1#, 0)End Sub
159. RedefiningAnAttribute
Sub Ch10_RedefiningAnAttribute()' Define the blockDim blockObj As AcadBlockDim insertionPnt(0 To 2) As DoubleinsertionPnt(0) = 0insertionPnt(1) = 0insertionPnt(2) = 0Set blockObj = ThisDrawing.Blocks.Add _(insertionPnt, "BlockWithAttribute")' Add an attribute to the blockDim attributeObj As AcadAttributeDim height As DoubleDim mode As LongDim prompt As StringDim insertionPoint(0 To 2) As DoubleDim tag As StringDim value As String
height = 1mode = acAttributeModeVerifyprompt = "New Prompt"insertionPoint(0) = 5insertionPoint(1) = 5insertionPoint(2) = 0tag = "New Tag"value = "New Value"Set attributeObj = blockObj.AddAttribute(height, mode, _prompt, insertionPoint, tag, value)' Insert the block, creating a block reference' and an attribute referenceDim blockRefObj As AcadBlockReferenceinsertionPnt(0) = 2insertionPnt(1) = 2insertionPnt(2) = 0Set blockRefObj = ThisDrawing.ModelSpace.InsertBlock _(insertionPnt, "BlockWithAttribute", 1#, 1#, 1#, 0)' Redefine the attribute text to display backwards.attributeObj.Backward = TrueattributeObj.Update
End Sub
160. GettingAttributes
Sub Ch10_GettingAttributes()' Create the blockDim blockObj As AcadBlockDim insertionPnt(0 To 2) As DoubleinsertionPnt(0) = 0insertionPnt(1) = 0insertionPnt(2) = 0Set blockObj = ThisDrawing.Blocks.Add _
(insertionPnt, "TESTBLOCK")' Define the attribute definitionDim attributeObj As AcadAttributeDim height As DoubleDim mode As LongDim prompt As StringDim insertionPoint(0 To 2) As DoubleDim tag As StringDim value As Stringheight = 1#mode = acAttributeModeVerifyprompt = "Attribute Prompt"insertionPoint(0) = 5insertionPoint(1) = 5insertionPoint(2) = 0tag = "Attribute Tag"value = "Attribute Value"' Create the attribute definition object on the blockSet attributeObj = blockObj.AddAttribute _
(height, mode, prompt, _insertionPoint, tag, value)
' Insert the blockDim blockRefObj As AcadBlockReferenceinsertionPnt(0) = 2insertionPnt(1) = 2insertionPnt(2) = 0Set blockRefObj = ThisDrawing.ModelSpace.InsertBlock _
(insertionPnt, "TESTBLOCK", 1, 1, 1, 0)ZoomAll' Get the attributes for the block referenceDim varAttributes As VariantvarAttributes = blockRefObj.GetAttributes' Move the attribute tags and values into a' string to be displayed in a MsgboxDim strAttributes As StringstrAttributes = ""
Dim I As IntegerFor I = LBound(varAttributes) To UBound(varAttributes)
strAttributes = strAttributes + " Tag: " + _varAttributes(I).TagString + vbCrLf + _" Value: " + varAttributes(I).textString
NextMsgBox "The attributes for blockReference " + _
blockRefObj.Name & " are: " & vbCrLf _& strAttributes
' Change the value of the attribute' Note: There is no SetAttributes. Once you have the' variant array, you have the objects.' Changing them changes the objects in the drawing.varAttributes(0).textString = "NEW VALUE!"' Get the attributes againDim newvarAttributes As VariantnewvarAttributes = blockRefObj.GetAttributes' Again, display the tags and valuesstrAttributes = ""For I = LBound(varAttributes) To UBound(varAttributes)
strAttributes = strAttributes + " Tag: " + _newvarAttributes(I).TagString + vbCrLf + _" Value: " + newvarAttributes(I).textString
NextMsgBox "The attributes for blockReference " & _
blockRefObj.Name & " are: " & vbCrLf _& strAttributes
End Sub
161. AttachingExternalReference
Sub Ch10_AttachingExternalReference()On Error GoTo ERRORHANDLER
Dim InsertPoint(0 To 2) As DoubleDim insertedBlock As AcadExternalReferenceDim tempBlock As AcadBlockDim msg As String, PathName As String' Define external reference to be insertedInsertPoint(0) = 1InsertPoint(1) = 1InsertPoint(2) = 0PathName = "C:/Program Files/AutoCAD 2004/sample/City map.dwg"' Display current Block information for this drawingGoSub ListBlocks' Add the external reference to the drawingSet insertedBlock = ThisDrawing.ModelSpace. _AttachExternalReference(PathName, "XREF_IMAGE", _InsertPoint, 1, 1, 1, 0, False)ZoomAll' Display new Block information for this drawingGoSub ListBlocksExit Sub
ListBlocks:msg = vbCrLf ' Reset messageFor Each tempBlock In ThisDrawing.Blocks
msg = msg & tempBlock.Name & vbCrLfNextMsgBox "The current blocks in this drawing are: " & msgReturn
ERRORHANDLER:MsgBox Err.Description
End Sub
162. DetachingExternalReference
Sub Ch10_DetachingExternalReference()On Error GoTo ERRORHANDLER
' Define external reference to be insertedDim xrefHome As AcadBlock
Dim xrefInserted As AcadExternalReferenceDim insertionPnt(0 To 2) As DoubleDim PathName As StringinsertionPnt(0) = 1insertionPnt(1) = 1insertionPnt(2) = 0PathName = "c:/AutoCAD/sample/City map.dwg"' Add the external referenceSet xrefInserted = ThisDrawing.ModelSpace. _AttachExternalReference(PathName, "XREF_IMAGE", _insertionPnt, 1, 1, 1, 0, False)ZoomAllMsgBox "The external reference is attached."' Detach the external reference definitionDim name As Stringname = xrefInserted.nameThisDrawing.Blocks.Item(name).DetachMsgBox "The external reference is detached."Exit Sub
ERRORHANDLER:MsgBox Err.Description
End Sub
163. ReloadingExternalReference
Sub Ch10_ReloadingExternalReference()On Error GoTo ERRORHANDLER
' Define external reference to be insertedDim xrefHome As AcadBlockDim xrefInserted As AcadExternalReferenceDim insertionPnt(0 To 2) As DoubleDim PathName As StringinsertionPnt(0) = 1insertionPnt(1) = 1insertionPnt(2) = 0PathName = "c:/AutoCAD/sample/City map.dwg"' Add the external reference to the blockSet xrefInserted = ThisDrawing.ModelSpace. _AttachExternalReference(PathName, "XREF_IMAGE", _insertionPnt, 1, 1, 1, 0, False)ZoomAllMsgBox "The external reference is attached."' Reload the external reference definitionThisDrawing.Blocks.Item(xrefInserted.name).ReloadMsgBox "The external reference is reloaded."Exit Sub
ERRORHANDLER:MsgBox Err.Description
End Sub
164. UnloadingExternalReference
Sub Ch10_UnloadingExternalReference()On Error GoTo ERRORHANDLER
' Define external reference to be insertedDim xrefHome As AcadBlockDim xrefInserted As AcadExternalReferenceDim insertionPnt(0 To 2) As DoubleDim PathName As StringinsertionPnt(0) = 1insertionPnt(1) = 1insertionPnt(2) = 0PathName = "c:/AutoCAD/sample/City map.dwg"' Add the external referenceSet xrefInserted = ThisDrawing.ModelSpace. _AttachExternalReference(PathName, "XREF_IMAGE", _insertionPnt, 1, 1, 1, 0, False)ZoomAllMsgBox "The external reference is attached."
' Unload the external reference definitionThisDrawing.Blocks.Item(xrefInserted.name).UnloadMsgBox "The external reference is unloaded."Exit Sub
ERRORHANDLER:MsgBox Err.Description
End Sub
165. BindingExternalReference
Sub Ch10_BindingExternalReference()On Error GoTo ERRORHANDLER
' Define external reference to be insertedDim xrefHome As AcadBlockDim xrefInserted As AcadExternalReferenceDim insertionPnt(0 To 2) As DoubleDim PathName As StringinsertionPnt(0) = 1insertionPnt(1) = 1insertionPnt(2) = 0PathName = "c:/AutoCAD/sample/City map.dwg"' Add the external referenceSet xrefInserted = ThisDrawing.ModelSpace. _AttachExternalReference(PathName, "XREF_IMAGE", _insertionPnt, 1, 1, 1, 0, False)ZoomAllMsgBox "The external reference is attached."' Bind the external reference definitionThisDrawing.Blocks.Item(xrefInserted.name).Bind FalseMsgBox "The external reference is bound."Exit Sub
ERRORHANDLER:MsgBox Err.Description
End Sub
166. AttachXDataToSelectionSetObjects
Sub Ch10_AttachXDataToSelectionSetObjects()' Create the selection setDim sset As ObjectSet sset = ThisDrawing.SelectionSets.Add("SS1")' Prompt the user to select objectssset.SelectOnScreen' Define the xdataDim appName As String, xdataStr As StringappName = "MY_APP"xdataStr = "This is some xdata"Dim xdataType(0 To 1) As IntegerDim xdata(0 To 1) As Variant' Define the values for each array'1001 indicates the appNamexdataType(0) = 1001xdata(0) = appName'1000 indicates a string valuexdataType(1) = 1000xdata(1) = xdataStr' Loop through all entities in the selection' set and assign the xdata to each entityDim ent As ObjectFor Each ent In sset
ent.SetXData xdataType, xdataNext ent
End Sub
167. ViewXData
Sub Ch10_ViewXData()' Find the selection created in previous exampleDim sset As Object
Set sset = ThisDrawing.SelectionSets.Item("SS1")' Define the xdata variables to hold xdata informationDim xdataType As VariantDim xdata As VariantDim xd As Variant'Define index counterDim xdi As Integerxdi = 0' Loop through the objects in the selection set' and retrieve the xdata for the objectDim msgstr As StringDim appName As StringDim ent As AcadEntityappName = "MY_APP"For Each ent In sset
msgstr = ""xdi = 0' Retrieve the appName xdata type and valueent.GetXData appName, xdataType, xdata' If the xdataType variable is not initialized, there' was no appName xdata to retrieve for that entityIf VarType(xdataType) <> vbEmpty Then
For Each xd In xdatamsgstr = msgstr & vbCrLf & xdataType(xdi) _& ": " & xdxdi = xdi + 1
Next xdEnd If' If the msgstr variable is NULL, there was no xdataIf msgstr = "" Then msgstr = vbCrLf & "NONE"MsgBox appName & " xdata on " & ent.ObjectName & _":" & vbCrLf & msgstr
Next entEnd Sub
168. Display a form
Public Sub MyApplication()UserForm1.Show
End Sub
169. Hide a form
Public Sub MyAppHide()UserForm1.Hide
End Sub
170. ColorEntities
Sub Ch11_ColorEntities()Dim entry As ObjectOn Error Resume NextFor Each entry In ThisDrawing.ModelSpace
entry.Color = acRedNext entry
End Sub
171. ColorEntities2
Sub Ch11_ColorEntities2()Dim entry As ObjectOn Error GoTo MyErrorHandlerFor Each entry In ThisDrawing.ModelSpace
entry.Color = acRedNext entry' Important! Exit the subroutine before the error handlerExit Sub
MyErrorHandler:
Msgbox entry.EntityName + " is on a locked layer." + _" The handle is: " + entry.HandleResume Next
End Sub
172.Tu dong load
(defun S::STARTUP()(command "_VBALOAD" "myproj.dvb")
)
173. Tu dong chay Macro
(defun S::STARTUP()(command "_-vbarun" "drawline")
)
174. Lam viec voi Excel
Sub Ch12_Extract()Dim Excel As Excel.ApplicationDim ExcelSheet As ObjectDim ExcelWorkbook As ObjectDim RowNum As IntegerDim Header As BooleanDim elem As AcadEntityDim Array1 As VariantDim Count As Integer' Launch Excel.Set Excel = New Excel.Application' Create a new workbook and find the active sheet.Set ExcelWorkbook = Excel.Workbooks.AddSet ExcelSheet = Excel.ActiveSheetExcelWorkbook.SaveAs "Attribute.xls"RowNum = 1Header = False' Iterate through model space finding' all block references.For Each elem In ThisDrawing.ModelSpace
With elem' When a block reference has been found,' check it for attributesIf StrComp(.EntityName, "AcDbBlockReference", 1) _
= 0 ThenIf .HasAttributes Then
' Get the attributesArray1 = .GetAttributes' Copy the Tagstrings for the' Attributes into ExcelFor Count = LBound(Array1) To UBound(Array1)
If Header = False ThenIf StrComp(Array1(Count).EntityName, _
"AcDbAttribute", 1) = 0 ThenExcelSheet.Cells(RowNum, _Count + 1).value = _Array1(Count).TagString
End IfEnd If
Next CountRowNum = RowNum + 1For Count = LBound(Array1) To UBound(Array1)
ExcelSheet.Cells(RowNum, Count + 1).value _= Array1(Count).textString
Next CountHeader = True
End IfEnd IfEnd With
Next elem
Excel.Application.QuitEnd Sub
175. Doi do sang Radian
Const pi = 3.14159' Convert angle in degrees to radiansFunction dtr(a As Double) As Double
dtr = (a / 180) * piEnd Function
176. Tinh khoang cach
Function distance(sp As Variant, ep As Variant) _As DoubleDim x As DoubleDim y As DoubleDim z As Doublex = sp(0) - ep(0)y = sp(1) - ep(1)z = sp(2) - ep(2)distance = Sqr((Sqr((x ^ 2) + (y ^ 2)) ^ 2) + (z ^ 2))
End Function
177. Gardenpath macro
Private sp(0 To 2) As DoublePrivate ep(0 To 2) As DoublePrivate hwidth As DoublePrivate trad As DoublePrivate tspac As DoublePrivate pangle As DoublePrivate plength As DoublePrivate totalwidth As DoublePrivate angp90 As DoublePrivate angm90 As Double
' Acquire information for garden pathPrivate Sub gpuser()
Dim varRet As VariantvarRet = ThisDrawing.Utility.GetPoint( _, "Start point of path: ")sp(0) = varRet(0)sp(1) = varRet(1)sp(2) = varRet(2)varRet = ThisDrawing.Utility.GetPoint( _, "Endpoint of path: ")ep(0) = varRet(0)ep(1) = varRet(1)ep(2) = varRet(2)hwidth = ThisDrawing.Utility. _GetDistance(sp, "Half width of path: ")trad = ThisDrawing.Utility. _GetDistance(sp, "Radius of tiles: ")tspac = ThisDrawing.Utility. _GetDistance(sp, "Spacing between tiles: ")pangle = ThisDrawing.Utility.AngleFromXAxis( _sp, ep)totalwidth = 2 * hwidthplength = distance(sp, ep)angp90 = pangle + dtr(90)angm90 = pangle - dtr(90)
End Sub
178. ' Draw outline of path
Private Sub drawout()Dim points(0 To 9) As Double
Dim pline As AcadLWPolylineDim varRet As VariantvarRet = 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)Set pline = ThisDrawing.ModelSpace. _AddLightWeightPolyline(points)
End Sub
179.
' Place one row of tiles the given distance along path' and possibly offset itPrivate Sub drow(pd As Double, offset As Double)
Dim pfirst(0 To 2) As DoubleDim pctile(0 To 2) As DoubleDim pltile(0 To 2) As DoubleDim cir As AcadCircleDim varRet As VariantvarRet = 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)Do While distance(pfirst, pltile) < (hwidth - trad)
Set cir = 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)
LoopvarRet = ThisDrawing.Utility.PolarPoint( _pctile, angm90, tspac + trad + trad)pltile(0) = varRet(0)pltile(1) = varRet(1)pltile(2) = varRet(2)Do While distance(pfirst, pltile) < (hwidth - trad)
Set cir = 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)
LoopEnd Sub
' Draw the rows of tilesPrivate Sub drawtiles()
Dim pdist As DoubleDim offset As Doublepdist = trad + tspacoffset = 0Do While pdist <= (plength - trad)
drow pdist, offsetpdist = pdist + ((tspac + trad + trad) * Sin(dtr(60)))If offset = 0 Then
offset = (tspac + trad + trad) * Cos(dtr(60))Else
offset = 0End If
LoopEnd Sub
180.
' Execute command, calling constituent functionsSub gardenpath()
Dim sblip As VariantDim scmde As Variantgpusersblip = ThisDrawing.GetVariable("blipmode")scmde = ThisDrawing.GetVariable("cmdecho")ThisDrawing.SetVariable "blipmode", 0ThisDrawing.SetVariable "cmdecho", 0drawoutdrawtilesThisDrawing.SetVariable "blipmode", sblipThisDrawing.SetVariable "cmdecho", scmde
End Sub
181.
'Draw the tile with the designated shapeSub DrawShape(pltile)Dim angleSegment As DoubleDim currentAngle As DoubleDim angleInRadians As DoubleDim currentSide As IntegerDim varRet As VariantDim aCircle As AcadCircleDim aPolygon As AcadLWPolylineReDim points(1 To tsides * 2) As Double'Branch based on the type of shape to drawSelect Case tshape
Case "Circle"Set aCircle = ThisDrawing.ModelSpace. _AddCircle(pltile, trad)
Case "Polygon"angleSegment = 360 / tsidescurrentAngle = 0For currentSide = 0 To (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 + angleSegmentNext currentSideSet aPolygon = ThisDrawing.ModelSpace. _AddLightWeightPolyline(points)aPolygon.Closed = True
End SelectEnd Sub
182.
Private Sub gp_poly_Click()gp_tsides.Enabled = TrueThisDrawing.tshape = "Polygon"
End SubPrivate Sub gp_circ_Click()
gp_tsides.Enabled = FalseThisDrawing.tshape = "Circle"
End Sub
183..
Private Sub accept_Click()If ThisDrawing.tshape = "Polygon" Then
ThisDrawing.tsides = CInt(gp_tsides.text)If (ThisDrawing.tsides < 3#) Or _(ThisDrawing.tsides > 1024#) Then
MsgBox "Enter a value between 3 and " & _"1024 for the number of sides."Exit Sub
End IfEnd IfThisDrawing.trad = CDbl(gp_trad.text)ThisDrawing.tspac = CDbl(gp_tspac.text)If ThisDrawing.trad < 0# Then
MsgBox "Enter a positive value for the radius."Exit Sub
End IfIf (ThisDrawing.tspac < 0#) Then
MsgBox "Enter a positive value for the spacing."Exit Sub
End IfGPDialog.Hide
End Sub184.
Private Sub cancel_Click()Unload MeEnd
End Sub
185.
Private Sub UserForm_Initialize()gp_circ.Value = Truegp_trad.Text = ".2"gp_tspac.Text = ".1"gp_tsides.Text = "5"gp_tsides.Enabled = FalseThisDrawing.tsides = 5
End Sub