Link to home
Start Free TrialLog in
Avatar of zachvaldez
zachvaldezFlag for United States of America

asked on

Unlocking a column in excel using C#

I have the Microsoft .Office.Interop.Excel installed but my question is
I want to unlock a column H. I do have data to reach H1..H500  but it could be less rows.
I want to unlock only until the last row with data. It should not affect more than the last row with data.
whats the code?
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

try the following:
Excel.Range all = app.get_Range("H:H", Type.Missing);
all.Locked = false;

Open in new window

Avatar of zachvaldez


I want to put gridlines in the column. Right now column is solid white with no gridlines. like the column look normal .
what is the code to do that in addition to above. THANKS!!!
Avatar of Rgonzo1971


pls try
        xlRange = (Excel.Range)xlWorkSheet.get_Range(xlWorkSheet.Cells[1, 8] as Excel.Range, (xlWorkSheet.Cells[xlWorkSheet.Cells.Rows.Count, 8] as Excel.Range).get_End(Excel.XlDirection.xlUp));

        xlRange.Locked = false;
        xlRange.Cells.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuou

Open in new window

Kyle's code changes the whole column

Can Usedrange substitute on this or not? Does usedrange cover only to the last row of data or till the 65,000+
Last row?
It depends on the data and usedrange is not very reliable
What if I want to change background color of "J1"? How to reference the cell?
then try
Excel.Range xlRange= (Excel.Range) xlWorkSheet.Cells[1, 8];
xlRange.Interior.Color = Excel.XlRgbColor.rgbYellow;

Open in new window

Is column J 10?
then try
Excel.Range xlRange= (Excel.Range) xlWorkSheet.Cells[1, 10];
xlRange.Interior.Color = Excel.XlRgbColor.rgbYellow;
It's not changing the color. Originally it was yellow on J1. Can the formatting start on J2 ..down instead because J1 is a header with background yellow?
Avatar of Rgonzo1971

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
is  "as" a C# keyword? just asking
this code:
range = xlsWorkSheet.UsedRange.Columns[10, Type.Missing]; covers whole column including header. Can you modify this to start at J2 instead because J1 is header and has the original yellow background.
Maybe this is easier to understand for me.
range = xlsWorkSheet.UsedRange.Columns[10, Type.Missing].Resize(xlsWorkSheet.UsedRange.Rows -1 , 1).Offset(1); 

Open in new window

Excel.Range range4 = xlsWorkSheet.UsedRange.Columns[10, Type.Missing].Resize(xlsWorkSheet.UsedRange.Rows - 1, 1).Offset(1);

>>after the Resize, I have red underline on (xlsWorkSheet.UsedRange.Rows

getting this message ..(operator '-' cannot be applied to operands...)
replace with