Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

Real Hardware Engineers

Code: Supplementary Tools


WRITING VBA MACROS | SAVE AS ‘STEP’ CODE | EXPORT PDF CODE

BY DAVID CAGLE, SENIOR TECHNICAL APPLICATIONS ENGINEER, FICTIV

READ THE ORIGINAL POST HERE


Writing VBA Macros
DOWNLOAD ZIP FOLDER OF MACROS HERE
Learning VBA (writing your own Macros)
● In Excel, numerous tasks are either very tedious or very simple to execute.
● Writing a Macro can take some time, but implementing and learning how to use
Macros becomes easier and easier.
● Writing a Macro correctly saves EVERYONE time and reduces turn time to do even
small jobs.

○ Problems mainly occur on Macros when the file structure changes (i.e., columns
are added, file type changes, names change, etc.).
○ Understanding Macro rules can help you set up an Excel sheet to write Macros
at a later date.
Learning to Navigate via VBA
● Excel is a large matrix (x columns, y rows).
● Learning to move in an Excel sheet is the first and most powerful tool to becoming
good at Macros.
● Why? An Excel sheet is data.
● Learning to move from one location to the next associated location helps you more
quickly associate your data or more quickly decide what you want to do next.

○ Note: If you can write instructions for someone to do your Excel manipulation,
you can write a Macro to do it!
Learning to Navigate via VBA
● Useful commands to help you navigate within your file.

VBA COMMAND Explanation


Sheets("sheet1").select This command selects a specific sheet within your workbook to work within.
Note: The name within the quotations “ “ must be verbatim to work. “sheet1” does
Sheets(##).select not equal “sheet1 “ (the space at the end of the name will return an error)
No quotations “ “ means the item within the parentheses is a variable.

Best Practice: use sheet names that NEVER have spaces. If you would like to use
sheet names with multiple words, separate them via an underscore. Ex:
“MONTHLY_BUDGET”
***In general, most applications will be hindered with the use of spaces; avoid them.

1) Range(“A1”).select This command can be used to select a specific cell (Ex. 1) or specific range of cells
2) Range (“A1: A10”).select (Ex. 2). Ex. 3 becomes powerful when you would like your range to be selected to
3) Range(“A” & j ).select become a variable and use the “Range” function within a loop (more on this later).

1) ActiveCell.Offset(1, 0).select This command can be used to navigate off your activecell. Ex. 1 moves you down
2) ActiveCell.Offset(0, 1).select one row. Ex. 2 moves you right one row. Ex. 3 allows you to use variables to make a
3) ActiveCell.Offset(y, x).select decision on where to navigate (you must clarify these values for the command to
work). Positive is down for “y” direction and to the right for “x” direction.

