views:

317

answers:

2

Hello,

I generate some Excel file with Microsoft Interop, no problem, I can create files, sheet, file, password protect. But I'd like :

  • for a specific range allow only numbers
  • for an another specific range allow only numbers but only 0 or 1

Do you have an idea how to do this ?

Thanks,

A: 

If you want to validate an entry into the Cell, look at the Validation.Add method.

MSDN Example

Your second one is something like:

aRange.Validation.Add(XlDVType.xlValidateWholeNumber, XlDVAlertStyle.xlValidAlertStop, XlFormatConditionOperator.xlBetween, 0, 1);
Mark
+1  A: 

Hi, took a while but I think I got it. I am assuming you're using Excel 2007. I am also assuming you have a reference to a range already. Here is a quick example.

Excel.Worksheet sheet = this.Application.ActiveSheet as Excel.Worksheet;
Excel.Range range = sheet.get_Range("A1", "A5") as Excel.Range;

 //delete previous validation rules 
 range.Validation.Delete();
 range.Validation.Add(Excel.XlDVType.xlValidateWholeNumber,
                                 Excel.XlDVAlertStyle.xlValidAlertStop,
                                 Excel.XlFormatConditionOperator.xlBetween,
                                 0, 1);

This will add a validation of number between 0 and 1 for a specific range in this case between A1 and A5.

You can also play with the Validation object further to create custom Error Messages etc.

Hope this helps.

Stan R.
I'll try this. But I use interop for Office 2002, it's the "standard" for my customer
Kris-I
@Kris, this should work either way. Let me know if it doesn't and i'll see if i can get 2002 to work.
Stan R.
I tried it with Visual Studio 2005 and Excel 2003, it works. One thing I can't get is how to NOT pass the optional parameters. According to the docs you use Type.Missing but this while this compiles it results in "Exception from HRESULT: 0x800A03EC".
Mark
@Mark, try Missing.Value
Stan R.
Thanks Stan, that's work fine with Interop for Office 2002
Kris-I