Quantcast
Viewing all articles
Browse latest Browse all 25

Quickly! Create an excel sheet with many aligned shapes

That's why it's good to be familiar with various APIs: programmatic access allows the automation of the repetitive tasks. Sometimes you can save yourself from lots of grunt work (and/or save time). I have "always delegate to the machine what it can do" or ingrained in my value system.

I added around 50 checkboxes to an excel sheet quickly for some ad-hoc required document (that also could have been automated :). I just copied and pasted and the list of checkboxes ended up having a misaligned list as you can see in the following screenshot.



I was hoping I'll find an "align lefts" feature that will automatically align the lefts of all the shapes. Nope. Someone from the office cuckled: "do it one by one", knowing that this is one extraordinarily mundane task. I said to myself: Nope.

I immediately decided to write up something that will adjust them for me. It should be and it was trivial. The following piece of code for a Visual Studio Excel Addin project was a one minute task. Debug. Run. Mission accomplished without losing my vision.

private void button1_Click(object sender, RibbonControlEventArgs e)
{
    var shapes = ThisAddIn.ApplicationInstance.ActiveSheet.Shapes as Excel.Shapes;
    float firstLeft = -123; //magic
    for (var i = 1; i <= shapes.Count; i++)
    {
        var item = shapes.Item(i);
        if (firstLeft == -123)
        {
            firstLeft = item.Left;
        }
        item.Left = firstLeft;
    }
}

Tada! The check boxes are aligned. You can add more calculations to improve the layout by spreading the items vertically or even into a grid. You can do whatever you want depending on what you need.




Viewing all articles
Browse latest Browse all 25

Trending Articles