1) Activecell.address This command returns the full address of the current position (Format: “$A$5”).
2) Activecell.row This command returns the row the cell is currently located in (Format: #).
3) Activecell.column This command returns the column the row is currently in (Format: #) .

For i = 1 To 10 This is a loop command. The commands below the “for” and above the “next i” will
‘ code to execute goes here repeat till i=10.
Next i
Learning to Navigate via VBA
● Check your understanding.
● Follow the script below. What will the code return for when i = 4?
Learning to Navigate via VBA
● Answer.
● Follow the script below. What will the code return for when i = 4?
Teaching Yourself New Commands
● There are many excel VBA commands that you may not know how to correctly
“write” as code, but learning what they are is easy to figure out.
● Doing this and using your engineering prowess for understanding something you’ve
never seen before will allow you to figure out which items you can change and
manipulate.
● HINT: Break down what you want to do in a series of basic steps.
Recording a Macro
● This can be a very powerful tool to teach yourself VBA commands.
● This can also be useful if you are doing generic Excel file manipulation to an Excel file
that is always in the same format.
Recording a Macro
● Prompt: You have an Excel file with numerous
columns that have different audiences.
Depending on to whom you are sending this
Excel report, you want to (hide and/or delete
columns). You do this daily.

● Details: You have one source sheet; you create


“report” outs in two separate tabs.

● You want to manipulate your source data for


Customer 1 and 2 but make sure you don’t lose
any data.

● Customer 1 : Needs all data in their sheet but


does not need columns in blue

● Customer 2: Needs all data in their sheet but


does not need columns in red

● Bonus: Your boss is only interested in seeing


columns in white, but wants to be able to see
the other data, should she have more
questions (a.k.a. You want to hide the data, not
remove it).
Recording a Macro
● Think through the exact steps it takes for you to perform the task.

○ Click the my “source_data” tab.


○ Press ctrl-shift-a (selects all cells in the tab).
○ Copy the selected cells (ctrl-c).
○ Click the “customer1_report_out” tab.
○ Select Cell “A1” and paste (ctrl-v).
○ Hold ctrl and select all blue columns.
○ Right click and press “delete”.

● You are now ready to record a Macro!


Recording a Macro
1. Select “View” in command tabs.
2. Select “Macros” on far-right menu options.
3. Select “Record Macro”.
Recording a Macro
● Input the “Macro Name” and “Description,” if you would like.
● Reminder: The name of your Macro cannot begin with special characters, have spaces, or conflict
with a Microsoft Excel function.
● “Customer 1 Report Out” – Shows error (on left).
● Instead follow Best Practice Rule (Slide 5):
○ “Customer1_Report_Out”

● After you press “OK,” you will be “live,” and every action you do within your Excel file will be
recorded. Know the steps you want to perform.
Recording a Macro
● To view your recorded Macro, right-click on the tab name (at bottom) and click “View
Code.” A new window will launch (short cut: alt-F11).
● In the new window, click on “Module” on the left-hand side.
● “Module#” stores your written or recorded code.
Recording a Macro
● All codes start with “Sub,” followed by the name of your Macro, and end with “End
Sub.”
● To the right is the code from your manual Excel
manipulation.
● What is not shown from our procedure?
● Why would this happen?
○ Click my “source_data” tab
○ Press ctrl-shift-a (selects all cells in the tab)
○ Copy the selected cells (ctrl-c)
○ Click “customer1_report_out” tab
○ Select Cell “A1” and paste (ctrl-v)
○ Hold ctrl and select all blue columns
○ Right click and press “delete”
Recording a Macro
● Click my “source_data” tab
● Press ctrl-shift-a (selects all cells in
the tab)
● Copy the selected cells (ctrl-c)
● Click “customer1_report_out” tab
● Select Cell “A1” and paste (ctrl-v)
● Hold ctrl and select all blue columns.
● Right click and press “delete”

What command is missing?


1. Click “source_data” tab

Why did this happen? When the macro These steps were not in our
began recording, the user was already on procedure. The first line was
the correct tab! recorded because when the user
“right-clicked” to delete, he clicked
What if the user was on the wrong tab in the Excel window that happened
and ran this? The procedure would work, to be cell “N1” (this line is not
but the data that was copy-pasted would important).
be wrong.
Fix: Add sheets (“Source_Data”).select “ to The second line was added by Excel.
the beginning of the code. Let Excel do its own thing when you
see a command you don’t fully
understand.
Learning from a Recorded Macro
● How do I take what I’ve learned via :
“Customer1_Report_out()” and perform
this similar task for “Customer2”

● What lines need to change? How?


Running a Macro from a VB Window

Click the “Green” play


triangle button to run
the code.

Click to the left of the code to add “break points.”


These will run your code up to a certain point and
then pause; they will help you find errors. Click
break point again to remove it.
Learning from a recorded Macro:

Application.ScreenUpdating = False

As your code becomes more involved, add this line to the beginning
of your code. This will prevent your screen from flickering.
Writing a Macro to Work on Two Files

● Easy task: Two files; same structure; one master file with 2 columns that are
separately owned.
● One column is “CompanyA” input; the other column is “Supplier” input.
● When the file comes from the supplier, column “E” must be copied and pasted into
“CompanyA” from the updated supplier file.
● Develop Procedure: Remember, think very basic—a to b, b to c, etc.
1. Open “Myfile1”
2. Open “Other_file2”
3. Click right tab in “Other_file2”
4. Copy column “E” in workbook “Other_file2”
5. Select Workbook “Myfile1”
6. Select right tab in “Myfile1”
7. Select Column “E” and paste
8. Save “Myfile1”
9. Close “Other_File2”
10. Save “Myfile1”

● Time to record!
Writing a Macro to Work on Two Files

● Check results.
● Any suggestions?
Writing a Macro to Work on Two Files
● “Sheet1” selection not specified in the paste command.
● Add line: Application.ScreenUpdating = False
● Make this Macro a button and place it on a control panel in your workbook! (People
like buttons!)
● When working, always think top down: what “workbook”; what “sheet”; what “cell”
(row/column).
Creating a “button” for a Macro
● Add “button” icon to your toolbar
● Right click “quick access toolbar”
■ Select “customize quick
access toolbar”
■ From pop up window>
left column > top drop
down > Select “All
Commands”
■ Scroll down to “button
(From control)”
■ Click “Add” from center

■ “Button” will now show
up on your toolbar
Creating a “button” for a Macro
● Add button to “control panel” sheet.
● Assign it a Macro.
Creating a “button” for a Macro
Click your Macro; click OK
SCRIPTS:
SAVE AS ‘STEP’
&
EXPORT PDF
Table 1: Save as “STEP” Code
' Save Part as STEP with rev in folder .swp ---------------------------12/09/14
'
'Description: Macro to save part as STEP file in specified location with rev information in the
step file name.
'
'Precondition: Any active part with some geometry
'
'Postcondition: Part is saved as "STEP" file.=

Dim swApp As SldWorks.SldWorks


Dim swModel As SldWorks.ModelDoc2
Dim sFileName As String
Dim FileLocation As String
Dim sRev As String

Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc

If swModel Is Nothing Then


swApp.SendMsgToUser2 "Please open a PART file!", swMbWarning, swMbOk
Exit Sub
End If
Table 1: Save as “STEP” Code

If swModel.GetType <> swDocPART Then


swApp.SendMsgToUser2 "Not a Part File, please open a PART file!", swMbWarning,
swMbOk
Exit Sub
End If

'Get File Name without extension


sFileName = Mid(swModel.GetPathName, InStrRev(swModel.GetPathName, "\") + 1)
sFileName = Left(sFileName, Len(sFileName) - 7)

'STEP file Location


‘Change the code in quotes to your file location
FileLocation = "C:\Users\David\Desktop\Macro_out_step"
FileLocation = FileLocation & "\"

'Custom Property
sRev = swModel.CustomInfo("Revision") 'Change Custom Property name here

swModel.SaveAs (FileLocation & sFileName & "_Rev_" & sRev & ".step")

End Sub
'------------------
Table 2: Export PDF Code
' Precondition: Have an open drawing document.
'
' Postcondition: Exports all Drawing sheets in a single PDF. Exports all KS in
' a single PDF. Writes a log showing the processed documents. Renames and
' moves duplicates to a backup directory.
'
'*******************************************************************************

Option Explicit
Global Const swDocDRAWING = 3 '
Global Const version = 2.55

Dim swApp As SldWorks.SldWorks


Dim swDoc As SldWorks.ModelDoc2
Dim swDraw As SldWorks.DrawingDoc
Dim swSheet As SldWorks.Sheet
Dim FileTyp As String
Dim swModelDocExt As SldWorks.ModelDocExtension
Dim swPDFData As SldWorks.ExportPdfData
Dim FSO
Table 2: Export PDF Code
' Dim strPartNumber As String ' Stores the Part Number of the current drawing document
Dim Path As String ' Stores the root path of Kit Sheet PDF's
Dim Format As String ' Stores the template name of the drawing sheet used
Dim SheetNames As Variant ' Array that stores all sheet names in the document
Dim bRet As Boolean ' Determines if function executed properly
Dim i As Long ' Count variable for "for" function
Dim g As Long ' Count variable for "for" function
Dim Filename As String ' Name of the open document
Dim ResFileName As String ' Resolved name of the open document

'**************************************************************************************************
' Function: Main
'
' Description: First process to run in the macro. Initiates all variables. Ensures a drawing doc
' is currently open and active.
'
'**************************************************************************************************

Sub main()
Set swApp = Application.SldWorks
Set swDoc = swApp.ActiveDoc
Set swDraw = swDoc
Table 2: Export PDF Code
bRet = False

If Not swDoc Is Nothing Then ' Document is valid


FileTyp = swDoc.GetType ' Get document type
If FileTyp = swDocDRAWING Then ' Is it a drawing ?
Set swSheet = swDoc.GetCurrentSheet
ProcessDoc swApp, swDoc
Else
MsgBox "Current document is not a drawing." & Chr(13) & Chr(13) _
& "Please load/activate a SolidWorks " & Chr(13) _
& "drawing and try again.", vbExclamation
End If
Else
MsgBox "No active drawing found in SolidWorks." & Chr(13) & Chr(13) _
& "Please load/activate a SolidWorks " & Chr(13) _
& "drawing and try again.", vbExclamation
End If
End Sub

'**************************************************************************************************
' Function: ProcessDoc
'
' Description: Get all sheet names and runs the export process.
'
'**************************************************************************************************
Table 2: Export PDF Code
Sub ProcessDoc(swApp As SldWorks.SldWorks, swModel As SldWorks.ModelDoc2)

'** Get the sheet names and count of each type


SheetNames = swDoc.GetSheetNames

'** Call the export procedure


ExportSheets swApp, swDoc

'** Refresh the view


swDoc.ClearSelection2 True
swDoc.WindowRedraw
End Sub

'***********************************************************************
' Function: ExportSheets
'
' Description: Exports all Kit Sheets and Drawings as PDFs to the
' appropriate sub-directories.
'
'***********************************************************************
Table 2: Export PDF Code
Sub ExportSheets(swApp As SldWorks.SldWorks, swDoc As SldWorks.ModelDoc2)
Dim strFile As String
Dim DrawingSheets() As String
Dim lErrors As Long
Dim lWarnings As Long
Dim Count As Long
Dim boolstatus As Boolean
Dim ExpPath As String
Dim Check As Boolean
Dim ModString As String
Dim FileLocation As String
Dim sRev As String

Filename = swDoc.GetPathName

Set swApp = Application.SldWorks


Set swDoc = swApp.ActiveDoc
Set FSO = CreateObject("Scripting.FileSystemObject")

'** Export path for the PDF file

FileLocation = "C:\Users\dcagle\Desktop\PDF_RELEASE"
FileLocation = FileLocation & "\"
Table 2: Export PDF Code
Set swModelDocExt = swDoc.Extension
Set swPDFData = swApp.GetExportFileData(swExportPdfData)

'Custom Property
sRev = swDoc.CustomInfo("Revision") 'Change Custom Property name here

Check = False
Count = 1
If Filename <> "" Then
ResFileName = Left(Filename, Len(Filename) - 7)
Else
MsgBox "Please save the drawing before running this macro.", vbCritical
End If

Do While Check = False


ModString = Right(ResFileName, Count)
If Left(ModString, 1) = "\" Then
ResFileName = Right(ResFileName, Count - 1)
Table 2: Export PDF Code
Check = True
Else
Count = Count + 1
End If
Loop

ExpPath = FileLocation & ResFileName & "_REV_" & sRev & ".PDF"

'** Export the Sheets as a PDF


boolstatus = swPDFData.SetSheets(swExportData_ExportSpecifiedSheets, SheetNames)
boolstatus = swModelDocExt.SaveAs(ExpPath, 0, 0, swPDFData, lErrors, lWarnings)
Fictiv can help save you up to 15 hours per month
with instant quotes, automated DfM, and access to a
wide range of capabilities through a single online
platform.

Learn more and create your free account to get


started at fictiv.com

You might also like