Tuesday, March 5, 2013

Office Development : How to make an Excel cell read only

*** Please note that this article describes how to lock an Excel cell from code in Excel Add-in/Template/ Workbook type Visual Studio projects. If you want to make an Excel cell read only from within your application, please check the comments.

In order to lock the cells for a given range, first set the Locked property for that range to true and then protect that particular sheet. This will lock the cells from being edited. The following sample code will lock the cell range from A1 to C3 from editing.
this.Application.Cells.Locked = false;
this.Application.get_Range("A1", "C3").Locked = true;
Excel.Worksheet Sheet1 = (Excel.Worksheet)this.Application.ActiveSheet;
Sheet1.Protect(missing, missing, missing, missing, missing, missing, missing 
        missing, missing, missing, missing, missing, missing, missing,                            missing, missing);

References :
http://social.msdn.microsoft.com/Forums/en/vsto/thread/f89fe6b3-68c0-4a98-9522-953cc5befb34
http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/583f39a1-c3e2-4aaf-8c85-caacb6dbfa94

2 comments:

  1. hi

    I tried your code ,but it desen't work for me, do I have to install any liabrary before I can compile the code.Additionally ,I got code snippet from Google either ,this solution is base on a free C# Excel component ,it works smoothly.Here is full programming guide regarding locking excel cells in C#.Hope it can be helpful.

    kind regards.

    ReplyDelete
    Replies
    1. Hi Alex, Answer to your question is NO, You don't need to include any library. This code segment can only be used with excel development. The article that you have provided explains how is it done externally. Title that I've given is misleading, I've change it. Thanks for the comment

      Delete