Excel / Google表格 - 如果单元格" X"则禁用行的数据验证。包含特定值

时间:2017-09-11 14:59:44

标签: excel excel-vba google-apps-script google-sheets spreadsheet vba

例如。通常会对工作表中的B列激活数据验证,这会阻止任何人使用" /"那么,是否有可能,如果单元格F5包含单词" Apples"然后对第5行停用数据验证,用户可以输入他们喜欢的任何信息" /" s和all。谢谢。

1 个答案:

答案 0 :(得分:0)

以下是您可以在Excel环境中使用的一些代码(不在Google表格中)

定义两个范围。如果应该应用数据验证, TIMESTAMP | ACTOR| CONTEXT| MESSAGE | CLASSIFICATION -----------------+------+--------+------------+----------- 01.02.2015 10:19 | user | text | hi bot! | opening 01.02.2015 10:20 | bot | text | blablabla | normal 01.02.2015 10:21 | user | text | blablabla | normal 01.02.2015 10:22 | bot | text | blablabla | normal 01.02.2015 10:23 | user | text | ok bye bot | closing 应评估为rng_test,如果不应用验证,则1评估为0。任何时候更新数据集都应该运行validate_this。或者,只要有人更新您认为应该触发数据验证规则更新的某些单元格,您就可以使用Private Target ByVal宏来运行此宏。 (有关详情,请参阅:http://www.ozgrid.com/VBA/run-macros-change.htm

Sub validate_this()

Dim i As Integer
Dim rws As Integer
Dim c As Range
Dim ws As Worksheet
Dim rng_test As Range, rng_validate As Range

Set ws = ThisWorkbook.Worksheets("Sheet1")
Set rng_test = ws.Range("C4:C7")
Set rng_validate = ws.Range("D4:D7")

rws = rng_test.Count

For i = 1 To rws
    rng_validate(i).Validation.Delete 'delete all old validations'
    If rng_test(i) = 1 Then
        validate (rng_validate(i))
    End If
Next i
End Sub

以下子控件实际数据验证。我写了valFormula来拒绝任何包含斜杠的单元格。您可以更新此变量以设置您想要的任何规则。

Sub validate(rng As Range)

Dim rng_address As String
Dim valFormula As String

rng_address = rng.Address

valFormula = "=IFERROR(NOT(IF(FIND(" & Chr(34) & "/" & Chr(34) & "," & rng_address & ")>-1,1,0)),1)"

With rng.Validation
    .Delete 'delete previous validation. not necessary since we did this above but can be good to keep for good measure'
    .Add Type:=xlValidateCustom, AlertStyle:=xlValidAlertStop, _
       Formula1:=valFormula
End With

End Sub

我的屏幕: enter image description here