VBA – Programmatically Draw Boxes with Code
VBA Draw Boxes with Code
There are many reasons you may want to be able to programmatically draw boxes, an automated gantt chart would be cool? Here is one way to do it.
This is the basic code to draw a box:
ActiveSheet.Shapes.AddShape _
(msoShapeFlowchartProcess, 0, 0, 48, 12.75).Select
Selection.ShapeRange.Fill.ForeColor.SchemeColor = 11
Selection.ShapeRange.Fill.Solid
Selection.ShapeRange.Fill.Visible = msoTrue
It’s really not that daunting, there are only two notable things to look at; Schemecolor is obviously the color and the 0,0,48,12.75.
So what’s the 0,0,48,12.75? Simply the Left Position, Top Position, Width, and Height. You can adjust these however you would like, adjusting the first two to change the boxes position on the screen, and the latter two to change the size of the box. I used these dimensions becuase they were a good guess at making a box the same size as a cell.
And here is the code used to dynamically draw the green boxes in the above picture:
Sub DynamicBoxes()
Dim x As Double
'This makes horizontal boxes
For x = 0 To 240 Step 48
'reference to the 4 numbers left,top,width,height
ActiveSheet.Shapes.AddShape _
(msoShapeFlowchartProcess, x, 0, 48, 12.75).Select
Selection.ShapeRange.Fill.ForeColor.SchemeColor = 11
Selection.ShapeRange.Fill.Solid
Selection.ShapeRange.Fill.Visible = msoTrue
Next x
'This makes vertical boxes
For x = 0 To 127.5 Step 12.75
ActiveSheet.Shapes.AddShape _
(msoShapeFlowchartProcess, 0, x, 48, 12.75).Select
Selection.ShapeRange.Fill.ForeColor.SchemeColor = 11
Selection.ShapeRange.Fill.Solid
Selection.ShapeRange.Fill.Visible = msoTrue
Next x
End Sub