VBA macro to toggle white background in drawings
Introduction
On the SolidWorks forum, someone asked how to create a macro that toggles between the default drawing background color and a white color.
The goal was to make it easier to capture images where a white background was required.
Here is a simple macro that does precisely that. I will also explain the basic buttons/shortcuts/menus you need.
If you want to switch between other colors, you can modify that in the Color1 and Color2 constants below.
But how do we get that number that corresponds to the color we want? Have a look in the immediate window. We used a Debug.Print statement to get the value from the options.
Modify the number in the code (Color2), and when you run the macro, the background color will switch between white and your favorite color.
Code
'Here you can set the 2 colors you want to toggle between
Sub main()
'It uses a system option, so every drawing you open will get the choosen color
'This can be usefull if you want to make screen captures on a white background.
Const Color1 As Variant = 16777215 'color white
Const Color2 As Variant = 14411494 'color grey (default color for drawing background)
try_:
On Error GoTo catch_
Dim swApp As Object
Set swApp = Application.SldWorks
Dim swModel As ModelDoc2
Set swModel = swApp.ActiveDoc
'Get the color on first use (look in Immediate window CTRL + G)
Dim Color As Variant
Color = swApp.GetUserPreferenceIntegerValue(swUserPreferenceIntegerValue_e.swSystemColorsDrawingsPaper)
Debug.Print "Color : " + CStr(Color)
If Color <> Color1 Then
Color = swApp.SetUserPreferenceIntegerValue(swUserPreferenceIntegerValue_e.swSystemColorsDrawingsPaper, Color1)
Else
Color = swApp.SetUserPreferenceIntegerValue(swUserPreferenceIntegerValue_e.swSystemColorsDrawingsPaper, Color2)
End If
swModel.ForceRebuild
GoTo finally_:
catch_:
Debug.Print "Error: " & Err.Number & ":" & Err.Source & ":" & Err.Description
finally_:
Debug.Print "FINISHED Toggle Drawing Background"
End Sub