【发布时间】: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