lov*_*nce 9 .net c# validation excel
我的目标是限制用户在MS Excel单元格中仅输入介于1到100之间的值.
我以编程方式生成Excel文件,但是当我添加上面的验证时,Exception被抛出 Exception from HRESULT: 0x800A03EC
我写的代码如下:
int[] arr = {1,100};
ExcelApp.get_Range(col1, col2).Cells.Validation.Add(Microsoft.Office.Interop.Excel.XlDVType.xlValidateList, Microsoft.Office.Interop.Excel.XlDVAlertStyle.xlValidAlertInformation, Microsoft.Office.Interop.Excel.XlFormatConditionOperator.xlBetween, arr, Type.Missing);
Run Code Online (Sandbox Code Playgroud)
在上面的代码ExcelApp
是一个对象Microsoft.Office.Interop.Excel.ApplicationClass
任何帮助都非常感谢.
您需要在添加另一个之前删除单元格验证程序.否则,您将看到验证异常从HRESULT抛出为异常:0x800A03EC
ExcelApp.get_Range("A1").Cells.Validation.Delete();
ExcelApp.get_Range("A1").Cells.Validation.Add(Microsoft.Office.Interop.Excel.XlDVType.xlValidateList, Microsoft.Office.Interop.Excel.XlDVAlertStyle.xlValidAlertInformation, Microsoft.Office.Interop.Excel.XlFormatConditionOperator.xlBetween, delimitedString1To100, Type.Missing);
Run Code Online (Sandbox Code Playgroud)
如果不存在单元验证器(即第一次),则删除不会导致问题,可以安全地离开.
在代码的问题是变量arr
包含两个项目1 100我猜XLFormatConditionOperator参数xlBetween
中Validation.Add
的参数误导我们.为了使它成为争论工作XLDVType的xlValidateList
的一级方程式参数需要包含所有有效值1,2,3 ... 100:
var val = new Random();
var delimitedString1To100 = string.Join(",", (int[])Enumerable.Range(1, 100).ToArray());
for (int i = 1; i < 11; i++)
{
using (var rnCells = xlApp.Range["A" + i.ToString()].WithComCleanup())
{
rnCells.Resource.Value2 = val.Next(100);
rnCells.Resource.Cells.Validation.Delete();
rnCells.Resource.Cells.Validation.Add(
Microsoft.Office.Interop.Excel.XlDVType.xlValidateList,
Microsoft.Office.Interop.Excel.XlDVAlertStyle.xlValidAlertInformation,
Microsoft.Office.Interop.Excel.XlFormatConditionOperator.xlBetween, delimitedString1To100, Type.Missing);
}
}
Run Code Online (Sandbox Code Playgroud)
我认为您不能传入 .NET 整数数组。您需要传入一个以逗号分隔的字符串,或对工作表范围的字符串引用。来自文档:
xlValidateList -需要Formula1 ;Formula2被忽略。Formula1必须包含以逗号分隔的值列表或对此列表的工作表引用。
例如:
ExcelApp.get_Range(col1, col2).Cells.Validation.Add(
XlDVType.xlValidateList,
XlDVAlertStyle.xlValidAlertInformation,
XlFormatConditionOperator.xlBetween,
"1,100"
);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6751 次 |
最近记录: |