【问题标题】:Excel VBA macro: how do I find cells with list validationExcel VBA 宏:如何找到具有列表验证的单元格
【发布时间】:2017-05-22 15:39:48
【问题描述】:

我想要一个宏来清除工作表上给定范围内的所有单元格,除非它具有(特别是)LIST 验证。 (在这种情况下,我想让它 = 'Select'。)

所以...我需要宏来:

1) 检查工作表范围内的所有单元格 2)如果单元格没有(特别是)LIST 验证,它将使单元格 = "" 3)如果单元格确实有(特别)LIST 验证,它将使单元格 = 'Select'

类似这样的:

Dim x as variant

with thisworkbook.sheets("audits") 
For each x in .range("A6:AZ200")
    if x.validationtype = "list" then
    x.value = "Select"
    else
    x.value = ""
    end if
next x
end with

谢谢!

【问题讨论】:

  • 乔有什么问题?您是否在让某些代码工作时遇到问题(在这种情况下,发布代码并告诉我们发生了什么)或尝试一些 Google-Fu,因为我确信某处有人构建了类似的东西。如果您需要帮助让 那个 工作,请告诉我们。
  • 嗨,@CLR - 在 google-fu,特别是 stackoverflow-fu 之后,我才发布问题。我会更新我的问题,但不知道如何让它更清楚。

标签: excel vba


【解决方案1】:

您可能可以使用范围对象的SpecialCells 属性仅返回具有 验证的单元格,然后再进行一次检查以确保验证类型为列表。

Dim rng As Range
Dim vRng As Range
Dim cl As Range

Set rng = thisworkbook.sheets("audits").Range("A6:AZ200") 'Modify as needed

'Get a range of ONLY the validation cells
Set vRng = rng.SpecialCells(xlCellTypeAllValidation)


For Each cl In rng
    'If the cell has NO VALIDATION:
    If Intersect(cl, vRng) Is Nothing Then
        cl.ClearContents
    ElseIf cl.Validation.Type = 3 Then  'xlValidateList
        cl.Value = "Select"
    End If
Next

注意: 3 is the xlDVType constant for "List" validation。您也可以使用常量表达式:xlValidateList

上面应该处理混合验证类型,并且不会对任何其他类型的验证做任何事情。如果可以安全地假设仅使用列表验证,则尝试将其压缩为:

Set vRng = rng.SpecialCells(xlCellTypeAllValidation)
vRng.Value = "Select"

For Each cl In rng
    'If the cell has NO VALIDATION:
    If Intersect(cl, vRng) Is Nothing Then
        cl.ClearContents
    End If
Next

【讨论】:

  • 这也很好用并且更直接(无需调用函数)。有多种类型的验证,我为什么需要专门缩小范围。非常感谢!
【解决方案2】:

这将是一种方法。为了使错误处理远离您的主程序,我将验证检查器放入一个独立的函数中:

Sub clear_validation()

Dim x As Range

With ThisWorkbook.Sheets("audits")
    For Each x In .Range("A6:AZ200")
        If validationtype(x) = 3 Then
            x.Value = "Select"
        Else
            x.Value = ""
        End If
    Next x
End With

End Sub

Function validationtype(cl As Range)
    Dim t As Integer
    t = 0
    On Error Resume Next
        t = cl.Validation.Type
    On Error GoTo 0
    validationtype = t
End Function

它是闪烁的,所以你可能想暂时关闭屏幕更新,也许在它运行时关闭计算,但我认为这可以满足你的需求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多