Setting validation via VBA in excel fails when using variable

后端 未结 6 2071
野趣味
野趣味 2021-01-06 07:56

I am trying to set the data validation for a range of cells using VBA. I get a run-time error 1004 (so helpful) \"Application defined or object defined error\" with this cod

6条回答
  •  清歌不尽
    2021-01-06 08:45

    The problem is almost certainly caused by the context of the named range being different from the current context in Excel.

    When Validation.Add is called, Excel evaluates the formula (which is returning a Range object) in the current context of the application, not the workbook or worksheet. So, if the named range is sheet-based and that sheet is not currently active, it won't work. If the named range exists in one workbook, but a different workbook is active, then it won't work. This is why your workaround of selecting a random cell solves the problem, and also the solution of performing a .Select followed by Selection.Validation.

提交回复
热议问题