Excel VBA:更改后验证单元格的值

时间:2012-04-16 17:56:47

标签: vba excel-vba excel-2007 excel

我有一个函数,在用户将一个单元格更改为此值后,将一系列单元格更新为某个值。但是,此范围内的单元格不具有相同的验证范围,因此我希望对每个更新的单元格进行单独验证。

这是我到目前为止所拥有的。对于每个单元格,数据验证设置为其自己的验证范围,并具有可接受的值。由于某种原因,即使数据不在验证范围内,验证仍然适用。我不太确定validation.value属性是如何工作的。

For index = 1 to UBound(someArray)
    wksSomeSheet.Cells(index, column).Value = requiredValue
    If Not wksSomeSheet.Cells(index, column).Validation.Value Then
        MsgBox "A value is not supported for one the cells."
        Exit For
    End If
Next

或者我应该实施它,以便我使用Range("validationRange").find(requiredValue)代替?

1 个答案:

答案 0 :(得分:2)

在查看了Siddharth的博客之后,我对他的代码进行了一些微小的更改,以使其适应我的需求:

Dim currentValidation As Excel.Validation
wksSomeSheet.Cells(index, Target.Column).Value = requiredValue

Set currentValidation = wksSomeSheet.Cells(index, Target.Column).Validation
If currentValidation.Type = xlValidateList Then
    Dim validationFound As Boolean, MyArray As Variant
    validationFound = False
    MyArray = Application.WorksheetFunction.Transpose(Range(Mid(currentValidation.Formula1, 1)))
    For i = 1 To UBound(MyArray)
        If requiredValue = MyArray(i, 1) Then
            validationFound = True
            Exit For
        End If
    Next

    If Not validationFound Then
        MsgBox wksSomeSheet.Cells(index, wksSomeSheet.Range("myRange").Column).Value & " does not have a valid value."
        Exit For
    End If
End If