Vaishali Sawant
Vaishali Sawant

Reputation: 17

How to create an Excel Shape (Polyline)?

I want to draw a polygon in Excel from VB.NET. whenever I use the AddPolyline method it gives the following error:

'The specified parameter has an incorrect data type.'

My code is:

Dim X1 As New Point
Dim X2 As New Point (25, 100)
Dim X3 As New Point (100, 50)
Dim X4 As New Point (150, 50)
Dim X5 As New Point (25, 100)

Dim arrPoint() As Point = {X1, X2, X3, X4, X5}
Dim rc As Microsoft.Office.Interop.Excel.Shape = objSheet.Shapes.AddPolyline(arrPoint)

Can someone please help?

Upvotes: 0

Views: 2647

Answers (1)

41686d6564
41686d6564

Reputation: 19641

VBA Excel Object Library (Interop.Excel) doesn't have a Point class/structure out of the box. You need to use a two-dimensional array of Singles rather than an array of Points. This should work.

Dim arr As Single(,) = {{25, 100}, {100, 50}, {150, 50}, {25, 100}}
Dim rc As Excel.Shape = objSheet.Shapes.AddPolyline(arr)

If you have an array/list of Points already (received from somewhere) and you'd like to use it, you can write a helper function to convert it to a 2D array. It would look something like this:

Private Function PointsTo2DArray(points As IList(Of Point)) As Single(,)
    Dim arr(points.Count - 1, 1) As Single
    For i = 0 To points.Count - 1
        arr(i, 0) = points(i).X
        arr(i, 1) = points(i).Y
    Next

    Return arr
End Function

Then you can easily do the following:

Dim X1 As New Point(25, 100)
Dim X2 As New Point(100, 50)
Dim X3 As New Point(150, 50)
Dim X4 As New Point(25, 100)

' Assuming you already have this array.
' If you Then don't, don't create one and use a 2D array directly as shown above.
Dim arrPoint() As Point = {X1, X2, X3, X4}

Dim rc As Excel.Shape = xlSheet.Shapes.AddPolyline(PointsTo2DArray(arrPoint))

The result in both cases:

Polyline

References:

Shapes.AddPolyline Method.

Upvotes: 1

Related Questions