Jeremy Thompson
Jeremy Thompson

Reputation: 65672

Range Validator in Excel with custom message text

I have the following code to give a Excel cell Validation with custom text.

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;

When debugging the line to set the ErrorTitle or ErrorMessage a 'System.Runtime.InteropServices.COMException' is thrown.

Stacktrace:

{System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC at
System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData) at
Microsoft.Office.Interop.Excel.Validation.set_ErrorTitle(String )

I have looked online and found a couple of examples that show this is possible: Range Validation with Excel using C#

I've even recorded a Macro in Excel and it works with the "VBA" equivilent code:

    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 

I've also tried different combinations of XlDVType and XlFormatConditionOperator but that didn't seem to make any difference in setting the custom messagebox text.

Does anyone know how to set a Validation rule with custom ErrorTitle and ErrorMessage?

Upvotes: 0

Views: 2623

Answers (1)

Jeremy Thompson
Jeremy Thompson

Reputation: 65672

The problem was due to setting a Validation.ErrorTitle to a range that didn't have a Validation rule.

Upvotes: 1

Related Questions