我的目标是限制用户只能在 MS Excel 单元格中输入 1 到 100 范围内的值。
我正在以编程方式生成 Excel 文件,但是当我添加上述验证时,异常被抛出为 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);
在上面的代码中,ExcelApp
是Microsoft.Office.Interop.Excel.ApplicationClass
的一个对象
非常感谢任何帮助。
最佳答案
您需要先删除单元格验证器,然后再添加另一个。否则你会看到验证异常被抛出为 Exception from 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);
如果不存在单元格验证器(即第一次),则删除不会导致问题,可以安全地留在其中。
编辑/解决方案:
代码中的问题是变量 arr
包含两项 1 和 100。我猜测 XLFormatConditionOperator 参数 xlBetween
在 Validation.Add
的参数误导了我们。要使其适用于 xlValidateList
的参数 XLDVType,Formula1 参数需要包含所有有效值 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);
}
}
关于c# - 如何使用 C# 在 MS Excel 单元格中添加数字验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13908505/