Search code examples
vb.netexcelbasicvba

How do I create and delete (or move) a freeform shape in Microsoft Visual Basic Express 2010


I have managed to create and delete multiple freeform shapes in Microsoft Excel through a set of VBA commands and would like to do the same with Microsoft Visual Basic Express 2010 but really am getting nowhere! The creation code in Excel looks something like:

With Sheet1.Shapes.BuildFreeform(msoEditingAuto, triXArray(1), triYArray(1))
    For cnt = 2 To 4
        .AddNodes msoSegmentLine, msoEditingAuto, triXArray(cnt), triYArray(cnt)
    Next
End With

triXArray() and triYArray() are arrays of the X and Y coordinates of the points and cnt is the counter which loops through the items (it's a triangle).


Solution

  • This is how you create and delete a freeform shape in Excel from VB.Net

    You need to assign the freeform to a shape after you .ConvertToShape(). That ways, you can work (delete, move) with it

    Imports Excel = Microsoft.Office.Interop.Excel
    Imports MsoEd = Microsoft.Office.Core.MsoEditingType
    Imports MsoSg = Microsoft.Office.Core.MsoSegmentType
    
    Public Class Form1
        '~~> Define your Excel Objects
        Dim xlApp As New Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet
        Dim shpFF As Excel.FreeformBuilder
        Dim Shp As Excel.Shape
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            '~~> Add a New Workbook
            xlWorkBook = xlApp.Workbooks.Add
            '~~> Work with first sheet
            xlWorkSheet = xlWorkBook.Sheets(1)
    
            '~~> Create the Freeform shape
            shpFF = xlWorkSheet.Shapes.BuildFreeform(MsoEd.msoEditingCorner, 360, 200)
    
            With shpFF
                '~~> Add the nodes. You can use your array method as well
                .AddNodes(MsoSg.msoSegmentCurve, MsoEd.msoEditingCorner, _
                 380, 230, 400, 250, 450, 300)
                .AddNodes(MsoSg.msoSegmentCurve, MsoEd.msoEditingAuto, 480, 200)
                .AddNodes(MsoSg.msoSegmentLine, MsoEd.msoEditingAuto, 480, 400)
                .AddNodes(MsoSg.msoSegmentLine, MsoEd.msoEditingAuto, 360, 200)
    
                '~~> Convert it to shape and assign it
                Shp = .ConvertToShape()
    
                '~~> Display Excel
                xlApp.Visible = True
            End With
    
            MessageBox.Show ("Wait")
    
            '~~> Delete the shape
            Shp.Delete()
        End Sub
    End Class