Click here to Skip to main content
15,908,020 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I want to lock some of excel cells (not all) using C#.
When someone opens the excel file, they will be able to edit any cell except those cells. And if someone wishes to delete all editable data then read-only cells will retain their value and other editable cells will lose their value. Also the workbook should not have password.

I tried to lock cells like this:

C#
wsht.Cells[rowcnt, colcnt].Locked = true;


Tried locking range in similar way. But they won't work. Protecting sheet after locking cells or range makes all cells read-only.

Anyone??

What I have tried:

Locking cells:
C#
wsht.Cells[rowcnt, colcnt].Locked = true;

Locking range:
C#
wsht.Range[wsht.Cells[rowcnt, 1], wsht.Cells[rowcnt, wordString.Length - 1]].Locked = true;


They won't work and protecting sheet after these codes makes all cells uneditable.
Posted
Updated 6-Apr-16 1:45am

1 solution

Protect the sheet first,
C#
wsht.Protect()

Then unprotect the cells you want to edit.
C#
wsht.Range[wsht.Cells[rowcnt, 1], wsht.Cells[rowcnt, wordString.Length - 1]].Locked = false;
 
Share this answer
 
Comments
planetz 6-Apr-16 7:35am    
My mistake..!! I didn't unlock all the cells first..now it works..!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900