【问题标题】:VBA Create a validation based on the first character of the entry into a cellVBA根据输入单元格的第一个字符创建验证
【发布时间】:2014-02-28 20:49:56
【问题描述】:

您好,我正在尝试通过 VBA 在 Excel 中创建单元格验证。我试图通过使用通配符来做到这一点,以便该单元格中的验证将基于数据输入中的第一个字符。

这是我正在使用的代码。

Dim wild1 as string
wild1 = Cells(11, 7) Like "b*"

With Cells(11, 7).Validation
    .Delete
    .Add Type:=xlValidateCustom, AlertStyle:=xlValidAlertStop, Formula1:=wild1
End With

使用上面的代码,每次尝试在 Cell(11, 7) 中输入内容时都会出现验证错误。如果该单元格中数据条目中的第一个字符以 b 开头,我将如何更改它以使数据条目有效?

谢谢!

【问题讨论】:

  • 为什么不只是Formula1:="=LEFT(G11,1)=""b"""
  • 我希望在第一个字符之后包含一个通配符,因为这是它将来自与此电子表格交互的数据库的格式。抱歉,我可能应该早点提到这一点,不过谢谢。
  • 真的不明白你为什么需要通配符,但如果你真的认为你需要它 - 使用Formula1:="=COUNTIF(G11,""b*"")"
  • 谢谢!这更接近我的需要。为了解释更多,在我的真实电子表格中,我不会在我的代码中使用 B*。我有一个基于该工作表上另一个单元格的公式,它将从数据库中提取一个值,因此它不一定总是 b* 它可能是 c* 或 d* 等。在我的代码中,虽然我只是参考那个公式。抱歉,我对 VBA 很陌生。不过,我感谢您的帮助。

标签: vba validation excel wildcard


【解决方案1】:

这是基于simoco的评论............这个事件代码进入工作表代码区域:

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim ch As String
    If Intersect(Target, Cells(11, 7)) Is Nothing Then Exit Sub
    If Target.Count > 1 Then Exit Sub
    ch = Left(Target, 1)
    dq = Chr(34)
    With Target.Validation
        .Delete
        .Add Type:=xlValidateCustom, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=left(A1,1)=" & dq & ch & dq
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
    Application.EnableEvents = False
End Sub

并假设 G7 开始时没有验证。输入值后,将在验证中使用第一个字母。

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多