c# - 如何使用 C# 在 MS Excel 单元格中添加数字验证

标签 c# .net excel validation

我的目标是限制用户只能在 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);

在上面的代码中,ExcelAppMicrosoft.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 参数 xlBetweenValidation.Add 的参数误导了我们。要使其适用于 xlValidateList 的参数 XLDVTypeFormula1 参数需要包含所有有效值 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/

相关文章:

c# - 如何控制面板内文本框的焦点顺序?

excel - VBA 舍入值

Excel 文本格式数字四舍五入到百万

c# - 通用类型推断不适用于动态?

C# SocketAsyncEventArgs 不发送所有数据

c# - 哪个命名空间保存有关 SQL Server TinyInt 数据类型的信息?

.net - Reactive Extensions 中的 BufferWithTime 会重叠调用 OnNext 吗?

c# 如何创建动态列表/数组

c# - 如何从证书库中获取X509Certificate并生成xml签名数据?

vba - Excel 宏平均值