【问题标题】:Range Validator in Excel with custom message textExcel 中的范围验证器,带有自定义消息文本
【发布时间】:2012-09-21 02:11:31
【问题描述】:

我有以下代码可以使用自定义文本对 Excel 单元格进行验证。

var cellValues = activeSheet.Range[columnLetterValue + startingRow, Type.Missing];
cellValues.Validation.Add(XlDVType.xlValidateCustom, XlDVAlertStyle.xlValidAlertInformation, XlFormatConditionOperator.xlBetween, cellValues.Value2, Type.Missing);
cellValues.Validation.IgnoreBlank = true;
cellValues.Validation.ErrorTitle = "Custom error title";
cellValues.Validation.ErrorMessage = "Custom error message description";
cellValues.Validation.ShowError = true;
cellValues.Validation.ShowInput = false;

在调试设置 ErrorTitle 或 ErrorMessage 的行时,会抛出 'System.Runtime.InteropServices.COMException'

堆栈跟踪:

{System.Runtime.InteropServices.COMException (0x800A03EC):异常 从 HRESULT:0x800A03EC 在
System.RuntimeType.ForwardCallToInvokeMember(字符串成员名称, BindingFlags 标志、对象目标、Int32[] aWrapperTypes、MessageData& msgData) 在
Microsoft.Office.Interop.Excel.Validation.set_ErrorTitle(String )

我在网上查了几个例子,证明这是可能的: Range Validation with Excel using C#

我什至在 Excel 中录制了一个宏,它可以与“VBA”等效代码一起使用:

    ActiveCell.FormulaR1C1 = "Custom"
    Range("A1").Select
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateCustom, AlertStyle:=xlValidAlertInformation, _
        Operator:=xlBetween, Formula1:="Custom"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = "UDF Title"
        .InputMessage = ""
        .ErrorMessage = "The message"
        .ShowInput = False
        .ShowError = True
    End With
End Sub 

我也尝试了 XlDVType 和 XlFormatConditionOperator 的不同组合,但这似乎对设置自定义消息框文本没有任何影响。

有人知道如何使用自定义 ErrorTitle 和 ErrorMessage 设置验证规则吗?

【问题讨论】:

  • 这适用于我在 C# 2010 和 Excel 2010 中。我可以如上所示运行您的代码,唯一的区别是我将 CellValues 设置为 ExcelApp.ActiveSheet.Range["A1"]。它添加了自定义消息。我可以做一些事情使它在长 Validation.Add 行上失败,比如在 A1 中有一个空白,但不能让它在错误消息或错误标题行上失败。请注意,当您运行它时,您可能应该包含 Validation.Delete 行,否则如果您尝试第二次设置它,您会遇到运行时错误。

标签: c# excel validation vsto customization


【解决方案1】:

问题是由于将Validation.ErrorTitle 设置为没有验证规则的范围。

【讨论】:

  • 请注意,您可能知道,如果示例代码准确地反映了您的实际代码,那就太好了。否则,尝试调试(我做了很长一段时间)可能会浪费时间。在您的示例代码Validation.ErrorTitle 中,生成错误的行设置为“自定义错误标题”,而不是范围。
  • 抱歉道格,是我把它剥光了,只见树木不见森林
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-04
相关资源
最近更新 更多