Ahora que ya ha conoce los aspectos bsicos de la programacin en VBA de AutoCAD, vamos a crear un sencillo ejercicio denominado Hola a todos.
En este ejercicio va a crear un dibujo de AutoCAD nuevo, va a aadirle una lnea de texto y va a guardarlo, todo ello desde VBA.
Para crear el objeto de texto Hola a todos
1. Abra el IDE de VBA ejecutando el siguiente comando desde la lnea de comando de AutoCAD:
Comando: VBAIDE
2. Abra la ventana de cdigo seleccionando la opcin Cdigo del men Ver en el IDE de VBA.
3. Cree un procedimiento nuevo en el proyecto seleccionando la opcin Procedimiento en el men Insertar en el IDE de VBA.
4. Cuando se le solicite la informacin del procedimiento, escriba un nombre, por ejemplo, HolaATodos. Asegrese de que estn
seleccionados el tipo Procedimiento y el mbito Pblico.
5. Pulse Aceptar.
6. Escriba el cdigo siguiente (que abre un dibujo nuevo) entre las lneas Public Sub Hola a todos() y End Sub.
ThisDrawing.Application.Documents.Add
7. Escriba el cdigo siguiente (que crea la cadena de texto y define el punto donde se inserta) inmediatamente despus del
cdigo introducido en el paso 6.
Dim insPoint(0 To 2) As Double 'Declare insertion point
Dim textHeight As Double 'Declare text height
Dim textStr As String 'Declare text string
Dim textObj As AcadText 'Declare text object
insPoint(0) = 2 'Set insertion point x coordinate
insPoint(1) = 4 'Set insertion point y coordinate
insPoint(2) = 0 'Set insertion point z coordinate
textHeight = 1 'Set text height to 1.0
textString = "Hello, World." 'Set the text string
'Create the Text object
Set textObj = ThisDrawing.ModelSpace.AddText _
(textStr, insPoint, textHeight)
8. Escriba el siguiente cdigo (que guarda el dibujo) inmediatamente despus del cdigo introducido en el paso 7.
ThisDrawing.SaveAs("Hello.dwg")
9. Ejecute el programa seleccionando la opcin Ejecutar Sub/UserForm en el men Ejecutar del IDE de VBA.
VBAIDE
Abre el IDE de VBA.
El IDE de VBA permite editar, ejecutar y depurar programas de forma interactiva. Aunque slo se puede activar el IDE de VBA mientras se ejecuta
AutoCAD, es posible minimizarlo, abrirlo y cerrarlo con independencia de la ventana de aplicacin de AutoCAD.
VBALOAD
Carga un proyecto VBA en la sesin actual de AutoCAD.
VBARUN
Ejecuta una macro de VBA desde el cuadro de dilogo Macros o desde la lnea de comando de AutoCAD.
VBADESCARGAR
Descarga un proyecto VBA de la sesin de AutoCAD actual.
Si el proyecto VBA se ha modificado pero no se ha guardado, se pregunta al usuario si desea guardarlo mediante el cuadro de dilogo Guardar proyecto
(o mediante el equivalente de la lnea de comando).
VBAMAN
Muestra el Administrador de VBA, donde puede ver, crear, cargar, cerrar, incrustar y extraer proyectos.
VBAENUN
Ejecuta una secuencia VBA desde la lnea de comando de AutoCAD.
Creacin de lneas
La lnea es el objeto ms sencillo de AutoCAD. Pueden crearse diversas lneas, lneas individuales y varios segmentos de lnea con o sin arcos. En
general, las lneas se dibujan designando puntos de coordenadas. El tipo de lnea por defecto es CONTINUOUS (lnea continua), pero hay varios tipos
de lnea posibles que utilizan puntos y rayas.
Para crear una lnea, utilice uno de los mtodos siguientes:
AddLine
Crea una lnea que pasa por dos puntos.
AddLightweightPolyline
Crea una polilnea optimizada 2D a partir de una lista de vrtices.
AddMLine
Crea una lnea mltiple.
AddPolyline
Crea una polilnea 2D o 3D.
Las lneas estndar y las polilneas se crean en el plano XY del sistema de coordenadas universales. Las polilneas y las polilneas optimizadas se crean
en el Sistema de coordenadas de objeto (SCO). Para obtener informacin acerca de la conversin de coordenadas SCO, vase Conversin de
coordenadas.
Creacin de un objeto Polyline
Este ejemplo aplica el mtodo AddLightweightPolyline para crear una polilnea sencilla de dos segmentos utilizando las coordenadas 2D (2,4), (4,2) y
(6,4).
Sub Ch4_AddLightWeightPolyline()
Dim plineObj As AcadLWPolyline
Dim points(0 To 5) As Double
' Define the 2D polyline points
points(0) = 2: points(1) = 4
points(2) = 4: points(3) = 2
points(4) = 6: points(5) = 4
' Create a light weight Polyline object in model space
Con AutoCAD podr crear una amplia variedad de objetos curvos, incluidos crculos, arcos, elipses y curvas spline. Todas las curvas se crean en el plano
XY del SCU actual.
Para crear una curva, utilice uno de los mtodos siguientes:
AddArc
Crea un arco contando con el centro, el radio y los ngulos inicial y final.
AddCircle
Crea un crculo con el radio y centro dados.
AddEllipse
Crea una elipse contando con el punto central, un punto en el eje mayor y la proporcin del radio.
AddSpline
Crea una curva NURBS (B-spline racional no uniforme) cuadrtica o cbica.
Creacin de un objeto Spline
En este ejemplo se crea una curva spline en espacio modelo a partir de tres puntos (0, 0, 0), (5, 5, 0) y (10, 0, 0). La curva tiene las tangentes inicial y
final de (0,5, 0,5, 0,0).
Sub Ch4_CreateSpline()
Para obtener ms informacin acerca de las curvas spline, vase la documentacin del objeto Spline y el mtodo AddSpline en ActiveX and VBA
Reference de AutoCAD.
Los objetos de punto pueden ser de mucha utilidad, por ejemplo, como puntos de referencia o de nodo hacia los cuales podr forzar el cursor o desfasar
los objetos. Si lo desea, podr especificar el estilo del punto, as como su tamao, en relacin con la pantalla o en unidades absolutas.
Las variables de sistema PDMODE y PDSIZE controlan el aspecto de los objetos de punto. Los valores 0, 2, 3 y 4 de PDMODE seleccionan una figura
que debe dibujarse a travs del punto. El valor 1 establece que no se visualice nada.
Aada 32, 64 o 96 al valor anterior para seleccionar una forma que debe dibujarse alrededor del punto adems de la que se dibuja para atravesarlo:
PDSIZE controla el tamao de las figuras de punto, salvo en los valores 0 y 1 de PDMODE. Al establecer PDSIZE en 0 se genera el punto al 5% de la
altura del rea grfica. Un valor positivo de PDSIZE especifica un tamao absoluto para las figuras de punto. Un valor negativo se interpreta como un
porcentaje del tamao de la ventana grfica. El tamao de todos los puntos vuelve a calcularse al regenerar el dibujo.
Despus de cambiar PDMODE y PDSIZE, la prxima vez que se regenere el dibujo cambiar el aspecto de los puntos existentes.
Para definir PDMODE y PDSIZE, utilice el mtodo SetVariable.
Creacin de un objeto Point y modificacin de su aspecto
El cdigo siguiente crea un objeto Point en las coordenadas (5, 5, 0) del espacio modelo. Despus se actualizan las variables de sistema PDMODE y
PDSIZE.
Sub Ch4_CreatePoint()
Dim pointObj As AcadPoint
Dim location(0 To 2) As Double
' Define the location of the point
location(0) = 5#: location(1) = 5#: location(2) = 0#
' Create the point
Set pointObj = ThisDrawing.ModelSpace.AddPoint(location)
ThisDrawing.SetVariable "PDMODE", 34
ThisDrawing.SetVariable "PDSIZE", 1
ZoomAll
End Sub
Cuando se crea un rea de relleno slido cuadrangular, la secuencia de los puntos tercero y cuarto determina su forma. Compare las figuras siguientes:
Los dos primeros puntos definen un lado del polgono. El tercer punto se define diagonalmente contrario al segundo. Si el cuarto punto se define igual
que el tercero, se crea un tringulo relleno.
Para crear un rea de relleno slido, utilice el mtodo AddSolid.
Para obtener ms informacin acerca del relleno de slidos, vase Creacin de reas de relleno slido en el Manual del usuario.
Creacin de un objeto con relleno slido
El cdigo del ejemplo siguiente crea un cuadriltero slido en las coordenadas (0, 0, 0), (5, 0, 0), (5, 8, 0) y (8, 8, 0) del espacio modelo.
Sub Ch4_CreateSolid()
Dim solidObj As AcadSolid
Dim point1(0 To 2) As Double
Dim point2(0 To 2) As Double
Dim point3(0 To 2) As Double
Dim point4(0 To 2) As Double
' Define the solid
point1(0) = 0#: point1(1) = 0#: point1(2) = 0#
point2(0) = 5#: point2(1) = 0#: point2(2) = 0#
point3(0) = 5#: point3(1) = 8#: point3(2) = 0#
point4(0) = 0#: point4(1) = 8#: point4(2) = 0#
' Create the solid object in model space
Set solidObj = ThisDrawing.ModelSpace.AddSolid _
(point1, point2, point3, point4)
ZoomAll
End Sub
Creacin de regiones
Para crear una regin, utilice el mtodo AddRegion Este mtodo crea una regin a partir de todos los bucles cerrados formados con la matriz de entrada
de curvas. AutoCAD convierte las polilneas 2D cerradas y las 3D planas en regiones distintas y, a continuacin, convierte las polilneas, lneas y curvas
que forman bucles planos cerrados. Si ms de dos curvas comparten un punto final, puede que la regin resultante sea arbitraria. Por esta razn, es
posible que algunas regiones en realidad se creen cuando se utilice el mtodo AddRegion. Utilice una variante que contenga la recin creada matriz de
regiones.
Puede calcular el total de objetos de regin creados mediante las funciones UBound y LBound de VBA, como ilustra el siguiente ejemplo:
UBound(objRegions) - LBound(objRegions) + 1
donde objRegions es un variante que contiene el valor de retorno de AddRegion. Esta instruccin calcula el nmero total de regiones creadas.
Creacin de una regin simple
Se pueden crear regiones compuestas mediante la sustraccin, combinacin o localizacin de la interseccin de regiones o slidos 3D. A continuacin,
se pueden extruir o girar las regiones compuestas para crear slidos complejos. Para crear una regin compuesta, utilice el mtodo Boolean.
Cuando se sustrae una regin de otra, se llama al mtodo Boolean desde la regin primera. Esta es la regin de la que debe realizar la sustraccin. Por
ejemplo, si desea calcular los metros de alfombrado que necesita para un suelo, llame al mtodo Boolean desde el contorno exterior del suelo y utilice
las zonas que no irn cubiertas con moqueta, como es el caso del espacio que ocupan las columnas o los mostradores, como objeto de la lista de
parmetros de Boolean.
Creacin de una regin compuesta
Sub Ch4_CreateCompositeRegions()
' Create two circles, one representing a room,
' the other a pillar in the center of the room
Dim RoomObjects(0 To 1) As AcadCircle
Dim center(0 To 2) As Double
Dim radius As Double
center(0) = 4
center(1) = 4
center(2) = 0
radius = 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 circles
Dim regions As Variant
regions = ThisDrawing.ModelSpace.AddRegion(RoomObjects)
' Copy the regions into the region variables for ease of use
Dim RoundRoomObj As AcadRegion
Dim PillarObj As AcadRegion
If regions(0).Area > regions(1).Area Then
' The first region is the room
Set RoundRoomObj = regions(0)
Set PillarObj = regions(1)
Else
' The first region is the pillar
Set 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 area
MsgBox "The carpet area is: " & RoundRoomObj.Area
End Sub
El reflejo de objetos crea una copia que es la imagen reflejada de un objeto con respecto a un eje o lnea de simetra. Se pueden reflejar todos los objetos
de dibujo.
Para reflejar un objeto, utilice el mtodo Mirror. Este mtodo requiere la entrada de dos coordenadas. Las dos coordenadas especificadas se convierten
en puntos finales de la lnea de simetra alrededor de la cual se refleja el objeto de base. En 3D, esta lnea orienta un plano de simetra perpendicular al
plano XY del SCP que contiene un eje de simetra especificado.
A diferencia del comando de simetra de AutoCAD, este mtodo sita en el dibujo la imagen reflejada y mantiene el objeto original. Si desea eliminar el
objeto original, utilice el mtodo Erase.
Para controlar las propiedades de simetra de objetos de texto, utilice la variable de sistema MIRRTEXT. El valor por defecto de MIRRTEXT es activada
(1), con el que la simetra de los objetos de texto se obtiene como la de los dems objetos. Cuando MIRRTEXT est desactivada (0), no se generan
imgenes simtricas de texto. Utilice los mtodos GetVariable y SetVariable para consultar y establecer el parmetro MIRRTEXT.
Puede obtener una imagen simtrica de un objeto de ventana grfica en espacio papel, aunque ello no afecta a la vista de los objetos en el espacio
modelo ni a los objetos de dicho espacio.
Para obtener informacin acerca del reflejo de objetos, vase Copia, desfase y reflejo de objetos en el Manual del usuario.
Reflexin de una polilnea con respecto a un eje
Este ejemplo crea una polilnea optimizada y la refleja con respecto a un eje de simetra. La nueva polilnea es de color azul.
Sub Ch4_MirrorPolyline()
' Create the polyline
Dim plineObj As AcadLWPolyline
Rotacin de objetos
Puede rotar todos los objetos de dibujo y todos los objetos de referencia de atributos.
Para rotar un objeto, utilice el mtodo Rotate del objeto. Este mtodo requiere la entrada de un punto base y de un ngulo de rotacin. El punto base es
una matriz de variantes con tres dobles. Estos dobles representan las coordenadas 3D del SCU que indican el punto sobre el que est definido el eje de
rotacin. El ngulo de rotacin se designa en radianes y determina cunto rota un objeto alrededor del punto base respecto de su posicin actual.
Para obtener ms informacin acerca de la rotacin de objetos, vase Rotacin de objetos en el Manual del usuario.
Rotacin de una polilnea con respecto a un punto base
Este ejemplo crea una polilnea optimizada cerrada y despus la gira 45 grados con respecto al punto base (4, 4.25, 0).
Sub Ch4_RotatePolyline()
' Create the polyline
Dim plineObj As AcadLWPolyline
Dim points(0 To 11) As Double
points(0) = 1: points(1) = 2
points(2) = 1: points(3) = 3
points(4) = 2: points(5) = 3
points(6) = 3: points(7) = 3
points(8) = 4: points(9) = 4
points(10) = 4: points(11) = 2
Set plineObj = ThisDrawing.ModelSpace. _
AddLightWeightPolyline(points)
plineObj.Closed = True
ZoomAll
' Define the rotation of 45 degrees about a
' base point of (4, 4.25, 0)
Dim basePoint(0 To 2) As Double
Dim rotationAngle As Double
basePoint(0) = 4: basePoint(1) = 4.25: basePoint(2) = 0
rotationAngle = 0.7853981 ' 45 degrees
' Rotate the polyline
plineObj.Rotate basePoint, rotationAngle
plineObj.Update
End Sub
Para ajustar el factor de escala de un objeto, utilice el mtodo ScaleEntity del objeto. Este mtodo ajusta la misma escala para el objeto en las
direcciones X, Y y Z. Acepta como entrada el punto base de la escala y un factor de escala. El punto base es una matriz de variantes con tres dobles.
Estos dobles representan las coordenadas 3D del SCU que indican el punto donde comienza la escala. El factor de escala es el valor sobre el que se
ajusta la escala del objeto. Las cotas del objeto se multiplican por el factor de escala. Un factor de escala superior al valor 1 ampla el objeto. Un factor
de escala entre 0 y 1 reduce el objeto.
Para obtener ms informacin acerca de la aplicacin de escala, vase Ajuste del tamao o la forma de los objetos en el Manual del usuario.
Cambio de la escala de una polilnea
Este ejemplo crea una polilnea optimizada cerrada y despus ajusta su escala con un factor 0.5.
Sub Ch4_ScalePolyline()
' Create the polyline
Dim plineObj As AcadLWPolyline
Dim points(0 To 11) As Double
points(0) = 1: points(1) = 2
points(2) = 1: points(3) = 3
points(4) = 2: points(5) = 3
points(6) = 3: points(7) = 3
points(8) = 4: points(9) = 4
points(10) = 4: points(11) = 2
Set plineObj = ThisDrawing.ModelSpace. _
AddLightWeightPolyline(points)
plineObj.Closed = True
ZoomAll
' Define the scale
Dim basePoint(0 To 2) As Double
Dim scalefactor As Double
basePoint(0) = 4: basePoint(1) = 4.25: basePoint(2) = 0
scalefactor = 0.5
' Scale the polyline
plineObj.ScaleEntity basePoint, scalefactor
plineObj.Update
End Sub
Transformacin de objetos
Un objeto se puede desplazar, cambiar de escala o rotar con una matriz de transformacin de 4 por 4 utilizando el mtodo TransformBy.
En la tabla siguiente se muestra la configuracin de la matriz de transformacin, donde R = rotacin y T = transformacin.
Configuracin de la matriz de transformacin
R00
R01
R02
T0
R10
R11
R12
T1
R20
R21
R22
T2
Para transformar un objeto, es necesario inicializar antes la matriz de transformacin. En el siguiente ejemplo se muestra una matriz de transformacin,
asignada a la variable tMatrix, que rota una entidad 90 grados alrededor del punto (0, 0, 0):
tMatrix(0,0)
tMatrix(0,1)
tMatrix(0,2)
tMatrix(0,3)
tMatrix(1,0)
tMatrix(1,1)
tMatrix(1,2)
tMatrix(1,3)
tMatrix(2,0)
tMatrix(2,1)
tMatrix(2,2)
tMatrix(2,3)
tMatrix(3,0)
tMatrix(3,1)
tMatrix(3,2)
tMatrix(3,3)
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
0.0
-1.0
0.0
0.0
1.0
0.0
0.0
0.0
0.0
0.0
1.0
0.0
0.0
0.0
0.0
1.0
Una vez terminada la matriz de transformacin, debe aplicarse al objeto con el mtodo TransformBy. La siguiente lnea de cdigo es una demostracin
de cmo se aplica una matriz (tMatrix) a un objeto (anObj):
anObj.TransformBy tMatrix
Este ejemplo crea una lnea y la gira 90 grados aplicando una matriz de transformacin.
Sub Ch4_TransformBy()
' Create a line
Dim lineObj As AcadLine
Dim startPt(0 To 2) As Double
Dim endPt(0 To 2) As Double
startPt(2) = 0
startPt(1) = 1
startPt(2) = 0
endPt(0) = 5
endPt(1) = 1
endPt(2) = 0
Set 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 Double
transMat(0, 0) = 0#: transMat(0, 1) = -1#
transMat(0, 2) = 0#: transMat(0, 3) = 0#
transMat(1, 0) = 1#: transMat(1, 1) = 0#
transMat(1, 2) = 0#: transMat(1, 3) = 0#
transMat(2, 0) = 0#: transMat(2, 1) = 0#
transMat(2, 2) = 1#: transMat(2, 3) = 0#
transMat(3, 0) = 0#: transMat(3, 1) = 0#
transMat(3, 2) = 0#: transMat(3, 3) = 1#
' Transform the line using the defined transformation matrix
lineObj.TransformBy transMat
lineObj.Update
End Sub
-1.0
0.0
0.0
1.0
0.0
0.0
0.0
0.0
0.0
1.0
0.0
0.0
0.0
0.0
1,0
-0.707107
0.0
5.0
0.707107
0.707107
0.0
-2.071068
0.0
0.0
1.0
0.0
0.0
0.0
0.0
1.0
0.0
0.0
10.0
0.0
1.0
0.0
10.0
0.0
0.0
1.0
0.0
0.0
0.0
0.0
1.0
0.0
0.0
0.0
0.0
10.0
0.0
0.0
0.0
0.0
10.0
0.0
0.0
0.0
0.0
1.0
0.0
0.0
-18.0
0.0
10.0
0.0
-18.0
0.0
0.0
10.0
0.0
0.0
0.0
0.0
1.0
En este ejemplo se crea una lnea y se cambia su punto final, con lo que aumenta su longitud.
Sub Ch4_LengthenLine()
' Define and create the line
Dim lineObj As AcadLine
Dim startPoint(0 To 2) As Double
Dim endPoint(0 To 2) As Double
startPoint(0) = 0
startPoint(1) = 0
startPoint(2) = 0
endPoint(0) = 1
endPoint(1) = 1
endPoint(2) = 1
Set lineObj = ThisDrawing.ModelSpace. _
AddLine(startPoint, endPoint)
lineObj.Update
' Lengthen the line by changing the
' endpoint to 4, 4, 4
endPoint(0) = 4
endPoint(1) = 4
endPoint(2) = 4
lineObj.endPoint = endPoint
lineObj.Update
End Sub
Descomposicin de objetos
La descomposicin de objetos fragmenta los objetos individuales en sus partes constitutivas, pero sus efectos no son visibles en la pantalla. Por ejemplo,
la descomposicin de formas de lugar a lneas y arcos a partir de polgonos 3D, polilneas, mallas poligonales y regiones. Sustituye una referencia a
bloque con copias de los objetos simples que componen el bloque.
Para obtener informacin acerca de la descomposicin de objetos, vase Disociacin de objetos compuestos (Descomponer) en el Manual del usuario.
Descomposicin de una polilnea
Este ejemplo crea un objeto de polilnea optimizada. Despus la descompone en varios objetos. El ejemplo realiza un bucle en los objetos resultantes y
muestra un cuadro de mensaje que contiene el nombre de todos los objetos y su ndice en la lista de objetos descompuestos.
Sub Ch4_ExplodePolyline()
Dim plineObj As AcadLWPolyline
Dim points(0 To 11) As Double
' Define the 2D polyline points
points(0) = 1: points(1) = 1
points(2) = 1: points(3) = 2
points(4) = 2: points(5) = 2
points(6) = 3: points(7) = 2
points(8) = 4: points(9) = 4
points(10) = 4: points(11) = 1
' Create a light weight Polyline object
Set plineObj = ThisDrawing.ModelSpace. _
AddLightWeightPolyline(points)
' Set the bulge on one segment to vary the
' type of objects in the polyline
plineObj.SetBulge 3, -0.5
plineObj.Update
' Explode the polyline
Dim explodedObjects As Variant
explodedObjects = plineObj.Explode
' Loop through the exploded objects
' and display a message box with
' the type of each object
Dim I As Integer
For I = 0 To UBound(explodedObjects)
explodedObjects(I).Update
MsgBox "Exploded Object " & I & ": " & _
explodedObjects(I).ObjectName
explodedObjects(I).Update
Next
End Sub
Edicin de polilneas
Las polilneas 2D y 3D, los rectngulos, los polgonos y las mallas poligonales 3D son variantes de polilneas y se editan de la misma manera que ellas.
AutoCAD reconoce tanto las polilneas ajustadas como las polilneas ajustadas en forma de splines. Una polilnea ajustada en forma de spline utiliza un
ajuste de curva, similar a una B-spline. Existen dos tipos de polilneas ajustadas en forma de spline: cuadrticas y cbicas. Las dos polilneas estn
controladas por la variable de sistema SPLINETYPE. Una polilnea ajustada utiliza curvas estndar para el ajuste de curvas y cualquier direccin
tangente definida en un vrtice determinado.
Para modificar una polilnea, utilice las propiedades y los mtodos de los objetos LightweightPolyline o Polyline. Para abrir o cerrar una polilnea,
cambiar las coordenadas de un vrtice de polilnea o agregar un vrtice, utilice los siguientes mtodos y propiedades:
Closed (propiedad)
Abre o cierra la polilnea.
Coordinates (propiedad)
Especifica las coordenadas de cada vrtice de la polilnea.
AddVertex (mtodo)
Aade un vrtice a una polilnea optimizada.
Utilice los siguientes mtodos para actualizar la curvatura o la anchura de una polilnea:
SetBulge
Define la curvatura de una polilnea, dado el ndice de segmentos.
SetWidth
Define las anchuras inicial y final de una polilnea, dado el ndice de segmentos.
Para obtener ms informacin acerca de la modificacin de polilneas, vase Modificacin o unin de polilneas en el Manual del usuario.
Modificacin de una polilnea
Este ejemplo crea una polilnea optimizada. Despus aade una curvatura al tercer segmento de la polilnea, aade un vrtice, cambia la anchura del
ltimo segmento y, por ltimo, la cierra.
Sub Ch4_EditPolyline()
Dim plineObj As AcadLWPolyline
Dim points(0 To 9) As Double
' Define the 2D polyline points
points(0) = 1: points(1) = 1
points(2) = 1: points(3) = 2
points(4) = 2: points(5) = 2
points(6) = 3: points(7) = 2
points(8) = 4: points(9) = 4
' Create a light weight Polyline object
Set plineObj = ThisDrawing.ModelSpace. _
AddLightWeightPolyline(points)
' Add a bulge to segment 3
plineObj.SetBulge 3, -0.5
' Define the new vertex
Dim newVertex(0 To 1) As Double
newVertex(0) = 4: newVertex(1) = 1
' Add the vertex to the polyline
plineObj.AddVertex 5, newVertex
' Set the width of the new segment
plineObj.SetWidth 4, 0.1, 0.5
' Close the polyline
plineObj.Closed = True
plineObj.Update
End Sub
Modificacin de splines
Utilice las siguientes propiedades modificables para cambiar curvas spline:
ControlPoints
Especifica los puntos de apoyo de la spline.
EndTangent
Establece la tangente final de la spline como vector de direccin.
FitPoints
Especifica todos los puntos de ajuste de la spline.
FitTolerance
Vuelve a ajustar la curva Spline a los puntos existentes con los valores de tolerancia nuevos.
Knots
Especifica el vector nodal de la spline.
StartTangent
Especifica la tangente inicial de la spline.
Tambin puede utilizar estos mtodos para editar splines:
AddFitPoint
Agrega un punto de ajuste a la spline en el ndice indicado.
DeleteFitPoint
Suprime el punto de ajuste de una spline en el ndice indicado.
ElevateOrder
Eleva el orden de la spline hasta el orden indicado.
GetFitPoint
Define el punto de ajuste en el ndice indicado (slo un punto de ajuste. (Slo un punto de ajuste. Para consultar todos los puntos de ajuste de la spline,
utilice la propiedad FitPoints).
Invertir
Invierte la direccin de la spline.
SetControlPoint
Define el punto de apoyo de la spline en el ndice indicado.
SetFitPoint
Define el punto de ajuste en el ndice indicado. (Slo un punto de ajuste. Para consultar todos los puntos de ajuste de la spline, utilice la propiedad
FitPoints).
SetWeight
Define el grosor del punto de apoyo en un ndice dado.
Utilice las siguientes propiedades de slo lectura para consultar splines:
Area
Obtiene el rea cerrada de una spline.
Closed
Indica si la spline est abierta o cerrada.
Degree
Obtiene el grado de la representacin polinmica de la spline.
IsPeriodic
Este ejemplo crea una curva spline y cambia su primer punto de apoyo.
Sub Ch4_ChangeSplineControlPoint()
' Create the spline
Dim splineObj As AcadSpline
Dim startTan(0 To 2) As Double
Dim endTan(0 To 2) As Double
Dim fitPoints(0 To 8) As Double
startTan(0) = 0.5: startTan(1) = 0.5: startTan(2) = 0
endTan(0) = 0.5: endTan(1) = 0.5: endTan(2) = 0
fitPoints(0) = 1: fitPoints(1) = 1: fitPoints(2) = 0
fitPoints(3) = 5: fitPoints(4) = 5: fitPoints(5) = 0
fitPoints(6) = 10: fitPoints(7) = 0: fitPoints(8) = 0
Set splineObj = ThisDrawing.ModelSpace. _
AddSpline(fitPoints, startTan, endTan)
splineObj.Update
' Change the coordinate of the first fit point
Dim controlPoint(0 To 2) As Double
controlPoint(0) = 0
controlPoint(1) = 3
controlPoint(2) = 0
splineObj.SetControlPoint 0, controlPoint
splineObj.Update
End Sub
Definicin de coordenadas 3D
Introducir coordenadas 3D en el sistema de coordenadas universales (SCU) es similar a introducir coordenadas 2D en dicho sistema. Adems de
especificar los valores X e Y, el usuario especifica un valor Z. Al igual que ocurre con las coordenadas 2D, se utiliza una variante para pasar las
coordenadas a los mtodos y propiedades ActiveX y para consultar las coordenadas.
Para obtener ms informacin acerca de la definicin de coordenadas 3D, vase Introduccin de coordenadas 3D en el Manual del usuario.
Definicin y consulta de coordenadas en polilneas 2D y 3D
En este ejemplo se crean dos polilneas, cada una con tres coordenadas. La primera es una polilnea 2D y la segunda 3D. Observe que la longitud de la
matriz que contiene los vrtices est ampliada para incluir las coordenadas Z en la creacin de la polilnea 3D. El ejemplo termina con la consulta de las
coordenadas de las polilneas, que se muestran en un cuadro de mensaje.
Sub Ch8_Polyline_2D_3D()
Dim pline2DObj As AcadLWPolyline
Dim pline3DObj As AcadPolyline
Dim points2D(0 To 5) As Double
Dim points3D(0 To 8) As Double
' Define three 2D polyline points
points2D(0) = 1: points2D(1) = 1
points2D(2) = 1: points2D(3) = 2
points2D(4) = 2: points2D(5) = 2
' Define three 3D polyline points
points3D(0) = 1: points3D(1) = 1: points3D(2) = 0
points3D(3) = 2: points3D(4) = 1: points3D(5) = 0
points3D(6) = 2: points3D(7) = 2: points3D(8) = 0
' Create the 2D light weight Polyline
Set pline2DObj = ThisDrawing.ModelSpace. _
AddLightWeightPolyline(points2D)
pline2DObj.Color = acRed
pline2DObj.Update
' Create the 3D polyline
Set pline3DObj = ThisDrawing.ModelSpace. _
AddPolyline(points3D)
pline3DObj.Color = acBlue
pline3DObj.Update
' Query the coordinates of the polylines
Dim get2Dpts As Variant
Dim get3Dpts As Variant
get2Dpts = pline2DObj.Coordinates
get3Dpts = pline3DObj.Coordinates
' Display the coordinates
MsgBox ("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
& _
& _
_
_
_
Puede definir un sistema de coordenadas personales ( SCP ) para cambiar el emplazamiento del punto de origen (0, 0, 0) y la orientacin del plano XY y
del eje Z. Un SCP se puede colocar y orientar en cualquier punto del espacio tridimensional. Se pueden definir, guardar y utilizar tantos sistemas de
coordenadas como se necesiten. La introduccin y visualizacin de las coordenadas depende del sistema SCP que est activo.
Para indicar el origen y la orientacin del SCP, puede mostrar el icono SCP en el punto de origen del SCP mediante la propiedad UCSIconAtOrigin. Si el
icono SCP est activado (vase la propiedad UCSIconOn) pero no aparece en el origen, se muestra en la coordenada del SCU definida por la variable de
sistema UCSORG.
Puede crear un sistema de coordenadas personales con el mtodo Add. Este mtodo requiere cuatro valores de entrada: la coordenada del origen, una
coordenada en los ejes X e Y, y el nombre del SCP.
Todas las coordenadas de ActiveX Automation de AutoCAD se introducen en el sistema de coordenadas universales. Utilice el mtodo GetUCSMatrix
para volver a la matriz de transformacin de un SCP concreto. Utilice esta matriz de transformacin para buscar las coordenadas SCU equivalentes.
Para activar un SCP, utilice la propiedad ActiveUCS del objeto Document. Si se realizan cambios en el SCP activo, el nuevo objeto de SCP debe
restablecerse como SCP activo para que los cambios se vean. Para restablecer el SCP activo, slo hay que llamar a la propiedad ActiveUCS de nuevo
con el objeto de SCP actualizado.
Para obtener ms informacin sobre la definicin del SCP, vase Control del sistema de coordenadas personales (SCP) en 3D en el Manual del
usuario.
Creacin de un SCP nuevo, activacin y traduccin de las coordenadas de un punto a SCP
La siguiente subrutina crea un nuevo SCP y lo establece como el SCP activo del dibujo. A continuacin, pide al usuario que designe un punto del dibujo
y devuelve las coordenadas SCU y SCP del punto.
Sub Ch8_NewUCS()
' Define the variables we will need
Dim ucsObj As AcadUCS
Dim origin(0 To 2) As Double
Dim xAxisPnt(0 To 2) As Double
Dim yAxisPnt(0 To 2) As Double
' Define the UCS points
origin(0) = 4: origin(1) = 5: origin(2) = 3
xAxisPnt(0) = 5: xAxisPnt(1) = 5: xAxisPnt(2) = 3
yAxisPnt(0) = 4: yAxisPnt(1) = 6: yAxisPnt(2) = 3
' Add the UCS to the
' UserCoordinatesSystems collection
Set ucsObj = ThisDrawing.UserCoordinateSystems. _
Add(origin, xAxisPnt, yAxisPnt, "New_UCS")
' Display the UCS icon
ThisDrawing.ActiveViewport.UCSIconAtOrigin = True
ThisDrawing.ActiveViewport.UCSIconOn = True
' Make the new UCS the active UCS
ThisDrawing.ActiveUCS = ucsObj
MsgBox "The current UCS is : " & ThisDrawing.ActiveUCS.Name _
& vbCrLf & " Pick a point in the drawing."
' Find the WCS and UCS coordinate of a point
Dim WCSPnt As Variant
Dim UCSPnt As Variant
WCSPnt = 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
En este ejemplo se crea una malla poligonal de . La direccin de la ventana grfica activa se ajusta de forma que la naturaleza tridimensional de la
malla se visualiza con ms facilidad.
Sub Ch8_Create3DMesh()
Dim meshObj As AcadPolygonMesh
Dim mSize, nSize, Count As Integer
Dim points(0 To 47) As Double
' create the matrix of points
points(0) = 0: points(1) = 0: points(2) = 0
points(3) = 2: points(4) = 0: points(5) = 1
points(6) = 4: points(7) = 0: points(8) = 0
points(9) = 6: points(10) = 0: points(11) = 1
points(12) = 0: points(13) = 2: points(14) = 0
points(15) = 2: points(16) = 2: points(17) = 1
points(18) = 4: points(19) = 2: points(20) = 0
points(21) = 6: points(22) = 2: points(23) = 1
points(24) = 0: points(25) = 4: points(26) = 0
points(27) = 2: points(28) = 4: points(29) = 1
points(30) = 4: points(31) = 4: points(32) = 0
points(33) = 6: points(34) = 4: points(35) = 0
points(36) = 0: points(37) = 6: points(38) = 0
points(39) = 2: points(40) = 6: points(41) = 1
points(42) = 4: points(43) = 6: points(44) = 0
points(45) = 6: points(46) = 6: points(47) = 0
mSize = 4: nSize = 4
' creates a 3Dmesh in model space
Set meshObj = ThisDrawing.ModelSpace. _
Add3DMesh(mSize, nSize, points)
' Change the viewing direction of the viewport
' to better see the cylinder
Dim NewDirection(0 To 2) As Double
NewDirection(0) = -1
NewDirection(1) = -1
NewDirection(2) = 1
ThisDrawing.ActiveViewport.direction = NewDirection
ThisDrawing.ActiveViewport = ThisDrawing.ActiveViewport
ZoomAll
End Sub
En este ejemplo se crea una malla policara en espacio modelo. Despus se actualiza la direccin de visualizacin de la ventana grfica activa para
permitir una mejor visin de la naturaleza tridimensional de la malla.
Sub Ch8_CreatePolyfaceMesh()
En el siguiente ejemplo se crea un slido con forma de cua en espacio modelo. Despus se actualiza la direccin de visualizacin de la ventana grfica
activa para permitir una mejor visin de la naturaleza tridimensional de la cua.
Sub Ch8_CreateWedge()
Dim wedgeObj As Acad3DSolid
Dim center(0 To 2) As Double
Dim length As Double
Dim width As Double
Dim height As Double
' Define the wedge
center(0) = 5#: center(1) = 5#: center(2) = 0
Modificacin de slidos 3D
Una vez creado un slido, puede proceder a la creacin de formas slidas ms complejas mediante la combinacin de distintos objetos slidos. Puede
optar por unir slidos, sustraerlos o localizar su volumen comn (partes superpuestas). Utilice el mtodo Boolean o CheckInterference para efectuar
dichas combinaciones.
Los slidos se pueden modificar tambin mediante la obtencin de la seccin transversal bidimensional de un slido o el corte de un slido en dos
partes. Utilice el mtodo SectionSolid para buscar secciones transversales de slidos, y el mtodo SliceSolid para cortar un slido en dos partes.
Bsqueda de la interferencia entre dos slidos
En este ejemplo se crea un prisma rectangular y un cilindro en espacio modelo. A continuacin, se localiza la interferencia entre los dos slidos y se crea
un slido nuevo a partir de ella. Para facilitar la visualizacin, el prisma se colorea en blanco, el cilindro en cin y el slido de interferencia en rojo.
Sub Ch8_FindInterferenceBetweenSolids()
' Define the box
Dim boxObj As Acad3DSolid
Dim length As Double
Dim width As Double
Dim height As Double
Dim center(0 To 2) As Double
En este ejemplo se crea un prisma rectangular en espacio modelo. Despus se corta tomando como referencia un plano definido por tres puntos. La
seccin se devuelve como slido 3D.
Sub Ch8_SliceABox()
' Create the box object
Dim boxObj As Acad3DSolid
Dim length As Double
Dim width As Double
Dim height As Double
Dim center(0 To 2) As Double
center(0) = 5#: center(1) = 5#: center(2) = 0
length = 5#: width = 7: height = 10#
' Create the box (3DSolid) object in model space
Set boxObj = ThisDrawing.ModelSpace. _
AddBox(center, length, width, height)
boxObj.Color = acWhite
' Define the section plane with three points
Dim slicePt1(0 To 2) As Double
Dim slicePt2(0 To 2) As Double
Dim slicePt3(0 To 2) As Double
slicePt1(0) = 1.5: slicePt1(1) = 7.5: slicePt1(2) = 0
slicePt2(0) = 1.5: slicePt2(1) = 7.5: slicePt2(2) = 10
slicePt3(0) = 8.5: slicePt3(1) = 2.5: slicePt3(2) = 10
' slice the box and color the new solid red
Dim sliceObj As Acad3DSolid
Set sliceObj = boxObj.SliceSolid _
(slicePt1, slicePt2, slicePt3, True)
sliceObj.Color = acRed
ZoomAll
End Sub
Este aprendizaje muestra cmo utilizar ActiveX y Visual Basic para Aplicaciones (VBA) y cmo aadir una macro a AutoCAD. Se orienta hacia la
arquitectura paisajstica, pero los conceptos que contiene se pueden aplicar a cualquier especialidad.
Este Aprendizaje est destinado al usuario avanzado de AutoCAD que a su vez es principiante en programacin VBA.
Inspeccionar el entorno
Definir el objetivo
La primera funcin
Obtencin de datos
Ejecucin de la macro
Inspeccionar el entorno
Para el aprendizaje, necesitar el entorno de desarrollo integrado de VBA (VBA IDE) de AutoCAD. VBA IDE se instala automticamente con la opcin
de instalacin Completa del programa de instalacin de AutoCAD. Si seleccion la opcin de instalacin Personalizada en el momento de instalar
AutoCAD, VBA IDE puede no haberse instalado. Es posible que tenga que instalarlo ejecutando de nuevo el programa de instalacin de AutoCAD.
Para comprobar si VBA IDE est instalado
1. Inicie AutoCAD.
2. En la lnea de comando, escriba vbaide y pulse INTRO.
Si se abre VBA IDE, esto significa que est instalado. Si aparece el mensaje AutoCAD VBA no se encuentra instalado, VBA IDE no est
instalado.
Definir el objetivo
El objetivo de este aprendizaje es desarrollar una nueva macro para AutoCAD que dibuje el camino de un jardn y lo rellene con losetas circulares de
cemento. La nueva macro tendr la siguiente secuencia de solicitudes:
Command: gardenpath
Punto inicial del camino: El usuario especificar el punto inicial
Punto final del camino: El usuario especificar el punto final
Mitad de la anchura del camino: El usuario especificar un nmero
La primera funcin
La macro Gardenpath se desarrolla utilizando una serie de funciones y subrutinas. Muchas subrutinas requieren la manipulacin de ngulos. Puesto que
ActiveX especifica ngulos en radianes, pero la mayora de los usuarios utiliza grados para medir ngulos, comenzaremos por crear una funcin que
convierta grados a radianes.
Para convertir grados a radianes
Observe que tan pronto como se pulsa INTRO despus de escribir la lnea Function dtr(a As Double) As Double,End Function se aade
automticamente. Esto garantiza que todas las subrutinas y funciones tienen una instruccin End asociada.
Ahora revise el cdigo. Primero, la constante pi se define con el valor de 3.14159. Esto permite que se utilice la palabra pi en lugar de tener que
teclear 3.14159 cada vez que vaya a usar el valor.
A continuacin, define una funcin llamada dtr (abreviacin de grados a radianes). La funcin dtr toma un argumento, a, que es el ngulo en
grados. El resultado se obtiene dividiendo el ngulo en grados por 180 y, a continuacin, multiplicando su valor por pi. La lnea que comienza
por una comilla simple es un comentario. VBA ignora todo el texto que haya en una lnea despus de una comilla simple.
Ahora esta funcin puede utilizarse en otras subrutinas de todo el proyecto
4. Guarde su trabajo. Pulse Archivo Guardar Global1. Escriba gardenpath.dvb como nombre del proyecto.
A continuacin, aadir una funcin para calcular la distancia entre puntos.
Para calcular la distancia entre dos puntos
2. Guarde su trabajo.
Obtencin de datos
La macro Gardenpath pregunta al usuario dnde debe dibujarse el camino, qu anchura debe tener, de qu tamao son las losetas de cemento y cul es el
espacio entre stas. Ahora definir una subrutina que solicita al usuario todos estos datos y que calcula diversos nmeros que se utilizarn en el resto de
la macro.
En esta subrutina, utilizar los mtodos de entrada de datos de usuario del objeto Utility.
Declaracin de variables
Declaracin de variables
La siguiente subrutina utiliza diversas variables. Todas las variables deben declararse previamente para que la subrutina pueda acceder a ellas.
En VBA IDE, escriba el siguiente cdigo en la ventana Cdigo, inmediatamente despus de la lnea Const pi = 3.14159:
Private
Private
Private
Private
Private
Private
Private
Private
Private
Private
sp(0 To 2) As Double
ep(0 To 2) As Double
hwidth As Double
trad As Double
tspac As Double
pangle As Double
plength As Double
totalwidth As Double
angp90 As Double
angm90 As Double
Ahora observe las dos listas desplegables de la parte superior de la ventana Cdigo. Estas listas se denominan cuadro Objeto y cuadro
Procedimiento/Evento y actualmente muestran respectivamente los trminos (General) y (Declaraciones). Estas listas muestran la seccin del cdigo en
la que est trabajando en este momento, y le permiten desplazarse rpidamente a otra seccin simplemente seleccionndola en la lista. La seccin
(Declaraciones) es el lugar apropiado para declarar variables que va a utilizar en ms de una subrutina.
La subrutina gpuser solicita al usuario la informacin necesaria para dibujar un camino de jardn. Escriba lo siguiente despus de la funcin distance:
' Adquisicin de informacin para el camino del jardn
Private Sub gpuser()
Dim varRet As Variant
varRet = ThisDrawing.Utility.GetPoint( _
En la subrutina gpuser, la lnea Dim varRet As Variant declara la variable varRet. Puesto que esta variable se utiliza solamente en esta subrutina, puede
declararse aqu localmente, en vez de hacerlo en la seccin (Declaraciones).
La siguiente lnea, varRet = ThisDrawing.Utility.GetPoint( , "Punto inicial del camino: "), llama al mtodo GetPoint. El carcter de subrayado sirve para
que una lnea larga sea ms fcil de leer, ya que indica a VBA que debe leer esa lnea y la siguiente como si formaran una sola lnea. El carcter de
subrayado puede eliminarse colocando todo el cdigo en una nica lnea.
Para acceder al mtodo GetPoint, antes debe ir al objeto ThisDrawing que representa el dibujo actual. Despus de escribir ThisDrawing se escribe un
punto (.), lo que significa que va a acceder a algo que hay dentro de ese objeto. Despus del punto, se escribe Utility y otro punto. Una vez ms, va a
acceder a algo que hay dentro del objeto Utility. Finalmente, escriba GetPoint, que es el nombre del mtodo que se est invocando.
El mtodo GetPoint toma dos parmetros. El primer parmetro es opcional y no se utilizar. Deje el parmetro en blanco y escriba nicamente una coma
para marcar su ubicacin. El segundo parmetro es la solicitud, que tambin es opcional. Para este parmetro, ha escrito una cadena que solicita al
usuario que especifique el punto inicial. El punto especificado por el usuario se coloca en la variable varRet. Las tres lneas siguientes de la subrutina
copian el punto devuelto por el usuario en la matriz sp.
El punto final se obtiene de la misma forma.
El mtodo GetDistance se utiliza para obtener la mitad de la anchura del camino (hwidth), el radio de las losetas (trad), y el espacio entre stas (tspac).
El mtodo GetDistance utiliza dos parmetros. El primer parmetro es un punto base. Para este valor, usted determina el punto inicial. El segundo
parmetro es la solicitud, para la que proporciona una cadena que solicita al usuario el dato correspondiente. Lo interesante acerca del mtodo
GetDistance es que puede devolver tanto un valor escrito en la lnea de comando como la distancia entre el punto inicial y un punto seleccionado en
AutoCAD.
La subrutina continua calculando diversas variables utilizadas ms tarde en la macro. La variable pangle se define con el ngulo entre los puntos inicial
y final y se halla utilizando el mtodo AngleFromXAxis. La anchura del camino se halla multiplicando la mitad de la anchura por dos. La variable
plength se define como la longitud del camino y se halla utilizando la funcin distancia escrita anteriormente. Finalmente, se calcula y se guarda el
ngulo del camino ms y menos 90 grados en angp90 y angm90, respectivamente.
La siguiente ilustracin muestra la forma en la que las variables obtenidas por gpuser especifican las dimensiones del camino.
Ahora que ha obtenido la ubicacin y la anchura del camino, puede dibujar su contorno. Aada el siguiente cdigo bajo la subrutina gpuser:
' Dibujo del contorno del camino
Private Sub drawout()
Dim points(0 To 9) As Double
Dim pline As AcadLWPolyline
Dim varRet As Variant
varRet = ThisDrawing.Utility.PolarPoint( _
Esta subrutina dibuja el contorno del camino utilizando el mtodo AddLightweightPolyline. Este mtodo requiere un parmetro: una matriz de puntos
que genere la polilnea. Debe hallar todos los puntos que forman el objeto de polilnea y colocarlos en una matriz en el orden en que deben dibujarse.
Para esta polilnea, los puntos necesarios son los vrtices del camino.
Para hallar los vrtices del camino, utilice el mtodo PolarPoint. Este mtodo encuentra un punto que est a un ngulo y una distancia determinados
desde un punto base. Comience por el punto inicial (sp) y encuentre el primer vrtice del camino trabajando en direccin contraria a las agujas del reloj.
Este vrtice estar a una distancia equivalente a la mitad de la anchura del camino (hwidth) y a -90 grados del ngulo del camino. Puesto que desea
dibujar un rectngulo cerrado para el camino, ese punto se convierte en el primer y ltimo punto de la matriz. Por lo tanto, las coordenadas X e Y
obtenidas con el mtodo PolarPoint se desplazan a la primera y a la ltima posicin de la matriz de puntos.
Los restantes vrtices del camino se hallan de la misma forma utilizando la longitud y la anchura del camino (plength y width), y el ngulo del camino.
Cada vez que se invoca el mtodo PolarPoint, las coordenadas obtenidas (varRet) se copian en la matriz de puntos.
Una vez identificados los vrtices en la matriz de puntos, se invoca el mtodo AddLightweightPolyline. Observe que este mtodo es invocado desde el
objeto ModelSpace. Si ejecutara esta macro, vera que la polilnea todava no es visible en AutoCAD. La polilnea no ser visible hasta que actualice la
visualizacin, cosa que har m
Ahora que se ha desarrollado la subrutina de entrada de datos de usuario y la subrutina para dibujar el contorno, ya se puede rellenar el camino con
losetas circulares. Esta tarea requiere algo de geometra.
En VBA IDE, escriba el siguiente cdigo en la ventana Cdigo, despus de la rutina drawout:
' Colocacin de una hilera de losetas a lo largo de la distancia dada del camino
' y posiblemente desfase de sta
Private Sub drow(pd As Double, offset As Double)
Dim pfirst(0 To 2) As Double
Dim pctile(0 To 2) As Double
Dim pltile(0 To 2) As Double
Dim cir As AcadCircle
Dim varRet As Variant
varRet = ThisDrawing.Utility.PolarPoint( _
sp, pangle, pd)
pfirst(0) = varRet(0)
pfirst(1) = varRet(1)
pfirst(2) = varRet(2)
varRet = ThisDrawing.Utility.PolarPoint( _
pfirst, angp90, offset)
pctile(0) = varRet(0)
pctile(1) = varRet(1)
pctile(2) = varRet(2)
pltile(0) = pctile(0)
pltile(1) = pctile(1)
pltile(2) = pctile(2)
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)
Loop
varRet = 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)
Loop
End Sub
' Dibujo de las hileras de losetas
Private Sub drawtiles()
Dim pdist As Double
Dim offset As Double
pdist = trad + tspac
offset = 0
Do While pdist <= (plength - trad)
drow pdist, offset
pdist = pdist + ((tspac + trad + trad) * Sin(dtr(60)))
If offset = 0 Then
offset = (tspac + trad + trad) * Cos(dtr(60))
Else
offset = 0
End If
Loop
End Sub
Para comprender cmo funcionan estas subrutinas, consulte la siguiente ilustracin. La subrutina drow dibuja una hilera de losetas a una distancia dada a
lo largo del camino especificada por su primer argumento, y desfasa la hilera perpendicularmente al camino con una distancia especificada por el
segundo argumento. Se desea desfasar las losetas en hileras alternas para que cubran ms espacio y se distribuyan de forma ms esttica.
La subrutina drow halla la ubicacin de la primera hilera mediante el mtodo PolarPoint para desplazarla a lo largo del camino con la distancia
especificada por el primer argumento. La subrutina vuelve a utilizar entonces el mtodo PolarPoint para desplazarse perpendicularmente al camino para
efectuar el desfase. La subrutina utiliza la instruccin While para continuar dibujando crculos hasta que se encuentra el final del camino. El mtodo
PolarPoint de la primera instruccin While se desplaza a la siguiente posicin de loseta creando un espacio equivalente a dos radios de loseta (trad) ms
un espacio entre losetas (tspac). El segundo bucle while dibuja entonces las losetas de la hilera en la otra direccin hasta que se encuentra el otro borde.
La subrutina drawtiles invoca drow repetidamente hasta que se dibujan todas las hileras de losetas. La subrutina While loop recorre paso a paso el
camino, invocando drow para cada hilera. Las losetas de las hileras adyacentes forman tringulos equilteros, tal como se muestra en la ilustracin
anterior. Las aristas de estos tringulos equivalen al doble del radio de la loseta ms el espacio entre losetas. Por lo tanto, por la trigonometra, la
distancia a lo largo del camino entre hileras es el seno de 60 grados multiplicado por esta cantidad, y el desfase de las hileras impares es el coseno
sesenta grados multiplicado por esta cantidad.
La instruccin If se utiliza en drawtiles para desfasar hileras alternas. Si el desfase es igual a 0, defnalo como el espacio entre los centros de las hileras
multiplicadas por el coseno de 60 grados, tal como se explic anteriormente. Si el desfase no es igual a 0, establzcalo en 0. Esto alterna el desfase de las
hileras de la forma deseada.
Guarde su trabajo.
Integracin de los elementos
Ahora ya es posible combinar las subrutinas en la macro Gardenpath. En VBA IDE escriba el siguiente cdigo en la ventana Cdigo, despus de la
subrutinadrawtiles:
' Ejecucin del comando, invocando las funciones constituyentes
Sub gardenpath()
Dim sblip As Variant
Dim scmde As Variant
gpuser
sblip = ThisDrawing.GetVariable("blipmode")
scmde = ThisDrawing.GetVariable("cmdecho")
ThisDrawing.SetVariable "blipmode", 0
ThisDrawing.SetVariable "cmdecho", 0
drawout
drawtiles
ThisDrawing.SetVariable "blipmode", sblip
ThisDrawing.SetVariable "cmdecho", scmde
End Sub
La subrutinapath invocagpuser para obtener la entrada de los datos necesarios. El mtodo GetVariable se utiliza entonces para obtener los valores
actuales de las variables de sistema BLIPMODE y CMDECHO y guarda estos valores como sblip y scmde. La subrutina utiliza entonces el mtodo
SetVariable para establecer ambas variables de sistema en 0, desactivando marcas auxiliares y eco de comandos. A continuacin, se dibuja el camino
usando las subrutinas drawout y drawtiles. Finalmente, se utiliza el mtodo SetVariable para restablecer el valor original de las variables de sistema.
Como puede verse, sta es la nica subrutina, entre las que ha escrito, que no comienza con la palabra clave Private, que garantiza que la subrutina slo
puede invocarse desde el mdulo actual. Puesto que la subrutina gardenpath debe estar disponible para el usuario, debe omitirse la palabra clave Private.
Guarde su trabajo.
Ahora ejecute la macro, recorriendo el cdigo paso a paso a medida que se ejecuta.
En el men Herr. de AutoCAD, pulse Macro Macros. En el cuadro de dilogo Macros, seleccione ThisDrawing.gardenpath y pulse Entrar.
VBA IDE aparecer en primer plano en la pantalla, y la primera lnea de la macro gardenpath aparecer resaltada. La lnea resaltada es la lnea de cdigo
que est apunto de ejecutarse. Para ejecutar la lnea, pulse F8. La siguiente lnea de cdigo que debe ejecutarse es la subrutina gpuser. Para ejecutar paso
a paso la subrutina gpuser vuelva a pulsar F8.
Ahora est al principio de la rutina gpuser. Pulse F8 una vez ms para resaltar el primer mtodo GetPoint. Antes de ejecutar esta lnea abra la ventana
Locales pulsando Ver Ventana Locales. Esta ventana se muestra en la parte inferior de VBA IDE. Todas las variables locales y sus valores se muestran
en la ventana Locales mientras se ejecuta la macro.
Ahora pulse F8 para ejecutar el mtodo GetPoint. Observe que el resaltado desaparece y no se presenta nuevo cdigo. Esto es porque el mtodo
GetPoint est esperando a que el usuario especifique un punto en AutoCAD. Vuelva a la ventana de AutoCAD. Ver la solicitud que ha especificado en
la llamada GetPoint de la lnea de comandos. Especifique un punto.
El control vuelve ahora a la macro. La lnea que sigue a la llamada al mtodo GetPoint queda resaltada. Contine la ejecucin paso a paso del cdigo
pulsando F8. Recuerde volver a la ventana de AutoCAD cuando tenga que introducir datos.
Ejecucin de la macro
No es necesario recorrer paso a paso el cdigo cada vez que se ejecuta la macro. Se puede ejecutar la macro desde el men Herr. pulsando Macro
Macros, seleccionando una macro y pulsando Ejecutar. Esto le permite ver el flujo de ejecucin de la misma forma en que lo hara el usuario. Ejecute la
macro desde AutoCAD, especificando los siguientes valores:
Punto inicial del camino: 2, 2
La macro Gardenpath se ha escrito para aceptar la introduccin de datos en la lnea de comando. Para aadir cuadros de dilogo, utilice los formularios
de VBA IDE.
Primero, copie la versin terminada de gardenpath.dvb en otro archivo, gpdialog.dvb. Luego arrastre gpdialog.dvb a AutoCAD.
El cuadro de dilogo que va a crear contiene dos botones de opcin (si se selecciona uno, el otro se deselecciona) para escoger la forma de la loseta:
circular o poligonal. El cuadro de dilogo incluye tambin tres cajas de texto para introducir los siguientes valores numricos: el radio de las losetas, el
espaciado entre las mismas y el nmero de lados de la loseta (que est slo disponible si se ha seleccionado la opcin Polgono).
Para crear un cuadro de dilogo en VBA IDE
1. En el men Insertar, pulse UserForm para abrir un nuevo formulario. Se muestran dos ventanas, un cuadro de herramientas y
un formulario en blanco de usuario.
2. Seleccione y arrastre uno por uno los siguientes controles desde el cuadro de herramientas y sitelos en el formulario de
usuario. Tendr que colocar dos botones de opcin (
), tres etiquetas (
), tres cuadros de texto (
) y dos
botones de comando (
(Name) = gp_poly
Caption = Polgono
ControlTipText = Loseta en forma de polgono
Accelerator = P
2. En el formulario de usuario, seleccione el control OptionButton2. En la ventana Propiedades, cambie las siguientes
propiedades para OptionButton2:
(Name) = gp_circ
Caption = Crculo
ControlTipText = Loseta en forma de crculo
Accelerator = I
Para definir las propiedades de los controles de etiqueta
1. En el formulario de usuario, seleccione el control Label1. En la ventana Propiedades, cambie las siguientes propiedades para
Label1:
(Name) = label_trad
Caption = Radio de las losetas
TabStop = True
2. En el formulario de usuario, seleccione el control Label2. En la ventana Propiedades, cambie las siguientes propiedades para
Label2:
(Name) = label_tspac
Caption = Espacio entre losetas
TabStop = True
3. En el formulario de usuario, seleccione el control Label3. En la ventana Propiedades, cambie las siguientes propiedades para
Label3:
(Name) = label_tsides
Caption = Nmero de caras
TabStop = True
Para definir las propiedades de los controles del cuadro de texto
1. En el formulario de usuario, seleccione el control TextBox1. En la ventana Propiedades, cambie las siguientes propiedades
para TextBox1:
(Name) = gp_trad
2. En el formulario de usuario, seleccione el control TextBox2. En la ventana Propiedades, cambie las siguientes propiedades
para TextBox2:
(Name) = gp_tspac
3. En el formulario de usuario, seleccione el control TextBox3. En la ventana Propiedades, cambie las siguientes propiedades
para TextBox3:
(Name) = gp_tsides
Para establecer las propiedades de los controles de botn de comando y la ventana de formulario
1. En el formulario de usuario, seleccione el control CommandButton1. En la ventana Propiedades, cambie las siguientes
propiedades para CommandButton1:
(Name) = accept
Caption = Aceptar
ControlTipText = Acepta las opciones
Accelerator = O
Default = True
2. En el formulario de usuario, seleccione el control CommandButton2. En la ventana Propiedades, cambie las siguientes
propiedades para CommandButton2:
(Name) = cancel
Caption = Cancelar
ControlTipText = Cancela la operacin
Accelerator = C
3. Seleccione todo el formulario haciendo clic en el fondo del formulario, lejos de cualquier control. En la ventana Propiedades,
cambie las siguientes propiedades para el formulario:
(Name) = gpDialog
Caption = Camino de jardn
El formulario deber ahora tener este aspecto:
4.
5.
6. Guarde su trabajo.
Puesto que el cdigo del formulario accede a trad y tspac, ha actualizado sus definiciones para hacerlas pblicas. Las variables privadas slo
estn disponibles en el mdulo en el que se han definido, por lo que las variables deben convertirse en pblicas. Adems, ha aadido tsides para
el nmero de lados de las losetas poligonales y tshape para que el usuario seleccione la forma de las losetas, que puede ser un crculo o un
polgono.
3. Vaya a la subrutina gpuser. Elimine las dos lneas que obtienen el radio de las losetas y el espacio entre ellas, puesto que esta
informacin se obtiene ahora a travs del formulario. En concreto, elimine lo siguiente:
trad = ThisDrawing.Utility. _
GetDistance(sp, "Radio de las losetas: ")
tspac = ThisDrawing.Utility. _
GetDistance(sp, "Espacio entre losetas: ")
4. Aada las lneas que cargan y muestran el formulario. Aada las siguientes lneas en el lugar de las lneas eliminadas en el
paso 3:
Load gpDialog
gpDialog.Show
5. Aada una subrutina al final del archivo de cdigo que dibuja tanto las losetas circulares como las losetas poligonales:
'Dibuja la loseta con la forma seleccionada
Sub DrawShape(pltile)
Dim angleSegment As Double
Dim currentAngle As Double
Dim angleInRadians As Double
Dim currentSide As Integer
Dim varRet As Variant
Dim aCircle As AcadCircle
Dim aPolygon As AcadLWPolyline
ReDim points(1 To tsides * 2) As Double
'Rama basada en el tipo de forma a dibujar
Select Case tshape
Case "Crculo"
Set aCircle = ThisDrawing.ModelSpace. _
AddCircle(pltile, trad)
Case "Polgono"
angleSegment = 360 / tsides
currentAngle = 0
For 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 + angleSegment
Next currentSide
Set aPolygon = ThisDrawing.ModelSpace. _
AddLightWeightPolyline(points)
aPolygon.Closed = True
End Select
End Sub
Esta subrutina utiliza la instruccin Select Case para ramificar el control del programa segn el tipo de forma que se deba dibujar. La variable
tshape se utiliza para determinar el tipo de forma.
6. A continuacin, vaya a la subrutina drow. Encuentre los dos casos en los que aparece la siguiente lnea:
Set cir = ThisDrawing.ModelSpace.AddCircle(pltile, trad)
Cambie estas lneas para que dibujen la forma correspondiente de losetas, como se muestra a continuacin:
DrawShape (pltile) ' Actualizado
Ahora puede eliminar el cdigo para la creacin de losetas circulares e invocar la subrutina DrawShape para que dibuje la forma apropiada.
Observe que las subrutinas gp_poly_Click() y gp_circ_Click() tienen el mismo nombre que los dos controles de opcin aadidos anteriormente,
con la adicin de _Click. Estas subrutinas se ejecutan automticamente cuando el usuario pulsa en el control respectivo. Observe tambin que el
cuadro Objeto muestra los controles del formulario, ordenados alfabticamente por la propiedad "Name" (nombre).
1. Site el cursor sobre la lnea Private Sub gp_poly_Click() y abra el cuadro Procedimiento/Evento.
Podr ver una lista de todos los eventos a los que puede responder para el control de opcin gp_poly. Las dos subrutinas que ha escrito gestionan
el evento Click. Tambin puede aadir cdigo para responder al evento DblClick, que se ejecutar automticamente cuando el usuario haga doble
clic en el control. Puede aadir cdigo para cualquiera de los eventos de la lista. Estos tipos de subrutinas se denominan gestores de eventos.
Observe el cdigo que ha escrito para estos dos gestores de eventos. El primer gestor de eventos responde al evento Click que corresponde al
control de opcin gp_poly. La primera lnea de cdigo activa el cuadro de texto para el nmero de lados. Este cuadro de texto slo est
disponible para polgonos, por lo que no est activado a no ser que seleccione el control Polgono. La siguiente lnea de cdigo establece la
variable tshape como Polgono.
El segundo gestor de eventos responde al evento Click para el control de opcin gp_circ . Este gestor desactiva el cuadro de texto para nmero de
lados y establece la variable tshape en Crculo.
2. Aada el siguiente gestor de eventos para el botn Aceptar:
Private Sub accept_Click()
If ThisDrawing.tshape = "Polgono" Then
ThisDrawing.tsides = CInt(gp_tsides.text)
If (ThisDrawing.tsides < 3#) Or _
(ThisDrawing.tsides > 1024#) Then
MsgBox "Escriba un valor entre 3 y " & _
"1024 para el nmero de lados."
Exit Sub
End If
End If
ThisDrawing.trad = CDbl(gp_trad.text)
ThisDrawing.tspac = CDbl(gp_tspac.text)
If ThisDrawing.trad < 0# Then
MsgBox "Escriba un valor positivo para el radio."
Exit Sub
End If
If (ThisDrawing.tspac < 0#) Then
MsgBox "Escriba un valor positivo para el espaciado."
Exit Sub
End If
GPDialog.Hide
End Sub
Este cdigo comprueba si la eleccin final de la forma ha sido la de polgono. Si es as, el cdigo obtiene el nmero de lados del control
gp_tsides. El valor que introduce el usuario se almacena en la propiedad Text. Puesto que se almacena como cadena de texto, la cadena debe
convertirse al entero equivalente utilizando la funcin CInt. Una vez obtenido, el gestor de eventos comprueba el rango del valor para asegurar
que se encuentra entre 3 y 1024. Si no es as, se muestra un mensaje y se sale del gestor de eventos sin que tenga lugar ningn otro proceso. El
resultado es que aparece un mensaje y que el usuario tiene otra oportunidad para cambiar el valor. Despus de pulsar de nuevo el botn Aceptar,
este gestor de eventos se ejecuta y vuelve a comprobar el valor.
La macro obtiene valores de radio y de espacio, pero estos valores son dobles, no enteros, y se obtienen utilizando la funcin CDbl. Estos valores
tambin se verifican para comprobar que son positivos.
Una vez obtenidos y verificados los valores, la instruccin gpDialog.Hide oculta el formulario, devolviendo el control a la subrutina que invoc
el formulario por primera vez.
Este cdigo establece los valores iniciales del formulario y para la variable tsides. La tsides debe establecerse en un nmero positivo mayor que 3,
aunque el usuario seleccione un crculo. Para comprender esto, fjese en la subrutina DrawShape que ha escrito anteriormente. Hay una variable llamada
points que se define utilizando el nmero de lados del polgono. Tanto si se solicita una forma de polgono como si no, se asigna memoria a la variable.
Por este motivo, tsides debe estar dentro de un rango vlido. El usuario puede cambiar este valor durante la ejecucin de la macro.
Ahora puede guardar la macro y ejecutarla desde AutoCAD.
Action Example
Sub Example_Action()
' This example encrypts and saves a file.
Dim acad As New AcadApplication
Activate Example
Sub Example_ActivateMethod()
' This example creates two new drawings and activates each drawing in turn.
Dim
Dim
Set
Set
NewDrawing1
Newdrawing2
NewDrawing1
Newdrawing2
As AcadDocument
As AcadDocument
= ThisDrawing.Application.Documents.Add("")
= ThisDrawing.Application.Documents.Add("")
Next drawing
End Sub
Active Example
Sub Example_Active()
' This example creates two new drawings and determines
' which of the drawings is the active drawing.
Dim
Dim
Set
Set
NewDrawing1
Newdrawing2
NewDrawing1
Newdrawing2
As AcadDocument
As AcadDocument
= ThisDrawing.Application.Documents.Add("")
= ThisDrawing.Application.Documents.Add("")
ActiveDimStyle Example
Sub Example_ActiveDimStyle()
' This example returns the current dimension style
' and then sets a new style.
' Finally, it returns the style to the previous setting.
Dim newDimStyle As AcadDimStyle
Dim currDimStyle As AcadDimStyle
' Return current dimension style of active document
Set currDimStyle = ThisDrawing.ActiveDimStyle
MsgBox "The current dimension style is " & currDimStyle.name, vbInformation, "ActiveDimStyle Example"
' Create a dimension style and makes it current
Set newDimStyle = ThisDrawing.DimStyles.Add("TestDimStyle")
ThisDrawing.ActiveDimStyle = newDimStyle
' set current dimension style to newDimStyle
MsgBox "The new dimension style is " & newDimStyle.name, vbInformation, "ActiveDimStyle Example"
ActiveDocument Example
Sub Example_ActiveDocument()
Dim activeDoc As AcadDocument
' Returns current document in AutoCAD
Set activeDoc = ThisDrawing.Application.ActiveDocument
MsgBox "The active document is: " & activeDoc.name, vbInformation, "ActiveDocument Example"
End Sub
ActiveLayer Example
Sub Example_ActiveLayer()
' This example returns the current layer
' and then adds a new layer.
' Finally, it returns the layer to the previous setting.
Dim currLayer As AcadLayer
Dim newLayer As AcadLayer
' Return the current layer of the active document
Set currLayer = ThisDrawing.ActiveLayer
MsgBox "The current layer is " & currLayer.name, vbInformation, "ActiveLayer Example"
' Create a Layer and make it the active layer
Set newLayer = ThisDrawing.Layers.Add("TestLayer")
ThisDrawing.ActiveLayer = newLayer
MsgBox "The new layer is " & newLayer.name, vbInformation, "ActiveLayer Example"
' Reset the layer to its previous setting
ThisDrawing.ActiveLayer = currLayer
MsgBox "The active layer is reset to " & currLayer.name, vbInformation, "ActiveLayer Example"
End Sub
ActiveLayout Example
Sub Example_ActiveLayout()
' This example cycles through the documents collection
' and uses the ActiveLayout object to list the active layout
' for all open documents.
Dim DOC As AcadDocument
Dim msg As String
' If there are no open documents, then exit
If Documents.count = 0 Then
MsgBox "There are no open documents!"
Exit Sub
End If
msg = vbCrLf & vbCrLf
' Cycle through documents and determine the active layout name using the
' ActiveLayout property of the document object
For Each DOC In Documents
msg = msg & DOC.WindowTitle & ": " & DOC.ActiveLayout.name
Next
' Display results
MsgBox "The active layouts for the open drawings are: " & msg
End Sub
ActiveLinetype Example
Sub Example_ActiveLinetype()
' This example finds the
' the new linetype to be
' collection that is not
' Finally, it resets the
' setting.
ActiveProfile Example
Sub Example_ActiveProfile()
' This example returns the current setting of
' ActiveProfile.
Dim preferences As AcadPreferences
Dim currActiveProfile As String
Set preferences = ThisDrawing.Application.preferences
' Retrieve the current ActiveProfile value
currActiveProfile = preferences.Profiles.ActiveProfile
MsgBox "The current value for ActiveProfile is " & currActiveProfile, vbInformation, "ActiveProfile Example"
End Sub
ActivePViewport Example
Sub Example_ActivePViewport()
Dim newPViewport As AcadPViewport
Dim centerPoint(0 To 2) As Double
Dim height As Double
Dim width As Double
height = 5#
width = 5#
centerPoint(0) = 5#: centerPoint(1) = 5#: centerPoint(2) = 0#
' Create a paper space Viewport object
ThisDrawing.ActiveSpace = acPaperSpace
Set newPViewport = ThisDrawing.PaperSpace.AddPViewport(centerPoint, width, height)
ZoomAll
newPViewport.DISPLAY (True)
' Before making a paper space Viewport active,
' the mspace property needs to be True
ThisDrawing.mspace = True
ThisDrawing.ActivePViewport = newPViewport
End Sub
ActiveSelectionSet Example
Sub Example_ActiveSelectionSet()
Dim sset As AcadSelectionSet
' The following example returns current selection set from current drawing
Set sset = ThisDrawing.ActiveSelectionSet
End Sub
ActiveSpace Example
Sub Example_ActiveSpace()
' This example toggles the ActiveSpace property from
' paper space to model space.
' Display the current setting for TILEMODE
MsgBox "TILEMODE = " & ThisDrawing.ActiveSpace, vbInformation, "ActiveSpace Example"
' Changes active document to paper space
ThisDrawing.ActiveSpace = acPaperSpace
MsgBox "TILEMODE = " & ThisDrawing.ActiveSpace, vbInformation, "ActiveSpace Example"
' Changes active document to model space
ThisDrawing.ActiveSpace = acModelSpace
MsgBox "TILEMODE = " & ThisDrawing.ActiveSpace, vbInformation, "ActiveSpace Example"
End Sub
ActiveTextStyle Example
Sub Example_ActiveTextStyle()
' This example returns the current text style
' and then sets a new style.
' Finally, it returns the style to the previous setting.
Dim newTextStyle As AcadTextStyle
Dim currTextStyle As AcadTextStyle
' Return current text style of active document
Set currTextStyle = ThisDrawing.ActiveTextStyle
MsgBox "The current text style is " & currTextStyle.name, vbInformation, "ActiveTextStyle Example"
' Create a text style and make it current
Set newTextStyle = ThisDrawing.TextStyles.Add("TestTextStyle")
ThisDrawing.ActiveTextStyle = newTextStyle
MsgBox "The new text style is " & newTextStyle.name, vbInformation, "ActiveTextStyle Example"
' Reset the text style to its previous setting
ThisDrawing.ActiveTextStyle = currTextStyle
MsgBox "The text style is reset to " & currTextStyle.name, vbInformation, "ActiveTextStyle Example"
End Sub
ActiveUCS Example
Sub Example_ActiveUCS()
' This example returns the current saved UCS (or saves a new one dynamically)
' and then sets a new UCS.
' Finally, it returns the UCS to the previous setting.
Dim
Dim
Dim
Dim
Dim
newUCS As AcadUCS
currUCS As AcadUCS
origin(0 To 2) As Double
xAxis(0 To 2) As Double
yAxis(0 To 2) As Double
' Get the current saved UCS of the active document. If the current UCS is
' not saved, then add a new UCS to the UserCoordinateSystems collection
If ThisDrawing.GetVariable("UCSNAME") = "" Then
' Current UCS is not saved so get the data and save it
With ThisDrawing
Set currUCS = .UserCoordinateSystems.Add( _
.GetVariable("UCSORG"), _
.Utility.TranslateCoordinates(.GetVariable("UCSXDIR"), acUCS, acWorld, 0), _
.Utility.TranslateCoordinates(.GetVariable("UCSYDIR"), acUCS, acWorld, 0), _
"OriginalUCS")
End With
Else
MsgBox "The current UCS is " & currUCS.name, vbInformation, "ActiveUCS Example"
' Create a UCS and make it current
origin(0) = 0: origin(1) = 0: origin(2) = 0
xAxis(0) = 1: xAxis(1) = 1: xAxis(2) = 0
yAxis(0) = -1: yAxis(1) = 1: yAxis(2) = 0
Set newUCS = ThisDrawing.UserCoordinateSystems.Add(origin, xAxis, yAxis, "TestUCS")
ThisDrawing.ActiveUCS = newUCS
MsgBox "The new UCS is " & newUCS.name, vbInformation, "ActiveUCS Example"
' Reset the UCS to its previous setting
ThisDrawing.ActiveUCS = currUCS
MsgBox "The UCS is reset to " & currUCS.name, vbInformation, "ActiveUCS Example"
End Sub
ActiveViewport Example
Sub Example_ActiveViewport()
' This example returns the current viewport.
' It creates a new viewport and makes it active, and
' Then it splits the viewport into four windows.
' It then takes one of the four windows, and splits that
' window horizontally into half.
Dim currViewport As AcadViewport
Dim newViewport As AcadViewport
' Returns current viewport of active document
Set currViewport = ThisDrawing.ActiveViewport
MsgBox "The current viewport is " & currViewport.name, vbInformation, "ActiveViewport Example"
' Create a new viewport and make it active
Set newViewport = ThisDrawing.Viewports.Add("TESTVIEWPORT")
ThisDrawing.ActiveViewport = newViewport
MsgBox "The new active viewport is " & newViewport.name, vbInformation, "ActiveViewport Example"
' Split the viewport in four windows
newViewport.Split acViewport4
' Make the newly split viewport active
ThisDrawing.ActiveViewport = newViewport
' Note that current drawing layout will show four windows.
' However, only one of the windows will be active.
' The following code sets the lower-left corner window
' to be the active window and then splits that
' window into two horizontal windows.
Dim entry
For Each entry In ThisDrawing.Viewports
If entry.name = "TESTVIEWPORT" Then
Dim lowerLeft
lowerLeft = entry.LowerLeftCorner
If lowerLeft(0) = 0 And lowerLeft(1) = 0 Then
Set newViewport = entry
Exit For
End If
End If
Next
newViewport.Split acViewport2Horizontal
ThisDrawing.ActiveViewport = newViewport
End Sub
Add Example
Sub Example_Add()
' This example adds a block, dictionary, dimension style,
' group, layer, registered application, selection set,
' textstyle, view, viewport and UCS using the Add method.
GoSub ADDBLOCK
GoSub ADDDICTIONARY
GoSub ADDDIMSTYLE
GoSub ADDGROUP
GoSub ADDLAYER
GoSub ADDREGISTEREDAPP
GoSub ADDSELECTIONSET
GoSub ADDTEXTSTYLE
GoSub ADDVIEW
GoSub ADDVIEWPORT
GoSub ADDUCS
GoSub ADDMATERIAL
Exit Sub
ADDBLOCK:
' Create a new block called "New_Block"
Dim blockObj As AcadBlock
' Define the block
Dim insertionPnt(0 To 2) As Double
insertionPnt(0) = 0#: insertionPnt(1) = 0#: insertionPnt(2) = 0#
' Add the block to the blocks collection
Set blockObj = ThisDrawing.Blocks.Add(insertionPnt, "New_Block")
MsgBox blockObj.name & " has been added." & vbCrLf & _
"Origin: " & blockObj.origin(0) & ", " & blockObj.origin(1) _
& ", " & blockObj.origin(2), , "Add Example"
Return
ADDDICTIONARY:
' Create a new dictionary called "New_Dictionary"
Dim dictObj As AcadDictionary
' Add the dictionary to the dictionaries collection
Set dictObj = ThisDrawing.Dictionaries.Add("New_Dictionary")
MsgBox dictObj.name & " has been added.", , "Add Example"
Return
ADDDIMSTYLE:
' Create a new dimension style called "New_Dimstyle" in current drawing
Dim DimStyleObj As AcadDimStyle
' Add the dimstyle to the dimstyles collection
Set DimStyleObj = ThisDrawing.DimStyles.Add("New_Dimstyle")
MsgBox DimStyleObj.name & " has been added.", , "Add Example"
Return
ADDGROUP:
' Create a new group called "New_Group" in current drawing
Dim groupObj As AcadGroup
' Add the group to the groups collection
Set groupObj = ThisDrawing.Groups.Add("New_Group")
MsgBox groupObj.name & " has been added.", , "Add Example"
Return
ADDLAYER:
' This example creates a new layer called "New_Layer"
Dim layerObj As AcadLayer
' Add the layer to the layers collection
Return
End Sub
Add3DFace Example
Sub Example_Add3DFace()
' This example creates a 3D face in model space.
Dim
Dim
Dim
Dim
Dim
faceObj As Acad3DFace
point1(0 To 2) As Double
point2(0 To 2) As Double
point3(0 To 2) As Double
point4(0 To 2) As Double
Add3DMesh Example
Sub Example_Add3DMesh()
' This example creates a 4 X 4 polygonmesh in model space.
Dim meshObj As AcadPolygonMesh
Dim mSize, nSize, count As Integer
Dim points(0 To 47) As Double
' Create the matrix of points
points(0) = 0: points(1) = 0: points(2) = 0
points(3) = 2: points(4) = 0: points(5) = 1
points(6) = 4: points(7) = 0: points(8) = 0
points(9) = 6: points(10) = 0: points(11) = 1
points(12) = 0: points(13) = 2: points(14) = 0
points(15) = 2: points(16) = 2: points(17) = 1
points(18)
points(21)
points(24)
points(27)
points(30)
points(33)
points(36)
points(39)
points(42)
points(45)
=
=
=
=
=
=
=
=
=
=
4:
6:
0:
2:
4:
6:
0:
2:
4:
6:
points(19)
points(22)
points(25)
points(28)
points(31)
points(34)
points(37)
points(40)
points(43)
points(46)
=
=
=
=
=
=
=
=
=
=
2:
2:
4:
4:
4:
4:
6:
6:
6:
6:
points(20)
points(23)
points(26)
points(29)
points(32)
points(35)
points(38)
points(41)
points(44)
points(47)
=
=
=
=
=
=
=
=
=
=
0
1
0
1
0
0
0
1
0
0
mSize = 4: nSize = 4
' creates a 3Dmesh in model space
Set meshObj = ThisDrawing.ModelSpace.Add3DMesh(mSize, nSize, points)
' Change the viewing direction of the viewport to better see the polygonmesh
Dim NewDirection(0 To 2) As Double
NewDirection(0) = -1: NewDirection(1) = -1: NewDirection(2) = 1
ThisDrawing.ActiveViewport.direction = NewDirection
ThisDrawing.ActiveViewport = ThisDrawing.ActiveViewport
ZoomAll
End Sub
Add3DPoly Example
Sub Example_Add3DPoly()
Dim polyObj As Acad3DPolyline
Dim points(0 To 8) As Double
' Create the array of points
points(0) = 0: points(1) = 0: points(2) = 0
points(3) = 10: points(4) = 10: points(5) = 10
points(6) = 30: points(7) = 20: points(8) = 30
' Create a 3DPolyline in model space
Set polyObj = ThisDrawing.ModelSpace.Add3DPoly(points)
ZoomAll
End Sub
AddArc Example
Sub Example_AddArc()
' This example creates an arc in model space.
Dim
Dim
Dim
Dim
Dim
arcObj As AcadArc
centerPoint(0 To 2) As Double
radius As Double
startAngleInDegree As Double
endAngleInDegree As Double
AddAttribute Example
Sub Example_AddAttribute()
' This example creates an attribute definition in model space.
Dim
Dim
Dim
Dim
Dim
Dim
Dim
attributeObj As AcadAttribute
height As Double
mode As Long
prompt As String
insertionPoint(0 To 2) As Double
tag As String
value As String
mode = acAttributeModeVerify
prompt = "New Prompt"
insertionPoint(0) = 5#: insertionPoint(1) = 5#: insertionPoint(2) = 0
tag = "NEW_TAG"
value = "New Value"
' Create the attribute definition object in model space
Set attributeObj = ThisDrawing.ModelSpace.AddAttribute(height, mode, prompt, insertionPoint, tag, value)
ZoomAll
End Sub
AddBox Example
Sub Example_AddBox()
' This example creates a box in model space.
Dim boxObj As Acad3DSolid
Dim length As Double, width As Double, height As Double
Dim center(0 To 2) As Double
' Define the box
center(0) = 5#: center(1) = 5#: center(2) = 0
length = 5#: width = 7: height = 10#
' Create the box (3DSolid) object in model space
Set boxObj = ThisDrawing.ModelSpace.AddBox(center, length, width, height)
' Change the viewing direction of the viewport to better see the box
Dim NewDirection(0 To 2) As Double
NewDirection(0) = -1: NewDirection(1) = -1: NewDirection(2) = 1
ThisDrawing.ActiveViewport.direction = NewDirection
ThisDrawing.ActiveViewport = ThisDrawing.ActiveViewport
ZoomAll
End Sub
AddCircle Example
Sub Example_AddCircle()
' This example creates a circle in model space.
Dim circleObj As AcadCircle
Dim centerPoint(0 To 2) As Double
AddCone Example
Sub Example_AddCone()
' This example creates a cone in model space.
Dim
Dim
Dim
Dim
coneObj As Acad3DSolid
radius As Double
center(0 To 2) As Double
height As Double
AddCylinder Example
Sub AddCylinder()
' This example creates a cylinder in model space.
Dim cylinderObj As Acad3DSolid
AddDim3PointAngular Example
Sub Example_AddDim3PointAngular()
' This example creates a Dim3PointAngular object in model space
Dim
Dim
Dim
Dim
DimPointAngularObj As AcadDim3PointAngular
AngleVertex(0 To 2) As Double
FirstPoint(0 To 2) As Double, SecondPoint(0 To 2) As Double
TextPoint(0 To 2) As Double
AddDimAligned Example
Sub Example_AddDimAligned()
' This example creates an aligned dimension in model space.
Dim
Dim
Dim
Dim
dimObj As AcadDimAligned
point1(0 To 2) As Double
point2(0 To 2) As Double
location(0 To 2) As Double
AddDimAngular Example
Sub Example_AddDimAngular()
' This example creates an angular dimension in model space.
Dim
Dim
Dim
Dim
Dim
dimObj As AcadDimAngular
angVert(0 To 2) As Double
FirstPoint(0 To 2) As Double
SecondPoint(0 To 2) As Double
TextPoint(0 To 2) As Double
AddDimArc Example
Sub Example_AddDimArc()
Dim PI As Double: PI = 3.141592
Dim oMS As IAcadModelSpace3
Set oMS = ThisDrawing.ModelSpace
Dim ptCenter(2) As Double
Dim oA As AcadArc
Set oA = oMS.AddArc(ptCenter, 10, PI / 3, PI * 3 / 4)
Dim ptArcPoint(2) As Double
ptArcPoint(0) = 0: ptArcPoint(1) = 15
Dim oAcadDimArcLength As AcadDimArcLength
Set oAcadDimArcLength = oMS.AddDimArc(oA.Center, oA.startPoint, oA.endPoint, ptArcPoint)
Update
ZoomExtents
End Sub
AddDimDiametric Example
Sub Example_AddDimDiametric()
' This example creates a diametric dimension in model space.
Dim
Dim
Dim
Dim
dimObj As AcadDimDiametric
chordPoint(0 To 2) As Double
farChordPoint(0 To 2) As Double
leaderLength As Double
AddDimOrdinate Example
Sub Example_AddDimOrdinate()
' This example creates an ordinate dimension in model space.
Dim
Dim
Dim
Dim
dimObj As AcadDimOrdinate
definingPoint(0 To 2) As Double
leaderEndPoint(0 To 2) As Double
useXAxis As Long
AddDimRadial Example
Sub Example_AddDimRadial()
' This example creates a radial dimension in model space.
Dim
Dim
Dim
Dim
dimObj As AcadDimRadial
center(0 To 2) As Double
chordPoint(0 To 2) As Double
leaderLen As Integer
AddDimRadialLarge Example
Sub Example_AddDimRadialLarge()
Dim PI As Double: PI = 3.141592
Dim oMS As IAcadModelSpace3
Set oMS = ThisDrawing.ModelSpace
AddDimRotated Example
Sub Example_AddDimRotated()
' This example creates a rotated dimension in model space.
Dim
Dim
Dim
Dim
Dim
dimObj As AcadDimRotated
point1(0 To 2) As Double
point2(0 To 2) As Double
location(0 To 2) As Double
rotAngle As Double
End Sub
AddEllipse Example
Sub Example_AddEllipse()
' This example creates an ellipse in model space.
Dim
Dim
Dim
Dim
ellObj As AcadEllipse
majAxis(0 To 2) As Double
center(0 To 2) As Double
radRatio As Double
AddEllipticalCone Example
Sub Example_AddEllipticalCone()
' This example creates an elliptical cone in model space.
Dim
Dim
Dim
Dim
Dim
coneObj As Acad3DSolid
center(0 To 2) As Double
majorRadius As Double
minorRadius As Double
height As Double
ThisDrawing.ActiveViewport.direction = NewDirection
ThisDrawing.ActiveViewport = ThisDrawing.ActiveViewport
ZoomAll
End Sub
AddEllipticalCylinder Example
Sub Example_AddEllipticalCylinder()
' This example creates an elliptical cylinder in model space.
Dim
Dim
Dim
Dim
Dim
cylinderObj As Acad3DSolid
center(0 To 2) As Double
majorRadius As Double
minorRadius As Double
height As Double
AddExtrudedSolid Example
Sub Example_AddExtrudedSolid()
' This example extrudes a solid from a region.
' The region is created from an arc and a line.
Dim curves(0 To 1) As AcadEntity
' Define the arc
AddExtrudedSolidAlongPath Example
Sub Example_AddExtrudedSolidAlongPath()
' This example extrudes a solid from a region
' along a path defined by a spline.
' The region is created from an arc and a line.
Dim curves(0 To 1) As AcadEntity
' Define the arc
AddHatch Example
Sub Example_AddHatch()
' This example creates an associative gradient hatch in model space.
Dim
Dim
Dim
Dim
hatchObj As AcadHatch
patternName As String
PatternType As Long
bAssociativity As Boolean
AddItems Example
Sub Example_AddItems()
' This example creates a selection set and several objects.
' It then adds the objects to the selection set.
' Create the new selection set
Dim ssetObj As AcadSelectionSet
Set ssetObj = ThisDrawing.SelectionSets.Add("TEST_SELECTIONSET")
' Create a Ray object in model space
Dim rayObj As AcadRay
Dim basePoint(0 To 2) As Double
Dim SecondPoint(0 To 2) As Double
basePoint(0) = 3#: basePoint(1) = 3#: basePoint(2) = 0#
SecondPoint(0) = 1#: SecondPoint(1) = 3#: SecondPoint(2) = 0#
Set rayObj = ThisDrawing.ModelSpace.AddRay(basePoint, SecondPoint)
ssetObj.AddItems ssobjs
ThisDrawing.Regen acActiveViewport
End Sub
AddLeader Example
Sub Example_AddLeader()
' This example creates a leader in model space.
' The leader is not attached to any annotation object
' in this example.
Dim
Dim
Dim
Dim
leaderObj As AcadLeader
points(0 To 8) As Double
leaderType As Integer
annotationObject As AcadObject
AddLightweightPolyline Example
Sub Example_AddLightWeightPolyline()
' This example creates a lightweight polyline in model space.
Dim plineObj As AcadLWPolyline
Dim points(0 To 9) As Double
' Define the 2D polyline
points(0) = 1: points(1)
points(2) = 1: points(3)
points(4) = 2: points(5)
points(6) = 3: points(7)
points
= 1
= 2
= 2
= 2
points(8) = 4: points(9) = 4
' Create a lightweight Polyline object in model space
Set plineObj = ThisDrawing.ModelSpace.AddLightWeightPolyline(points)
ZoomAll
End Sub
AddLine Example
Sub Example_AddLine()
' This example adds a line in model space
Dim lineObj As AcadLine
Dim startPoint(0 To 2) As Double
Dim endPoint(0 To 2) As Double
' Define the start and end points for the line
startPoint(0) = 1#: startPoint(1) = 1#: startPoint(2) = 0#
endPoint(0) = 5#: endPoint(1) = 5#: endPoint(2) = 0#
' Create the line in model space
Set lineObj = ThisDrawing.ModelSpace.AddLine(startPoint, endPoint)
ZoomAll
End Sub
AddMInsertBlock Example
Sub Example_AddMInsertBlock()
' This example creates a new Block in the current drawing, adds a
' Circle object to the new block, and uses the newly created block
' to create a rectangular array of block references using AddMInsertBlock
Dim
Dim
Dim
Dim
Dim
circleObj As AcadCircle
centerPoint(0 To 2) As Double, InsertPoint(0 To 2) As Double
radius As Double
newMBlock As AcadMInsertBlock
newBlock As AcadBlock
' Define the Circle object that will be inserted into the block
centerPoint(0) = 0: centerPoint(1) = 0: centerPoint(2) = 0
InsertPoint(0) = 1: InsertPoint(1) = 1: InsertPoint(2) = 0
radius = 0.5
' Create a new block to hold the Circle object
Set newBlock = ThisDrawing.Blocks.Add(centerPoint, "CBlock")
' Add the Circle object to the new block object
Set circleObj = ThisDrawing.Blocks("CBlock").AddCircle(centerPoint, radius)
' Create a rectangular array of Circles using the new block containing the Circle
' and the AddMInsertBlock method
Set newMBlock = ThisDrawing.ModelSpace.AddMInsertBlock(InsertPoint, "CBlock", 1, 1, 1, 1, 2, 2, 1, 1)
ThisDrawing.Application.ZoomAll
MsgBox "A rectangular array has been created from the original block."
End Sub
AddMLine Example
Sub Example_AddMLine()
' This example adds an Mline in model space
Dim mLineObj As AcadMLine
Dim vertexList(0 To 17) As Double
' Define data for new object
vertexList(0) = 4: vertexList(1) = 7: vertexList(2) = 0
vertexList(3) = 5: vertexList(4) = 7: vertexList(5) = 0
vertexList(6) = 6: vertexList(7) = 7: vertexList(8) = 0
vertexList(9) = 4: vertexList(10) = 6: vertexList(11) = 0
vertexList(12) = 5: vertexList(13) = 6: vertexList(14) = 0
vertexList(15) = 6: vertexList(16) = 6: vertexList(17) = 6
' Create the line in model space
Set mLineObj = ThisDrawing.ModelSpace.AddMLine(vertexList)
ThisDrawing.Application.ZoomAll
MsgBox "A new MLine has been added to the drawing."
End Sub
AddMText Example
Sub Example_AddMtext()
' This example creates an MText object in model space.
Dim MTextObj As AcadMText
Dim corner(0 To 2) As Double
Dim width As Double
Dim text As String
corner(0) = 0#: corner(1) = 10#: corner(2) = 0#
width = 10
text = "This is the text String for the mtext Object"
' Creates the mtext Object
Set MTextObj = ThisDrawing.ModelSpace.AddMText(corner, width, text)
ZoomAll
End Sub
AddObject Example
Sub Example_AddObject()
' This example creates a dictionary and adds
' a custom object to that dictionary.
Dim dictObj As AcadDictionary
Set dictObj = ThisDrawing.Dictionaries.Add("TEST_DICTIONARY")
' Load the ObjectARX application that defines the custom object.
' Note: The application listed here does not exist and
' will cause an error when run. Change the application name
' to the path and name of your ObjectARX application.
ThisDrawing.Application.LoadArx ("MyARXApp.dll")
' Create the custom object in the dictionary
Dim keyName As String
Dim className As String
Dim customObj As AcadObject
keyName = "OBJ1"
className = "CAsdkDictObject"
Set customObj = dictObj.AddObject(keyName, className)
End Sub
AddPoint Example
Sub Example_AddPoint()
' This example creates a point in model space.
Dim pointObj As AcadPoint
Dim location(0 To 2) As Double
' Define the location of the point
location(0) = 5#: location(1) = 5#: location(2) = 0#
' Create the point
Set pointObj = ThisDrawing.ModelSpace.AddPoint(location)
ZoomAll
End Sub
AddPolyfaceMesh Example
Sub Example_AddPolyfaceMesh()
Dim vertexList(0 To 17) As Double
'Data
vertexList(0) = 4: vertexList(1) = 7: vertexList(2) = 0
vertexList(3) = 5: vertexList(4) = 7: vertexList(5) = 0
vertexList(6) = 6: vertexList(7) = 7: vertexList(8) = 0
vertexList(9) = 4: vertexList(10) = 6: vertexList(11) = 0
vertexList(12) = 5: vertexList(13) = 6: vertexList(14) = 0
vertexList(15) = 6: vertexList(16) = 6: vertexList(17) = 1
Dim FaceList(0 To 7) As Integer
FaceList(0)
FaceList(1)
FaceList(2)
FaceList(3)
=
=
=
=
1
2
5
4
FaceList(4)
FaceList(5)
FaceList(6)
FaceList(7)
=
=
=
=
2
3
6
5
AddPolyline Example
Sub Example_AddPolyline()
' This example creates a polyline in model space.
Dim plineObj As AcadPolyline
Dim points(0 To 14) As Double
' Define the 2D polyline points
points(0) = 1: points(1) = 1: points(2) = 0
points(3) = 1: points(4) = 2: points(5) = 0
points(6) = 2: points(7) = 2: points(8) = 0
points(9) = 3: points(10) = 2: points(11) = 0
points(12) = 4: points(13) = 4: points(14) = 0
' Create a lightweight Polyline object in model space
Set plineObj = ThisDrawing.ModelSpace.AddPolyline(points)
ZoomAll
End Sub
AddPViewport Example
Sub Example_AddPViewport()
' This example creates a new paper space viewport
Dim
Dim
Dim
Dim
pviewportObj As AcadPViewport
center(0 To 2) As Double
width As Double
height As Double
AddRaster Example
Sub Example_AddRaster()
' This example adds a raster image in model space.
' This example uses a file named "raster.jpg."
' You should change this example to use
' a raster file on your computer.
Dim insertionPoint(0 To 2) As Double
Dim scalefactor As Double
Dim rotationAngle As Double
Dim imageName As String
Dim rasterObj As AcadRasterImage
imageName = "C:\raster.jpg"
insertionPoint(0) = 5#: insertionPoint(1) = 5#: insertionPoint(2) = 0#
scalefactor = 1#
rotationAngle = 0
On Error Resume Next
' Creates a raster image in model space
Set rasterObj = ThisDrawing.ModelSpace.AddRaster(imageName, insertionPoint, scalefactor, rotationAngle)
If Err.Description = "File error" Then
MsgBox imageName & " could not be found."
Exit Sub
End If
ZoomExtents
End Sub
AddRay Example
Sub Example_AddRay()
' This example creates a ray in model space.
Dim rayObj As AcadRay
Dim basePoint(0 To 2) As Double
Dim SecondPoint(0 To 2) As Double
' Define the ray
basePoint(0) = 3#: basePoint(1) = 3#: basePoint(2) = 0#
SecondPoint(0) = 4#: SecondPoint(1) = 4#: SecondPoint(2) = 0#
' Creates a Ray object in model space
Set rayObj = ThisDrawing.ModelSpace.AddRay(basePoint, SecondPoint)
ZoomAll
End Sub
AddRegion Example
Sub Example_AddRegion()
' This example creates a region from an arc and a line.
Dim curves(0 To 1) As AcadEntity
' Define the arc
Dim centerPoint(0 To 2) As Double
Dim radius As Double
Dim startAngle As Double
Dim endAngle As Double
centerPoint(0) = 5#: centerPoint(1) = 3#: centerPoint(2) = 0#
radius = 2#
startAngle = 0
endAngle = 3.141592
Set curves(0) = ThisDrawing.ModelSpace.AddArc(centerPoint, radius, startAngle, endAngle)
' Define the line
Set curves(1) = ThisDrawing.ModelSpace.AddLine(curves(0).startPoint, curves(0).endPoint)
AddRevolvedSolid Example
Sub Example_AddRevolvedSolid()
' This example creates a solid from a region
' rotated around an axis.
' The region is created from an arc and a line.
Dim curves(0 To 1) As AcadEntity
' Define the arc
Dim centerPoint(0 To 2) As Double
Dim radius As Double
Dim startAngle As Double
Dim endAngle As Double
centerPoint(0) = 5#: centerPoint(1) = 3#: centerPoint(2) = 0#
radius = 2#
startAngle = 0
endAngle = 3.141592
Set curves(0) = ThisDrawing.ModelSpace.AddArc(centerPoint, radius, startAngle, endAngle)
' Define the line
Set curves(1) = ThisDrawing.ModelSpace.AddLine(curves(0).startPoint, curves(0).endPoint)
' Create the region
Dim regionObj As Variant
regionObj = ThisDrawing.ModelSpace.AddRegion(curves)
ZoomAll
MsgBox "Revolve the region to create the solid.", , "AddRevolvedSolid Example"
' Define the rotation axis
Dim axisPt(0 To 2) As Double
Dim axisDir(0 To 2) As Double
Dim angle As Double
axisPt(0) = 7: axisPt(1) = 2.5: axisPt(2) = 0
axisDir(0) = 11: axisDir(1) = 1: axisDir(2) = 3
angle = 6.28
' Create the solid
Dim solidObj As Acad3DSolid
AddShape Example
Sub Example_AddShape()
' This example creates a BAT shape from the ltypeshp.shx file.
' Load the shape file containing the shape you wish to create.
' Note: Replace the ltypeshp.shx file name
' with a valid shape file for your system.
On Error GoTo ERRORHANDLER
ThisDrawing.LoadShapeFile ("C:/Program Files/AutoCAD/Support/ltypeshp.shx")
Dim
Dim
Dim
Dim
Dim
shapeObj As AcadShape
shapeName As String
insertionPoint(0 To 2) As Double
scalefactor As Double
rotation As Double
AddSolid Example
Sub Example_AddSolid()
' This example creates a solid in model space.
Dim
Dim
Dim
Dim
Dim
solidObj
point1(0
point2(0
point3(0
point4(0
As
To
To
To
To
AcadSolid
2) As Double
2) As Double
2) As Double
2) As Double
=
=
=
=
1#:
1#:
8#:
6#:
point1(2)
point2(2)
point3(2)
point4(2)
=
=
=
=
0#
0#
0#
0#
AddSphere Example
Sub Example_AddSphere()
' This example creates a sphere in model space.
Dim sphereObj As Acad3DSolid
Dim centerPoint(0 To 2) As Double
Dim radius As Double
centerPoint(0) = 5#: centerPoint(1) = 5#: centerPoint(2) = 0#
radius = 5#
Set sphereObj = ThisDrawing.ModelSpace.AddSphere(centerPoint, radius)
' Change the viewing direction of the viewport
Dim NewDirection(0 To 2) As Double
NewDirection(0) = -1: NewDirection(1) = -1: NewDirection(2) = 1
ThisDrawing.ActiveViewport.direction = NewDirection
ThisDrawing.ActiveViewport = ThisDrawing.ActiveViewport
ZoomAll
End Sub
AddSpline Example
Sub Example_AddSpline()
' This example creates a spline object in model space.
' Create the spline
Dim splineObj As AcadSpline
Dim startTan(0 To 2) As Double
Dim endTan(0 To 2) As Double
Dim fitPoints(0 To 8) As Double
startTan(0) = 0.5: startTan(1) = 0.5: startTan(2) = 0
endTan(0) = 0.5: endTan(1) = 0.5: endTan(2) = 0
fitPoints(0) = 1: fitPoints(1) = 1: fitPoints(2) = 0
fitPoints(3) = 5: fitPoints(4) = 5: fitPoints(5) = 0
fitPoints(6) = 10: fitPoints(7) = 0: fitPoints(8) = 0
Set splineObj = ThisDrawing.ModelSpace.AddSpline(fitPoints, startTan, endTan)
ZoomAll
End Sub
AddText Example
Sub Example_AddText()
' This example creates a text object in model space.
Dim
Dim
Dim
Dim
textObj As AcadText
textString As String
insertionPoint(0 To 2) As Double
height As Double
AddTolerance Example
Sub Example_AddTolerance()
' This example creates a tolerance object in model space.
Dim toleranceObj As AcadTolerance
Dim textString As String
Dim insertionPoint(0 To 2) As Double
Dim direction(0 To 2) As Double
' Define the tolerance object
textString = "{\Fgdt;r}%%vasdf{\Fgdt;l}%%vdf%%vxc%%v12{\Fgdt;m}%%vsd" & vbCrLf & _
"{\Fgdt;t}%%vdfd%%v3dd{\Fgdt;l}%%vv%%v%%vxc{\Fgdt;m}" & vbCrLf & _
"123"
insertionPoint(0) = 5#: insertionPoint(1) = 5#: insertionPoint(2) = 0#
direction(0) = 1#: direction(1) = 1#: direction(2) = 0#
' Create the tolerance object in model space
Set toleranceObj = ThisDrawing.ModelSpace.AddTolerance(textString, insertionPoint, direction)
ZoomAll
End Sub
AddToolbarButton Example
Sub Example_AddToolbarButton()
' This example creates a new toolbar called TestToolbar and inserts a
' toolbar button into it. The toolbar is then displayed.
' To remove the toolbar after execution of this macro, use the Customize Menu
' option from the Tools menu.
Dim currMenuGroup As acadMenuGroup
Set currMenuGroup = ThisDrawing.Application.MenuGroups.Item(0)
' Create the new toolbar
Dim newToolBar As AcadToolbar
Set newToolBar = currMenuGroup.Toolbars.Add("TestToolbar")
' Add a button to the new toolbar
Dim newButton As AcadToolbarItem
Dim openMacro As String
' Assign the macro string the VB equivalent of "ESC ESC _open "
openMacro = Chr(3) & Chr(3) & Chr(95) & "open" & Chr(32)
Set newButton = newToolBar.AddToolbarButton("", "NewButton", "Open a file.", openMacro)
End Sub
AddTorus Example
Sub Example_AddTorus()
' This example creates a torus in model space.
Dim
Dim
Dim
Dim
torusObj As Acad3DSolid
centerPoint(0 To 2) As Double
torusRadius As Double
tubeRadius As Double
AddTrace Example
Sub Example_AddTrace()
' This example creates a trace in model space.
Dim traceObj As AcadTrace
Dim tracePts(0 To 11) As Double
0
0
0
= 0
AddVertex Example
Sub Example_AddVertex()
' This example creates a lightweight polyline in model space.
' It then adds a vertex to the polyline.
Dim plineObj As AcadLWPolyline
Dim points(0 To 9) As Double
points
= 1
= 2
= 2
= 2
= 4
End Sub
AddWedge Example
Sub Example_AddWedge()
' This example creates a wedge in model space.
Dim
Dim
Dim
Dim
Dim
wedgeObj As Acad3DSolid
center(0 To 2) As Double
length As Double
width As Double
height As Double
AddXLine Example
Sub Example_AddXLine()
' This example creates an XLine in model space.
Dim xlineObj As AcadXline
Dim basePoint(0 To 2) As Double
Dim directionVec(0 To 2) As Double
' Define the xline
basePoint(0) = 2#: basePoint(1) = 2#: basePoint(2) = 0#
directionVec(0) = 1#: directionVec(1) = 1#: directionVec(2) = 0#
Algorithm Example
Sub Example_Algorithm()
' This example encrypts and saves a file.
Dim acad As New AcadApplication
Dim sp As New AcadSecurityParams
acad.Visible = True
sp.Action = AcadSecurityParamsType.ACADSECURITYPARAMS_ENCRYPT_DATA
sp.Algorithm = AcadSecurityParamsConstants.ACADSECURITYPARAMS_ALGID_RC4
sp.KeyLength = 40
sp.Password = UCase("mypassword") 'AutoCAD converts all passwords to uppercase before applying them
sp.ProviderName = "Microsoft Base Cryptographic Provider v1.0"
sp.ProviderType = 1
acad.ActiveDocument.SaveAs "C:\MyDrawing.dwg", , sp
End Sub
Alignment Example
Sub Example_Alignment()
' This example creates a text object in model space and
' demonstrates setting the alignment of the new text string
Dim
Dim
Dim
Dim
Dim
Dim
textObj As AcadText
textString As String
insertionPoint(0 To 2) As Double, alignmentPoint(0 To 2) As Double
height As Double
oldPDMODE As Integer
pointObj As AcadPoint
ThisDrawing.Application.ZoomAll
' Set the text alignment to a value other than acAlignmentLeft, which is the default.
' Create a point that will act as an alignment reference point
textObj.Alignment = acAlignmentRight
' Create the text alignment reference point and the text will automatically
' align to the right of this point, because the text
' alignment was set to acAlignmentRight
textObj.TextAlignmentPoint = alignmentPoint
ThisDrawing.Regen acActiveViewport
MsgBox "The Text object is now aligned to the right of the alignment point"
' Center the text to the alignment point
textObj.Alignment = acAlignmentCenter
ThisDrawing.Regen acActiveViewport
MsgBox "The Text object is now centered to the alignment point"
' Reset point style
ThisDrawing.SetVariable "PDMODE", oldPDMODE
End Sub
AltUnitsScale Example
Sub Example_AltUnitsScale()
' This example creates an aligned dimension in model space and
' uses AltUnitsScale to cycle through some common scales
' for the alternate dimension
Dim dimObj As AcadDimAligned
Dim point1(0 To 2) As Double, point2(0 To 2) As Double
Dim location(0 To 2) As Double
Angle Example
Sub Example_Angle()
' This example adds a line in model space and returns the angle of the new line
Dim lineObj As AcadLine
Dim startPoint(0 To 2) As Double, endPoint(0 To 2)
As Double
' Define the start and end points for the line
startPoint(0) = 1: startPoint(1) = 1: startPoint(2) = 0
endPoint(0) = 5: endPoint(1) = 5: endPoint(2) = 0
' Create the line in model space
Set lineObj = ThisDrawing.ModelSpace.AddLine(startPoint, endPoint)
ThisDrawing.Application.ZoomAll
MsgBox "The angle of the new Line is: " & lineObj.angle
End Sub
AngleFormat Example
Sub Example_AngleFormat()
' This example creates a Dim3PointAngular object in model space
' and sets its Angle Format to some common values
Dim
Dim
Dim
Dim
DimPointAngularObj As AcadDim3PointAngular
AngleVertex(0 To 2) As Double
FirstPoint(0 To 2) As Double, SecondPoint(0 To 2) As Double
TextPoint(0 To 2) As Double
AngleFromXAxis Example
Sub Example_AngleFromXAxis()
' This example finds the angle, in radians, between the X axis
' and a line defined by two points.
AngleToReal Example
Sub Example_AngleToReal()
' This example passes several different strings representing
' an angle in different units to be converted to radians.
Dim angAsStr As String
Dim unit As Integer
Dim angAsReal As Double
' Convert the angle given in degrees unit to a real
angAsStr = "45"
unit = acDegrees
angAsReal = ThisDrawing.Utility.AngleToReal(angAsStr, unit)
MsgBox "45 degrees converts to " & angAsReal & " radians.", , "AngleAsReal Example"
' Convert the angle given in degrees/minutes/seconds unit to Radians
angAsStr = "45d0' 0"""
unit = acDegreeMinuteSeconds
angAsReal = ThisDrawing.Utility.AngleToReal(angAsStr, unit)
MsgBox "45 degrees, 0 minutes, 0 seconds converts to " & angAsReal & " radians.", , "AngleAsReal Example"
' Convert the angle given in grads unit to Radians
angAsStr = "50"
unit = acGrads
angAsReal = ThisDrawing.Utility.AngleToReal(angAsStr, unit)
MsgBox "50 grads converts to " & angAsReal & " radians.", , "AngleAsReal Example"
End Sub
AngleToString Example
Sub Example_AngleToString()
' This example converts a radian value to several different
' strings representing the value in different units.
Dim angAsRad As Double
Dim unit As Integer
Dim precision As Long
Dim angAsString As String
angAsRad = 0.785398163397448
unit = acDegrees
precision = 6
' Convert the radian value to degrees with a precision of 6
angAsString = ThisDrawing.Utility.AngleToString(angAsRad, unit, precision)
MsgBox "0.785398163397448 radians = " & angAsString & " degrees", , "AngleAsString Example"
' Convert the radian value to degrees/Minutes/Seconds with a precision of 6
unit = acDegreeMinuteSeconds
angAsString = ThisDrawing.Utility.AngleToString(angAsRad, unit, precision)
MsgBox "0.785398163397448 radians = " & angAsString, , "AngleAsString Example"
' Convert the radian value to grads with a precision of 6
unit = acGrads
angAsString = ThisDrawing.Utility.AngleToString(angAsRad, unit, precision)
MsgBox "0.785398163397448 radians = " & angAsString, , "AngleAsString Example"
End Sub
AngleVertex Example
Sub Example_AngleVertex()
' This example creates a Dim3PointAngular object in model space
' and then alters its angle vertex
Dim DimPointAngularObj As AcadDim3PointAngular
Dim AngleVertex(0 To 2) As Double, NewAngleVertex(0 To 2) As Double
Application Example
Sub Example_Application()
' This example creates a line and then uses the
' Application property of the line to return the
' application name.
Dim lineObj As AcadLine
Dim startPoint(0 To 2) As Double
Dim endPoint(0 To 2) As Double
Dim myApp As AcadApplication
ArcLength Example
Sub Example_ArcLength()
' This example creates an Arc in model space and returns the length of the new Arc
Dim arcObj As AcadArc
Dim centerPoint(0 To 2) As Double
Dim radius As Double
Dim startAngleInDegree As Double, endAngleInDegree As Double
Dim startAngleInRadian As Double, endAngleInRadian As Double
' Define the Arc
centerPoint(0) = 0: centerPoint(1) = 0: centerPoint(2) = 0
radius = 5#
startAngleInDegree = 10#: endAngleInDegree = 230#
' Convert the angles in degrees to angles in radians
startAngleInRadian = startAngleInDegree * 3.141592 / 180#
endAngleInRadian = endAngleInDegree * 3.141592 / 180#
' Create the arc object in model space
Set arcObj = ThisDrawing.ModelSpace.AddArc(centerPoint, radius, startAngleInRadian, endAngleInRadian)
ThisDrawing.Application.ZoomAll
' Return length of new arc
MsgBox "The length of the new Arc is: " & arcObj.ArcLength
End Sub
Area Example
Sub Example_Area()
' This example creates a polyline object and
the Polyline
7
2
5
ArrayPolar Example
Sub Example_ArrayPolar()
' This example creates a circle and then performs a polar array
' on that circle.
' Create the circle
Dim circleObj As AcadCircle
Dim center(0 To 2) As Double
Dim radius As Double
center(0) = 2#: center(1) = 2#: center(2) = 0#
radius = 1
Set circleObj = ThisDrawing.ModelSpace.AddCircle(center, radius)
ZoomAll
MsgBox "Perform the polar array on the circle.", , "ArrayPolar Example"
' Define the polar array
Dim noOfObjects As Integer
Dim angleToFill As Double
Dim basePnt(0 To 2) As Double
noOfObjects = 4
angleToFill = 3.14
' 180 degrees
basePnt(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 Variant
retObj = circleObj.ArrayPolar(noOfObjects, angleToFill, basePnt)
ZoomAll
MsgBox "Polar array completed.", , "ArrayPolar Example"
End Sub
ArrayRectangular Example
Sub Example_ArrayRectangular()
' This example creates a circle and then performs
' a rectangular array on that circle.
' Create the circle
Dim circleObj As AcadCircle
Dim center(0 To 2) As Double
Dim radius As Double
center(0) = 2#: center(1) = 2#: center(2) = 0#
radius = 0.5
Set circleObj = ThisDrawing.ModelSpace.AddCircle(center, radius)
ThisDrawing.Application.ZoomAll
MsgBox "Perform the rectangular array on the circle.", , "ArrayRectangular Example"
' Define the rectangular array
Dim numberOfRows As Long
Dim numberOfColumns As Long
Dim numberOfLevels As Long
Dim distanceBwtnRows As Double
Dim distanceBwtnColumns As Double
Dim distanceBwtnLevels As Double
numberOfRows = 5
numberOfColumns = 5
numberOfLevels = 2
distanceBwtnRows = 1
distanceBwtnColumns = 1
distanceBwtnLevels = 1
' Create the array of objects
Dim retObj As Variant
Arrowhead1Block Example
Sub Example_ArrowHead1Block()
' This example creates an aligned dimension object in model space
' and then alters the visible appearance (shape) of the arrowhead
' using the ArrowHeadBlock property.
' Use the ArrowHeadBlock property to set the arrowhead to an existing
' block object containing a custom Circle object
Dim
Dim
Dim
Dim
Dim
DimPointAngularObj As AcadDim3PointAngular
AngleVertex(0 To 2) As Double
FirstPoint(0 To 2) As Double, SecondPoint(0 To 2) As Double
TextPoint(0 To 2) As Double
BlockName As String
End Sub
AutoSnapAperture Example
Sub Example_AutoSnapAperture()
' This example reads and modifies the preference value that controls
' the display of the AutoSnap aperture.
' When finished, this example resets the preference value back to
' its original value.
Dim ACADPref As AcadPreferencesDrafting
Dim originalValue As Variant, newValue As Variant
' Get the drafting preferences object
Set ACADPref = ThisDrawing.Application.preferences.Drafting
' Read and display the original value
originalValue = ACADPref.AutoSnapAperture
MsgBox "The AutoSnapAperture preference is set to: " & originalValue
' Modify the AutoSnapAperture preference by toggling the value
ACADPref.AutoSnapAperture = Not (originalValue)
newValue = ACADPref.AutoSnapAperture
MsgBox "The AutoSnapAperture preference has been set to: " & newValue
' Reset the preference back to its original value
'
' * Note: Comment out this last section to leave the change to
'
this preference in effect
ACADPref.AutoSnapAperture = originalValue
MsgBox "The AutoSnapAperture preference was reset back to: " & originalValue
End Sub
AutoSnapApertureSize Example
Sub Example_AutoSnapApertureSize()
' This example reads and modifies the preference value that controls
' the size of the AutoSnap aperture. When finished, this example resets
' the preference value back to its original value.
Dim ACADPref As AcadPreferencesDrafting
Dim originalValue As Variant, newValue As Variant
' Get the drafting preferences object
AutoSnapMagnet Example
Sub Example_AutoSnapMagnet()
' This example reads and modifies the preference value that controls
' the AutoSnap magnet. When finished, this example resets the
' preference value back to its original value.
Dim ACADPref As AcadPreferencesDrafting
Dim originalValue As Variant, newValue As Variant
' Get the drafting preferences object
Set ACADPref = ThisDrawing.Application.preferences.Drafting
' Read and display the original value
originalValue = ACADPref.AutoSnapMagnet
MsgBox "The AutoSnapMagnet preference is set to: " & originalValue
' Modify the AutoSnapMagnet preference by toggling the value
ACADPref.AutoSnapMagnet = Not (originalValue)
newValue = ACADPref.AutoSnapMagnet
MsgBox "The AutoSnapMagnet preference has been set to: " & newValue
' Reset the preference back to its original value
'
' * Note: Comment out this last section to leave the change to
'
this preference in effect
ACADPref.AutoSnapMagnet = originalValue
MsgBox "The AutoSnapMagnet preference was reset back to: " & originalValue
End Sub
AutoSnapMarker Example
Sub Example_AutoSnapMarker()
' This example reads and modifies the preference value that controls
' the AutoSnap marker. When finished, this example resets the
' preference value back to its original value.
Dim ACADPref As AcadPreferencesDrafting
Dim originalValue As Variant, newValue As Variant
' Get the drafting preferences object
Set ACADPref = ThisDrawing.Application.preferences.Drafting
' Read and display the original value
originalValue = ACADPref.AutoSnapMarker
MsgBox "The AutoSnapMarker preference is set to: " & originalValue
' Modify the AutoSnapMarker preference by toggling the value
ACADPref.AutoSnapMarker = Not (originalValue)
newValue = ACADPref.AutoSnapMarker
MsgBox "The AutoSnapMarker preference has been set to: " & newValue
' Reset the preference back to its original value
'
' * Note: Comment out this last section to leave the change to
'
this preference in effect
ACADPref.AutoSnapMarker = originalValue
MsgBox "The AutoSnapMarker preference was reset back to: " & originalValue
End Sub
BackgroundFill Example
Sub Example_BackgroundFill()
' This example creates a circle and an MText object, and masks part of the
' circle with the MText object
'Draw a circle
Dim circleObj As AcadCircle
Dim CircleReference(0 To 2) As Double
Dim radius As Double
CircleReference(0) = 0
CircleReference(1) = 0
CircleReference(2) = 0
radius = 5
Set circleObj = ThisDrawing.ModelSpace.AddCircle(CircleReference, radius)
ZoomAll
MsgBox ("A circle has been drawn.")
'Create an MText object with the BackgroundFill property set to True
Dim MTextObj As AcadMText
Dim width As Double
Dim text As String
width = 10
text = "This is the text for the MText object"
Set MTextObj = ThisDrawing.ModelSpace.AddMText(CircleReference, width, text)
MTextObj.BackgroundFill = True
ZoomAll
End Sub
Backward Example
Sub Example_Backward()
' This example creates a text object in model space and
' uses the Backward property to flip the text horizontally
Dim
Dim
Dim
Dim
textObj As AcadText
textString As String
insertionPoint(0 To 2) As Double
height As Double
BasePoint Example
Sub Example_BasePoint()
' This example creates a ray object. It then finds the
' base point of the ray, changes the base point, and
' queries the new base point.
Dim basePoint(0 To 2) As Double
Dim directionVec(0 To 2) As Double
Dim rayObj As AcadRay
' Establish the base point and directional vector for the ray
basePoint(0) = 3#: basePoint(1) = 3#: basePoint(2) = 0#
directionVec(0) = 1#: directionVec(1) = 1#: directionVec(2) = 0#
' Create a Ray object in model space
Set rayObj = ThisDrawing.ModelSpace.AddRay(basePoint, directionVec)
ThisDrawing.Regen True
MsgBox "A new Ray has been added.", vbInformation
' Define a new base point
Dim newBase(0 To 2) As Double
newBase(0) = 4#: newBase(1) = 2#: newBase(2) = 0#
' Update the ray using the new base point
rayObj.basePoint = newBase
' Query the new basepoint for the Ray
Dim currBase As Variant
' Note that return from basepoint property is Variant and not a SafeArray
Dim msg As String
currBase = rayObj.basePoint
msg = currBase(0) & ", " & currBase(1) & ", " & currBase(2)
ThisDrawing.Regen True
MsgBox "We've just changed the basepoint of the new Ray to: " & msg, vbInformation
End Sub
BeginClose Example
Private Sub AcadDocument_BeginClose()
' This example intercepts a drawing BeginClose event.
'
' This event is triggered when a drawing receives a request to close.
'
' To trigger this example event: Close an open drawing
MsgBox "A drawing has just been closed!"
End Sub
BeginCommand Example
Private Sub AcadDocument_BeginCommand(ByVal CommandName As String)
' This example intercepts a drawing BeginCommand event.
'
' This event is triggered when a drawing receives
' any command compatible with this event.
'
' To trigger this example event: Issue any command to an open drawing from
' either the command line, VBA, the AutoCAD menus, the AutoCAD toolbars, or LISP.
' Use the "CommandName" variable to determine which command was started
MsgBox "A drawing has just been issued a " & CommandName & " command."
End Sub
BeginDocClose Example
Private Sub AcadDocument_BeginDocClose(Cancel As Boolean)
' This example prevents a drawing from closing.
Cancel = True
MsgBox "Please do not close this drawing."
End Sub
Circumference Example
Sub Example_Circumference()
' This example creates a Circle object in model space and
Color Example
Sub Example_Color()
' This example creates a polyline and colors it red.
' It then displays the current color setting for the polyline.
Dim plineObj As AcadPolyline
Dim currentcolor As Variant
' Create Polyline
Dim points(8) As Double
points(0) = 3: points(1) = 7: points(2) = 0
points(3) = 9: points(4) = 2: points(5) = 0
points(6) = 3: points(7) = 5: points(8) = 0
Set plineObj = ThisDrawing.ModelSpace.AddPolyline(points)
' First set the color of the object to Red
plineObj.Color = acRed
ThisDrawing.Regen (True)
' Now retrieve and display the Color property
currentcolor = plineObj.Color
' Translate the color from a number into text
If currentcolor = 256 Then
currentcolor = "By Layer"
Else
currentcolor = Choose(currentcolor + 1, "By Block", "Red", "Yellow", "Green", "Cyan", "Blue", "Magenta", "White")
End If
' Display
MsgBox "The Polyline color is: " & currentcolor, vbInformation, "Color Example"
End Sub
ColorIndex Example
Sub Example_ColorIndex()
'This example draws a circle and
'returns the closest color index.
Dim col As New AcadAcCmColor
Call col.SetRGB(125, 175, 235)
Dim cir As AcadCircle
Dim pt(0 To 2) As Double
Set cir = ThisDrawing.ModelSpace.AddCircle(pt, 2)
cir.TrueColor = col
ZoomAll
Dim retCol As AcadAcCmColor
Set retCol = cir.TrueColor
If col.ColorMethod = AutoCAD.acColorMethodByRGB Then
MsgBox "Closest ColorIndex=" & col.ColorIndex
End If
End Sub
ColorMethod Example
Sub Example_ColorMethod()
' This example shows how to change the
' ColorMethod property
Dim col As New AcadAcCmColor
col.ColorMethod = AutoCAD.acColorMethodForeground
'Circle number one
Dim cir1 As AcadCircle
Dim pt(0 To 2) As Double
Set cir1 = ThisDrawing.ModelSpace.AddCircle(pt, 2)
cir1.TrueColor = col
ZoomAll
Dim retCol As AcadAcCmColor
Set retCol = cir1.TrueColor
'Message box with method and index
Dim MethodText As String
MethodText = col.ColorMethod
MsgBox "ColorMethod=" & MethodText & vbCrLf & "Index=" & col.ColorIndex
'Circle number two
Dim cir2 As AcadCircle
Set cir2 = ThisDrawing.ModelSpace.AddCircle(pt, 6)
ZoomAll
col.ColorMethod = AutoCAD.acColorMethodByBlock
'Message box with method and index
MethodText = col.ColorMethod
MsgBox "ColorMethod=" & MethodText & vbCrLf & "Index=" & col.ColorIndex
'Circle number three
Dim cir3 As AcadCircle
Set cir3 = ThisDrawing.ModelSpace.AddCircle(pt, 10)
ZoomAll
Dim layColor As AcadAcCmColor
Set layColor = AcadApplication.GetInterfaceObject("AutoCAD.AcCmColor.16")
Call layColor.SetRGB(122, 199, 25)
ThisDrawing.ActiveLayer.TrueColor = layColor
col.ColorMethod = AutoCAD.acColorMethodByLayer
Set retCol = cir3.TrueColor
'Message box with method and index
MethodText = col.ColorMethod
MsgBox "ColorMethod=" & MethodText & vbCrLf & "Index=" & col.ColorIndex
End Sub
ColorName Example
Sub Example_ColorName()
GetColor Example
Sub Example_GetColor()
' This example creates a TableStyle object and sets values for
' the style name and other attributes.
Dim dictionaries As AcadDictionaries
Set dictionaries = ThisDrawing.Database.dictionaries
Dim dictObj As AcadDictionary
Set dictObj = dictionaries.Item("acad_tablestyle")
' Create the custom TableStyle object in the dictionary
Dim keyName As String
Dim className As String
Dim customObj As AcadTableStyle
keyName = "NewStyle"
className = "AcDbTableStyle"
Set customObj = dictObj.AddObject(keyName, className)
customObj.Name = "NewStyle"
customObj.Description = "New Style for My Tables"
customObj.FlowDirection = acTableBottomToTop
customObj.HorzCellMargin = 0.22
customObj.BitFlags = 1
customObj.SetTextHeight AcRowType.acDataRow+AcRowType.acTitleRow, 1.3
LinetypeScale Example
Sub Example_LinetypeScale()
' This example creates a line and finds the linetype scale
' for the line. It then changes the linetype scale, and finally
' resets the linetype scale back to the original value.
Dim startPoint(0 To 2) As Double
Dim endPoint(0 To 2) As Double
Dim lineObj As AcadLine
Dim currLTScale As Double
' Create a Line object in model space
startPoint(0) = 2#: startPoint(1) = 2#: startPoint(2) = 0#
endPoint(0) = 4#: endPoint(1) = 4#: endPoint(2) = 0#
Set lineObj = ThisDrawing.ModelSpace.AddLine(startPoint, endPoint)
lineObj.Update
currLTScale = lineObj.LinetypeScale
MsgBox "The linetype scale for the line is:" & lineObj.LinetypeScale, vbInformation, "Linetypes Example"
' Set the linetype scale of a Line to .5
lineObj.LinetypeScale = 0.5
lineObj.Update
MsgBox "The new linetype scale for the line is:" & lineObj.LinetypeScale, vbInformation, "Linetypes Example"
' Reset the linetype scale of a Line to what is was before
lineObj.LinetypeScale = currLTScale
lineObj.Update
MsgBox "The linetype scale for the line is reset to:" & lineObj.LinetypeScale, vbInformation, "Linetypes Example"
End Sub
Mirror Example
Sub Example_Mirror()
' This example creates a lightweight polyline
' and then mirrors that polyline.
' Create the polyline
Dim plineObj As AcadLWPolyline
Dim points(0 To 11) As Double
points(0) = 1: points(1) = 1
points(2) = 1: points(3) = 2
points(4) = 2: points(5) = 2
points(6) = 3: points(7) = 2
points(8) = 4: points(9) = 4
points(10) = 4: points(11) = 1
Set plineObj = ThisDrawing.ModelSpace.AddLightWeightPolyline(points)
plineObj.Closed = True
ZoomAll
' Define the mirror axis
Dim point1(0 To 2) As Double
Dim point2(0 To 2) As Double
point1(0) = 0: point1(1) = 4.25: point1(2) = 0
point2(0) = 4: point2(1) = 4.25: point2(2) = 0
MsgBox "Mirror the polyline.", , "Mirror Example"
' Mirror the polyline
Dim mirrorObj As AcadLWPolyline
Set mirrorObj = plineObj.Mirror(point1, point2)
ZoomAll
MsgBox "Mirror completed.", , "Mirror Example"
End Sub
Mirror3D Example
Sub Example_Mirror3D()
' This example creates a box in model space, and mirrors the box about a plane.
Dim boxObj As Acad3DSolid
Dim length As Double, width As Double, height As Double
Dim center(0 To 2) As Double
' Define the box
center(0) = 5#: center(1) = 5#: center(2) = 0
length = 5#: width = 7: height = 10#
' Create the box (3DSolid) object in model space
Set boxObj = ThisDrawing.ModelSpace.AddBox(center, length, width, height)
' Define the mirroring plane with three points
Dim mirrorPt1(0 To 2) As Double
Dim mirrorPt2(0 To 2) As Double
Dim mirrorPt3(0 To 2) As Double
mirrorPt1(0) = 1.25: mirrorPt1(1) = 0: mirrorPt1(2) = 0
mirrorPt2(0) = 1.25: mirrorPt2(1) = 2: mirrorPt2(2) = 0
mirrorPt3(0) = 1.25: mirrorPt3(1) = 2: mirrorPt3(2) = 2
' Mirror the box
Dim mirrorBoxObj As Acad3DSolid
Set mirrorBoxObj = boxObj.Mirror3D(mirrorPt1, mirrorPt2, mirrorPt3)
' Change the viewing direction of the viewport
Dim NewDirection(0 To 2) As Double
NewDirection(0) = -1: NewDirection(1) = -1: NewDirection(2) = 1
ThisDrawing.ActiveViewport.direction = NewDirection
ThisDrawing.ActiveViewport = ThisDrawing.ActiveViewport
ZoomAll
End Sub
Rotate Example
Sub Example_Rotate()
' This example creates a lightweight polyline
' and then rotates that polyline.
Rotate3D Example
Sub Example_Rotate3D()
' This example creates a box in model space.
' It then rotates the box about an axis.
Dim boxObj As Acad3DSolid
Dim length As Double, width As Double, height As Double
Dim center(0 To 2) As Double
' Define the box
center(0) = 5#: center(1) = 5#: center(2) = 0
Rotation Example
Sub Example_Rotation()
' This example creates a text object in model space.
' It then changes the Rotation of the text object.
Dim
Dim
Dim
Dim
textObj As AcadText
textString As String
insertionPoint(0 To 2) As Double
height As Double
ScaleFactor Example
Sub Example_ScaleFactor()
' This example creates a text object in model space.
' It then finds the current scale factor and changes it.
Dim textObj As AcadText
Dim textString As String
Dim insertionPoint(0 To 2) As Double
Dim height As Double
' Define the text object
textString = "Hello, World."
insertionPoint(0) = 2: insertionPoint(1) = 2: insertionPoint(2) = 0
height = 0.5
' Create the text object in model space
Set textObj = ThisDrawing.ModelSpace.AddText(textString, insertionPoint, height)
ZoomAll
' Find the current scale factor for the text object
Dim currScaleFactor As Double
currScaleFactor = textObj.scalefactor
MsgBox "The scale factor of the text is " & textObj.scalefactor, , "ScaleFactor Example"
' Change the scale factor for the text object
textObj.scalefactor = currScaleFactor + 1
ThisDrawing.Regen True
MsgBox "The scale factor of the text is now " & textObj.scalefactor, , "ScaleFactor Example"
End Sub
SliceSolid Example
Sub Example_SliceSolid()
' This example creates a box in model space.
' It then slices the box based on a plane
' defined by three points. The slice is returned
' as a 3Dsolid.
Dim boxObj As Acad3DSolid
Dim length As Double, width As Double, height As Double
Dim center(0 To 2) As Double
' Define the box
center(0) = 5#: center(1) = 5#: center(2) = 0
length = 5#: width = 7: height = 10#
' Create the box (3DSolid) object in model space
Set boxObj = ThisDrawing.ModelSpace.AddBox(center, length, width, height)
' Define the section
Dim slicePt1(0 To 2)
Dim slicePt2(0 To 2)
Dim slicePt3(0 To 2)
SolidFill Example
Sub Example_SolidFill()
' This example reads and modifies the preference value that controls
' whether multilines, traces, solids, all hatches (including solid-fill)
' and wide polylines are filled in.
'
' When finished, this example resets the preference value back to
' its original value.
Dim ACADPref As AcadDatabasePreferences
Dim originalValue As Variant, newValue As Variant
' Get the user preferences object
Set ACADPref = ThisDrawing.preferences
' Read and display the original value
originalValue = ACADPref.SolidFill
MsgBox "The SolidFill preference is set to: " & originalValue
' Modify the SolidFill preference by toggling the value
ACADPref.SolidFill = Not (ACADPref.SolidFill)
newValue = ACADPref.SolidFill
MsgBox "The SolidFill preference has been set to: " & newValue
' Reset the preference back to its original value
'
' * Note: Comment out this last section to leave the change to
'
this preference in effect
ACADPref.SolidFill = originalValue
MsgBox "The SolidFill preference was reset back to: " & originalValue
End Sub
ZoomAll Example
Sub Example_ZoomAll()
' This example creates several objects in model space and
' then performs a variety of zooms on the drawing.
' Create a Ray object in model space
Dim rayObj As AcadRay
Dim basePoint(0 To 2) As Double
Dim SecondPoint(0 To 2) As Double
basePoint(0) = 3#: basePoint(1) = 3#: basePoint(2) = 0#
SecondPoint(0) = 1#: SecondPoint(1) = 3#: SecondPoint(2) = 0#
Set rayObj = ThisDrawing.ModelSpace.AddRay(basePoint, SecondPoint)
ZoomCenter Example
Sub Example_ZoomCenter()
' This example creates several objects in model space and
' then performs a variety of zooms on the drawing.
' Create a Ray object in model space
Dim rayObj As AcadRay
Dim basePoint(0 To 2) As Double
Dim SecondPoint(0 To 2) As Double
basePoint(0) = 3#: basePoint(1) = 3#: basePoint(2) = 0#
SecondPoint(0) = 1#: SecondPoint(1) = 3#: SecondPoint(2) = 0#
ZoomExtents Example
Sub Example_ZoomExtents()
' This example creates several objects in model space and
' then performs a variety of zooms on the drawing.
' Create a Ray object in model space
Dim rayObj As AcadRay
Dim basePoint(0 To 2) As Double
Dim SecondPoint(0 To 2) As Double
basePoint(0) = 3#: basePoint(1) = 3#: basePoint(2) = 0#
ZoomScaled Example
Sub Example_ZoomScaled()
' This example creates several objects in model space and
' then performs a variety of zooms on the drawing.
' Create a Ray object in model space
Dim rayObj As AcadRay
Dim basePoint(0 To 2) As Double
Dim SecondPoint(0 To 2) As Double