首页 > 解决方案 > 将列中所有数据验证单元格的地址添加到数组中

问题描述

我有一个工作表更改事件宏,因此只要数据验证单元格的值为“”(删除键击等),它就会粘贴到字符串“单击以输入值”中。下面的代码,它工作正常。

在不同的工作表上,我需要相同的功能,但应用于多个数据验证单元格,全部在一个列中,尽管非常分散。因此,我的 VBA 需要更改更改事件宏,以便现在仅在这些验证单元格中查找更改。

最初的想法是将所有数据验证单元格地址放入一个数组中,以便宏在每次更改时循环遍历,检查空白值。这是最有效的方法吗?如果是这样,我需要语法方面的帮助。假设单元格都在 C 列中...

这是第一张表中的一个单元格宏。感谢您的任何指导。:

Private Sub Worksheet_Change(ByVal Target As Range)
  If Range("B2").Value = "" Then
     Range("B2").Value = "Click to Enter"
  End If
End Sub

标签: arraysexcelvba

解决方案


SpecialCells方法具有 xlCellTypeAllValidation 。

Private Sub Worksheet_Change(ByVal Target As Range)
  on error goto safe_exit
  If not intersect(target, target.parent.Cells.specialcells(xlCellTypeAllValidation)) is nothing then
     application.enableevents = false
     dim t as range
     for each t in intersect(target, target.parent.Cells.specialcells(xlCellTypeAllValidation))
         if not cbool(len(t.value)) then _
             t.Value = "Click to Enter"
     next t
  End If
safe_exit:
    application.enableevents = true
End Sub

推荐阅读