简体   繁体   English

Excel VBA-验证日期和特定的字符串输入

[英]Excel VBA - Validation for Date and specific string inputs

I am looking for a solution to the following problem: 我正在寻找以下问题的解决方案:

I need to add a Validation to a specific range on an Excel sheet. 我需要将验证添加到Excel工作表上的特定范围。 The Validation should allow any date and simple string inputs like "done" or "tbc". 验证应允许任何日期和简单的字符串输入,例如“ done”或“ tbc”。

I know how to add a validation for dates only via VBA but I can't find a way to use two validation types in one cell. 我知道如何仅通过VBA添加日期验证,但找不到在一个单元格中使用两种验证类型的方法。

Is there any solution to my problem? 我的问题有什么解决办法吗?

Many thanks in advance 提前谢谢了

The easiest thing I can thing of is to go to custom validation and to use something like this formula: 我能做的最简单的事情就是去自定义验证,并使用类似下面的公式:

=OR(ISDATE(RANGE),(LEN(RANGE)<5))

You can edit it and record it with the macro recorder... Or give code, as proposed. 您可以对其进行编辑并使用宏记录器进行记录...,或者按建议提供代码。

thanks for the answers so far. 感谢您到目前为止的回答。 I'd prefer a VBA solution. 我更喜欢VBA解决方案。 So I tried to implement the suggestions given by Vityata in VBA and came up with the following. 因此,我尝试在VBA中实施Vityata提出的建议,并提出以下建议。 However, I get runtime error 1004. Any help? 但是,我收到运行时错误1004。有什么帮助吗?

Sub customValidation() 子customValidation()

Dim rngCell As Range


With Tabelle1

    maxCell = .Cells(.Rows.Count, 1).End(xlUp).Row

    For Each rngCell In .Range("L11:O" & maxCell)

        With rngCell.Validation

            .Delete
            .Add Type:=xlValidateCustom, AlertStyle:=xlValidAlertStop, Formula1:="=OR(Isdate(rngCell),rngCell=""done"")"
            .IgnoreBlank = True
            .InCellDropdown = False
            .InputMessage = "Enter date or ""done"""
            .ErrorTitle = ""
            .InputMessage = "Enter date or ""done"""
            .ErrorMessage = ""
            .ShowInput = True
            .ShowError = True
        End With

    Next rngCell
End With

End Sub 结束子

Here is an example which allows dates or 'TBC'. 这是一个允许日期或“ TBC”的示例。 In this case covering a column range (part of a dynamic solution) 在这种情况下,覆盖列范围(动态解决方案的一部分)

Set rng = wksOpenReview.Range(wksOpenReview.Cells
   (display_row, ro.lco_sd), wksOpenReview.Cells(lngLastRow, ro.lco_sd))
With rng.Validation
  .Add xlValidateCustom, AlertStyle:=xlValidAlertStop, Formula1:="=OR(
  NOT(ISERROR(DATEVALUE(TEXT(" & rng.Cells(1, 1)
  .Address(False, True, xlA1) & ",""dd/mmm/yyyy""))))," &
  rng.Cells(1, 1).Address(False, True, xlA1) & "=""TBC"")"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM