Tutorial :What is the C# equivalent of this Excel VBA code for Shapes?



Question:

This is the VBA code for an Excel template, which I'm trying to convert to C# in a VSTO project I'm working on. By the way, it's a VSTO add-in:

Dim addedShapes() As Variant  ReDim addedShapes(1)  addedShapes(1) = aBracket.Name    ReDim Preserve addedShapes(UBound(addedShapes) + 1)  addedShapes(UBound(addedShapes)) = "unique2"    Set tmpShape = Me.Shapes.Range(addedShapes).Group  

At this point, I'm stumped by the addedShapes(), not sure what this is all about.

Update: Matti mentioned that addedShapes() represents a variant array in VBA. So now I'm wondering what the contents of addedShapes() should be. Would this be the correct way to call the Shapes.Range() call in C#?

List<string> addedShapes = new List<string>();  ...  Shape tmpShape = worksheet.Shapes.get_Range    (addedShapes.Cast<object>().ToArray()).Group();  

I'd appreciate anyone who's worked with VBA and C# willing to make a comment on my question & problem!


Solution:1

I'm not sure what your actual question is supposed to be, but addedShapes is an array. In VB and its variants, arrays are declared and accessed using () instead of [].

Also, your code looks like it's just a really long-winded way of doing:

object[] addedShapes = new object[] { aBracket.Name, "unique2" };  Shape tmpShape = worksheet.Shapes.get_Range(addedShapes).Group();  

The last part might alternatively be

Shape tmpShape = worksheet.Shapes[addedShapes].Group();  

See which ever works. I can't really figure out which one MSDN suggests.


Solution:2

Excuse the c style comments, the vb style doesnt syntax hilight nicely.

//This declares an array of variants but does not initialize it.  Dim addedshapes() As Variant    //Initializes the array with a max index of 1. (insert vb index rant here)  ReDim addedShapes(1)    //assigns the contents of aBracket.Name to element 1 of the array.  addedShapes(1) = aBracket.Name     //increases the size of addedShapes by 1, retaining any values.  ReDim Preserve addedShapes(UBound(addedShapes) + 1)     //sets the last element to the string literal  addedShapes(UBOund(addedShapes)) = "unique2"     //Not sure here because I havent done any VBA in a loooong time,  //but anyway it's passing the array.  set tmpShape = Me.Shapes.Range(addedShapes).Group   

in VB, Variant is just a lazy struct that can hold any datatype, int, floats, objects, etc. so in .Net the most direct comparison would be some collection/array of objects. However if you know what is going in there then it's far better to limit the collection to that. So rather than List<object> you'd use List<Class> or List<BaseClass> or List<ISomeInterface>


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »