views:

458

answers:

2

Hi there, im trying to manipulate excel file XLS with C# by using Microsoft.Office.Interop.Excel

the workbook im trying to manipulate has shared protection between users

i have the file pw and i have the pw of the cells which i want to access and edit.

if i try to do that from excel i do the following open the file type the pw

go to a cell double click on a cell to edit a dialogue apear asking me to provide pw i provide the pw and then i can edit

i exactly wanna do that from code

my code is as follow :

    xl.Application excelApp = new xl.Application();
        excelApp.Visible = true;
        xl.Workbook newworkbook = excelApp.Workbooks.Open(@"C:\1.xls",
        0, false, 5, "password", "", false, xl.XlPlatform.xlWindows, "",
        true, false, 0, true, false, false);
        xl.Sheets excelSheets = newworkbook.Worksheets;
        xl.Worksheet excelWorksheet = (xl.Worksheet)excelSheets.get_Item("Sign On_Off");
        excelWorksheet.Select(true);
        xl.Range myrange = excelWorksheet.get_Range("b16", "b16");
        myrange.Value2 = "testing"; 

the last line gives me this : The cell or chart that you are trying to change is protected and therefore read-only.

i cant unprotect the sheet cause that would mean i will have the file exclusive opened for me only and other users cant save changes

so my question is is there is way i can unprotect a cell only ? something like

myrange.unprotect("pw"); ?????!!!

thanks in advance

A: 

Protect is just available to Workbook and Worksheet classes.

Alternatively, you can try to work with Worksheet.Protection Property:

ActiveSheet.Protection.AllowEditRanges.Add _
    Title:="Range123", Range:=Range("K4:L10"), Password:="123"
Rubens Farias
thanks , but how do i edit a cell without unprotecting the whole shared workbook i mean with excel i simply click on the cell and type my pw for this cell, and then its editable, every user have different pws for different cells, i should be able to do that without haveing the pw for the protected shared workbook, since i can do it from excel
Stacker
thank you so much , here is what i have tried :excelWorksheet.Activate();xl.Range myrange = excelWorksheet.get_Range("b16", "b16"); excelWorksheet.Protection.AllowEditRanges.Add("Title", myrange, "1"); it generate an error : Exception from HRESULT: 0x800A03EC
Stacker
Sorry, but I don't know to here go from there =(
Rubens Farias
+1  A: 

I haven't had time to try it, but this paragraph looks like what you are looking for. It seems that the VBA equivalent object you are looking for is ActiveSheet.Protection.AllowEditRanges, which stores information about the areas that can be edited by users in a sheet.
One thing you might want to look into as well is the UserInterfaceOnly option on ActiveSheet.Protect. You can protect a range with a password for users, but access it without password through macros.

Mathias