首页 SolidWorks.2007_vba

SolidWorks.2007_vba

举报
开通vip

SolidWorks.2007_vba Macros can be an important source of productivity enhancementsthat are not offered directly by SolidWorks software. Being able tocreate your own macros can make you more valuable at your place of work. Macros can do anything from centering a rectangle on the ...

SolidWorks.2007_vba
Macros can be an important source of productivity enhancementsthat are not offered directly by SolidWorks software. Being able tocreate your own macros can make you more valuable at your place of work. Macros can do anything from centering a rectangle on the Origin, to setting all face colors back to the part color, to changing the decimal places of a selected dimension, to creating a spline from an equation. You do not have to be a programmer to follow the information in this chapter. However, you should have a general understanding of Visual Basic. Visual Basic is a common programming language. Visual Basic for Applications, or VBA, is included in SolidWorks in the same way that it is included in Word and Excel. If you have programming skills with these other common applications, then those skills are largely transferable to working with SolidWorks macros. Application Programming Interface, or API, refers to the available SolidWorks functions that can be called programmatically (numbered in the hundreds) from VB, VBA, VB.NET, C++, C# (c sharp), or macro files that have the filename extension of *.swp or *.swb. The *.swb filename extension type is a legacy macro. You can edit and save these files into the newer SWP format, or you can run them as they are. Also keep in mind that *.swp is the filename extension that is used by the Windows Swap file. This chapter is a quick overview of how to create simple macros, and how to connect them to hotkeys and custom toolbar buttons. It guides you through the creation of an intermediate-level macro to show some of the capabilities that are available to combine with Excel and SolidWorks at the same time. NOTENOTE 895 IN THIS CHAPTER Recording macros Creating a macro with a user form Finding macro help Creating and Using Macros 43_080139 ch32.qxp 3/26/07 5:40 PM Page 895 This chapter is not a comprehensive how-to guide for API programming. That would be a book unto itself. However, the end of this chapter does offer some useful resources for help with macros. Recording Macros Everything has to start somewhere, and macros start from one of three places: n As a completely new macro n From another copied and edited macro n From a recorded macro Recorded macros do not always do everything that you want them to do, but they usually offer a good starting place and direction. When recording a macro, SolidWorks lists the SolidWorks API commands that are used to create the action that is being recorded. The macro recorder does not always capture all of the actions, and it does not always record the latest versions of the functions, but again, it is a starting place. Recording a rectangle-sketching macro Before getting started, you need to become acquainted with the Macro toolbar. This is shown in Figure 32.1. FIGURE 32.1 The Macro toolbar The first macro in this chapter is a simple one that is used frequently: sketching a rectangle and centering it on the Origin. When you start to make a new macro, you have to think about where you want it to start and finish. What exactly do you want to automate? Do you want the macro to always create a rectangle on the Front plane, or just on a selected plane? Does it always center on the Origin or on a selected point? The macro in this example needs to do the following: n Create a rectangle on a selected plane n Center the rectangle on the part Origin n Add dimensions and allow the user to enter values as the macro plays 896 Working with Specialized FunctionalityPart VII 43_080139 ch32.qxp 3/26/07 5:40 PM Page 896 This means that the selection of the sketch plane needs to be either not recorded or edited out afterward. Because this section discusses recording rather than editing, the macro will be recorded without the reference. To prepare for recording the macro, you need to turn off PhotoWorks if it is turned on. Macros record some PhotoWorks settings, which are not needed unless you are doing something that is specific to PhotoWorks. You can turn it off at Tools ➪ Add-Ins ➪ PhotoWorks. Also, when recording a macro, be careful not to make a lot of extra mouse-clicks or keyboard strokes. These may record unnecessary data to the macro, which requires additional editing. Recording the macro To record the macro, follow these steps: 1. Open a new part and select a plane. 2. Click the Record Macro button on the Macro toolbar. 3. Open a sketch on the selected plane and sketch the rectangle around the Origin. 4. Sketch a construction line either from corner to corner or from midpoint to opposite midpoint. 5. Select the construction line and the Origin, and assign a sketch relation of Midpoint. 6. Apply a dimension to a horizontal line and accept the default dimension. 7. Apply a dimension to a vertical line and accept the default dimension. 8. Click the Stop Macro button on the Macro toolbar, and save the macro with a name such as Rectangle.swp. The Macro Editor appears and shows the recorded macro: ‘**************************************************************** **** ‘ C:\DOCUME~1\MATT~1.SON\LOCALS~1\Temp\swx3696\Macro1.swb – macro _ recorded on 12/05/06 by matt ‘**************************************************************** **** Dim swApp As Object Dim Part As Object Dim SelMgr As Object Dim boolstatus As Boolean Dim longstatus As Long, longwarnings As Long Dim Feature As Object Sub main() Set swApp = Application.SldWorks Set Part = swApp.ActiveDoc Set SelMgr = Part.SelectionManager 897 Creating and Using Macros 32 43_080139 ch32.qxp 3/26/07 5:40 PM Page 897 Part.SketchRectangle -0.04490775510204, 0.02713176870748, 0, _ 0.06081258503401, -0.02806734693878, 0, 1 Part.ClearSelection2 True Part.CreateLine2(-0.04490775510204, -4.677891156463E-04, 0, _ 0.06081258503401, -4.677891156463E-04, 0).ConstructionGeometry = True Part.SetPickMode Part.ClearSelection2 True boolstatus = Part.Extension.SelectByID2(“Point1@Origin”, _ “EXTSKETCHPOINT”, 0, 0, 0, False, 0, Nothing, 0) boolstatus = Part.Extension.SelectByID2(“Line5”, “SKETCHSEGMENT”, _ 0.007328696145125, -6.237188208617E-04, 0, True, 0, Nothing, 0) Part.SketchAddConstraints “sgATMIDDLE” Part.ClearSelection2 True boolstatus = Part.Extension.SelectByID2(“Line1”, “SKETCHSEGMENT”, _ 0.009355782312925, 0.02759955782313, 0, False, 0, Nothing, 0) Dim Annotation As Object Set Annotation = Part.AddDimension2(0.0057694, 0.039918, 0) Part.ClearSelection2 True Part.Parameter(“D1@Sketch6”).SystemValue = 0.0898155 boolstatus = Part.Extension.SelectByID2(“Line4”, “SKETCHSEGMENT”, _ 0.04490775510204, 0.009667641723356, 0, False, 0, Nothing, 0) Set Annotation = Part.AddDimension2(0.0661142, 0.0057694, 0) Part.ClearSelection2 True boolstatus = Part.Extension.SelectByID2(“D1@Sketch6@Part2.SLDPRT”, _ “DIMENSION”, 0, 0, 0, False, 0, Nothing, 0) Part.Parameter(“D2@Sketch6”).SystemValue = 0.0551991 Part.ClearSelection2 True End Sub Understanding what was recorded A few pieces of macro syntax and terminology need to be covered first, especially for those who are not familiar with programming, or who need a refresher. A single quote in front of a line of text is a way to comment out a line, which means that anything after the single quote is not processed, but may be used for reference, explanation, or troubleshooting. A space followed by an underscore at the end of a line means that the line is continued to the next line. You do not see this in the recorded macro, but it is used here because the lines are too long for the page and must therefore wrap. At the beginning of the macro, the line with the file path between two rows of asterisks is only added to make a record of who created the macro and when they did so. The name is taken from the user’s Windows login name. It is common practice to leave this information in the macro, and 898 Working with Specialized FunctionalityPart VII 43_080139 ch32.qxp 3/26/07 5:40 PM Page 898 even to edit it as various people update the macros. This is one way of giving credit to the original author when macros are shared among users. The six lines of Dim statements are establishing the different types of variables that are often used in macros. Just because a variable has a Dim statement does not necessarily mean that it is used in the macro. You can remove some of these if you want. The first two, swApp and Part, must remain; in fact, these are used for almost all SolidWorks macros. In this case, you can leave all of the Dim statements in. The line starting with Part.SketchRectangle is placing the two corners that are used to describe the rectangle. These dimensions are in meters. SolidWorks macros all work in meters, and to use other units, you have to work with conversion factors as appropriate. In more sophisticated macros, the document units are determined, and any user input is filtered through that setting. The corner coordinate data is given in the form X1, Y1, Z1, X2, Y2, Z2, with the 1 and 2 representing the first and second corners. To clean up the macro, you could change some of the numbers to round them out to whole numbers in the unit system of your choice. However, if you do that, then you will need to make other changes, such as changing the endpoint coordinates of the construc- tion line that is sketched later at the Part.CreateLine2 command. Going through the rest of the macro in this way helps you to understand what each of the func- tions does. It helps even more if you keep the SolidWorks API Help file open and look up func- tions as you go through the macro, such as the Part.ClearSelection2 True line. Searching the Index on just the ClearSelection2 code brings you to an entry that also indicates what the True option does. You can access the API Help from the main SolidWorks Help menu, under SolidWorks and Add-Ins API Help Topics. This help file has a lot of detailed information about specific methods. Replaying the macro The first step in using your new macro is to see what the recording contains. Exit and delete the sketch. As an experiment to see how the macro reacts, do not pre-select a plane. Return to the macro editor window, and press the Run Macro button. The rectangle is drawn, the construction line is drawn, the sketch relation is applied, and the first dimension is applied, but when you enter a value for the dimension, there is an error. The error originates from the Part.Parameter line. In this short chapter, there is not enough space to dis- cuss troubleshooting API functions; in this case, it is acceptable to comment out the offending line. The error message enables you to debug the problem. After you click the Debug button, the editor highlights the problem line of code, and if you put a single quote in front of the line and press Run Macro again, the same error occurs for the second dimension at an almost identical line. You can comment out the second line as you did with the first line. This is shown in Figure 32.2. 899 Creating and Using Macros 32 43_080139 ch32.qxp 3/26/07 5:40 PM Page 899 FIGURE 32.2 Commenting out offending lines in the code Clear the sketch and run the macro again. This time, with the two lines of code commented out, it works perfectly. Also notice that if no plane is pre-selected, then it goes to the Front plane by default; however, if a plane is pre-selected, then the rectangle is built on that plane. You may notice some irregularities, for example, that the sketch overdefines if multiple rectangles are built in a single sketch, or a that new rectangle may pick up automatic relations to existing geometry. You can either live with these shortcomings or learn more sophisticated programming techniques to overcome them. So with a simple recording operation and some minor revisions, you have a simple yet functional and highly useful macro that draws a centered rectangle around the Origin. Many of the tutorials in this book start with the instruction to “sketch a rectangle centered on the Origin,” and this is a macro that I use frequently. 900 Working with Specialized FunctionalityPart VII 43_080139 ch32.qxp 3/26/07 5:40 PM Page 900 Storing your macro Out of necessity, I usually store macros in two locations. One location is in the SolidWorks installa- tion directory in a folder called macros. It is important for this folder to exist with the name spelled just that way so that certain functions with the Tools ➪ Customize dialog box will work properly, including assigning hotkeys and menu selections to the macros. Of course, the other location is not in the SolidWorks installation directory so that when you unin- stall the software, you do not lose all of your macros. When you do this, remember to also set the Tools ➪ Options ➪ File Locations ➪ Macros setting. Telling SolidWorks where the macros are only affects where SolidWorks looks when you press the Run Macro button on the Macro toolbar; it does not affect the need for the macros folder in the installation directory that is required by the Tools ➪ Customize dialog box mentioned previously. Connecting to a hotkey You can connect a macro to a hotkey through the Tools ➪ Customize ➪ Keyboard interface. This interface has been greatly improved in SolidWorks 2007. In order to connect a macro to a hotkey, you require the macros folder mentioned previously. You may need to restart the software if you have just created the macros folder, or if you have added new macros in the current session. Scrolling to the bottom of the list shows the macros in the folder, as shown in Figure 32.3. FIGURE 32.3 The Tools ➪ Customize ➪ Keyboard interface 901 Creating and Using Macros 32 43_080139 ch32.qxp 3/26/07 5:40 PM Page 901 Notice that some of the listed macros already have shortcuts, or hotkeys, assigned. Hotkey assign- ments are discussed in Chapter 2. Connecting to a custom toolbar button Connecting a macro to a custom toolbar button is far easier than it sounds. You can place custom toolbar buttons onto your toolbar from Tools ➪ Customize ➪ Commands ➪ Macro. When you drop them onto a toolbar, the Customize Macro Button dialog box appears, as shown in Figure 32.4. FIGURE 32.4 The Customize Macro Button dialog box Type a Tooltip and a Prompt. You can select a custom image for the button. The custom image must be 16 pixels square, in a bitmap format using 256 colors. In the Macro selection box, click the Ellipse button (. . .) to browse to the macro location. You can even assign a shortcut, or hotkey, here; however, I would recommend one or the other, but not both a custom toolbar button and a hotkey. You will end up using one technique or the other, but not both. Creating a Macro with a User Form The rectangle macro is a very simple macro that performs a set operation using standard SolidWorks input forms for the dimensional data. While that was a very simple macro, the macro in this section is an intermediate-level macro; it is still not highly complex, but it may take more than an hour to put together. The interface, or user form, is shown in Figure 32.5. 902 Working with Specialized FunctionalityPart VII 43_080139 ch32.qxp 3/26/07 5:40 PM Page 902 FIGURE 32.5 The user form for the macro This macro creates a spline from an equation, using Excel to evaluate points in the equation. It allows the user to enter an equation in the form Y = , where the expression can use quadratic or periodic functions. The user then specifies a first and a last value, and then tells the macro to create the spline. You can open this macro using the Edit Macro tool on the Macro toolbar. The macro can be found on the CD-ROM for Chapter 32, with the filename Chapter 32 – User Form.swp. Building the Form Whenever an interface is created, specific actions are assigned to specific controls in the interface. The most obvious control that performs an action here is the Create Spline feature. In the macro editor, you can double-click the Create Spline button to display the code for the form. Each of the controls that accept user input drives a particular variable, which is then used to calcu- late another value or to set a part of the interface. You should have enough controls to do what needs to be done, but not so many that the interface becomes confusing. For example, the Spin Increment is an unnecessary control, and could be removed to make the interface a little less confusing. You can build the form visually by using the tools on the Toolbox toolbar. The properties for each control are found in the Properties window, which you can access through the View menu. The Properties window and Toolbox toolbar are shown in Figure 32.6. 903 Creating and Using Macros 32 43_080139 ch32.qxp 3/26/07 5:40 PM Page 903 FIGURE 32.6 The Properties window and Toolbox toolbar After the user fills out all of the boxes and presses the Create Spline button, the subroutine called CommandButton1_Click takes over. This is the code that you can see by double-clicking the Create Spline button in Design mode. The macro starts by checking to see if there is an active SolidWorks document: Set swApp = CreateObject(“SldWorks.Application”) Set Model = swApp.ActiveDoc If Model Is Nothing Then ‘ If no active doc found swApp.SendMsgToUser “No active doc found!” ‘ Warning to the user Exit Sub ‘ Exit this app End If Then, based on user input, the last X value of the spline is either calculated or used directly. The first X is entered explicitly by the user. first = firstval.Value last = rangeInt.Value If rangeInt1.Value = True Then last = first + rangeInt.Value 904 Working with Specialized FunctionalityPart VII 43_080139 ch32.qxp 3/26/07 5:40 PM Page 904 If rangeInt2.Value = True Then last = first + (howMany - 1) * rangeInt.Value Then the step interval is calculated, based on the range and number of data points. step = Abs((last - first) / (howMany - 1)) In macros, you find yourself checking for situations that you may normally assume to be the case, and having the macro make a decision, based on the results of the check. For example, this macro checks for an open sketch, and if it does not find one, then it creates one. Set activeSketch = Model.GetActiveSketch If (activeSketch Is Nothing) Then ‘ If a Sketch is not active, then Model.InsertSketch ‘ insert a new sketch for our spline End If The real functional part of the macro exists in the next few lines. For row = 1 To howMany ‘Rebuild user input equation strlen = Len(equation.Value) ‘length of equation string neweq = “=” & equation.Value ‘put an “=” in front of the eq repl = “A” & row neweq = Replace(neweq, “X”, repl, 1)’step through string and find “X” neweq = Replace(neweq, “x”, repl, 1) ‘replace “X” with “a(row)” ws.Cells(row, col).Value = xvalue ‘write values to excel ws.Cells(row, col + 1).Value = neweq yvalue = ws.Cells(row, col + 1).Value ‘read Y value from excel Model.SketchSpline (howMany - row), xvalue * unitconv, yvalue * unitconv, 0# ‘ Draw the sketch thru it xvalue = xvalue + step ‘ read X value from excel Next row This macro writes an equation in each cell with the appropriate X value, and then draws a spline point using the matching X and Y values. It then steps to the next row and does it again until all of the values have been calculated and all of the points drawn. This has the additional benefit of being able to leave you with an Excel spreadsheet that contains the values. 905 Creating and Using Macros 32 43_080139 ch32.qxp 3/26/07 5:40 PM Page 905 Finding Macro Help SolidWorks has some excellent on-line resources with a lot of sample code for many applications. If you are creating a completely new macro with programming, then it is probably best to start out by taking a class in Visual Basic or getting a book on the topic. This will give you a general founda- tion in programming with Visual Basic. Beyond Visual
本文档为【SolidWorks.2007_vba】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
is_329203
暂无简介~
格式:pdf
大小:609KB
软件:PDF阅读器
页数:12
分类:互联网
上传时间:2012-06-17
浏览量:23