简体   繁体   English

如何验证细胞的一部分?

[英]How do I validate a portion of a cell?

I need to ensure that a cell starts with a string (one of two, at the moment), followed by a colon and then whatever else (not blank). 我需要确保一个单元格以一个字符串(此时为两个中的一个)开头,然后是冒号,然后是其他任何内容(非空白)。

ie: 即:

IP Address:1.2.3.4
FQDN:a.b.c.d

So, I need to ensure that either of those strings plus ':' starts the cell. 所以,我需要确保这些字符串中的任何一个加上':'来启动单元格。 There could be spacing around the ':'. ':'周围可能有间距。

I'm not sure what you mean by "ensure"... 我不确定你的意思是“确保”......

This will check the cell to see if it has either of the two starting values in an Excel function: 这将检查单元格以查看它是否具有Excel函数中的两个起始值中的任何一个:

=IF(OR(LEFT(A1,5)="FQDN:",LEFT(A1,11)="IP Address:"),TRUE,FALSE)

That doesn't take into account spacing around the colon though. 但这并没有考虑到结肠周围的间距。 For that, it's Regular Expressions, which I am not very good with. 为此,它是正则表达式,我不是很好。

-- Take the code from Tushar Mehta's site: http://www.tmehta.com/regexp/add_code.htm - 从Tushar Mehta的网站获取代码: http ://www.tmehta.com/regexp/add_code.htm

Then, use an Excel function like this: 然后,使用这样的Excel函数:

=regexpfind(A1,"^FQDN\s*:\s*")
=regexpfind(A1,"^IP Address\s*:\s*")

or you could merge these into a single formula like this: 或者您可以将这些合并为一个公式,如下所示:

=regexpfind(A1,"^(FQDN|IP Address)\s*:\s*")

If your cell is A4, then try this in Data/Validation.. Custom formula: 如果您的单元格是A4,请在数据/验证中尝试此操作。自定义公式:

=((COUNTIF(A4,"fqdn*")+COUNTIF(A4,"ip address*"))*COUNTIF(A4,"*:*")>0)  

NB this is not case-sensitive. 注意,这不区分大小写。

This might be the simplest way to do it. 这可能是最简单的方法。 Assuming you are checking the value in cell A1: 假设您正在检查单元格A1中的值:

=IF(ISERR(FIND(":",A1)),"Bad!",IF(FIND(":",A1)<>LEN(A1), "OK", "Bad!"))

First, this formula checks that the cell A1 has a colon. 首先,该公式检查单元格A1是否有冒号。 If it doesn't, it is a bad cell. 如果没有,那就是坏细胞。 If it does, it checks that the colon is not the last character. 如果是,则检查冒号不是最后一个字符。 If it is the last character, there is no text after the colon, so it is a bad cell. 如果它是最后一个字符,冒号后面没有文字,所以它是一个坏单元格。 If there is text after the colon, it is a good cell. 如果冒号后面有文字,那就是一个好的细胞。 Hope this helps! 希望这可以帮助!

--Edit-- - 编辑 -

To check that the colon is not the first character, this is the formula: 要检查冒号不是第一个字符,这是公式:

=IF(ISERR(FIND(":",A1)),"Bad!",IF(OR(FIND(":",A1)=LEN(A1), FIND(":",A1) = 1), "Bad!", "OK"))"Bad!"))

With this formula, you have to have a string before the colon. 使用此公式,您必须在冒号之前有一个字符串。 But if you only need to check for the two strings, it's probably better to check for them explicitly. 但是如果你只需要检查两个字符串,最好明确地检查它们。

Here's one more solution (assuming string is in A1 ): 这是另一个解决方案(假设字符串在A1 ):

=IFERROR(IF(AND(SEARCH(":",A1)>1,SEARCH(":",A1)<LEN(TRIM(A1))),"GOOD","BAD"),"BAD")

This will handle: 这将处理:

  1. followed by a colon and then whatever else ( not blank ). 然后是冒号,然后是其他任何东西( 不是空白 )。
  2. There could be spacing around the ':'. ':'周围可能有间距

Sample file is shared (with different options): https://www.dropbox.com/s/5rxzyzgkg8biffg/StringWithColon.xlsx 示例文件是共享的(使用不同的选项): https//www.dropbox.com/s/5rxzyzgkg8biffg/StringWithColon.xlsx

If you really want to ensure that no one can enter anything else in the cells you're talking about, you can use a custom Data Validation formula. 如果您确实希望确保没有人可以在您正在讨论的单元格中输入任何其他内容,则可以使用自定义数据验证公式。 Here's a step-by-step: 这是一步一步:

  1. Highlight the first cell of the column you want to validate 突出显示要验证的列的第一个单元格
  2. On the ribbon, click on Data, then, under Data Tools heading, click Data Validation. 在功能区上,单击“数据”,然后在“数据工具”标题下,单击“数据验证”。
  3. The Data Validation window should be open. 数据验证窗口应该是打开的。 Click on the settings tab (it should be selected by default, actually) 单击设置选项卡(实际上应默认选中)
  4. In the "Allow" drop-down menu, click Custom. 在“允许”下拉菜单中,单击“自定义”。
  5. In the "formula" box, copy this formula: 在“公式”框中,复制此公式:

     =IF(NOT(ISERR(FIND(":",A1))), AND(FIND(":",A1)<>LEN(A1),FIND(":",A1) <> 1), FALSE) 

Substitute A1 for whatever cell you need. 将A1替换为您需要的任何细胞。 This is the same formula as in my other answer; 这与我的另一个答案中的公式相同; it checks only that there is text, then a colon, them more text (in that order), not for specific strings. 它仅检查是否有文本,然后是冒号,它们是更多文本(按此顺序),而不是特定字符串。 To explicitly check for the strings "IP Address" and "FQDN", substitute someone else's formula for this one in the data validation dialog. 要显式检查字符串“IP Address”和“FQDN”,请在数据验证对话框中替换其他人的公式。

If you want a VBA solution here is a function you can use either as a UDF or from VBA 如果您希望VBA解决方案是一个函数,您可以将其用作UDF或VBA

Option Explicit
Option Base 1
Function CorrectColonPlace(StringtoCheck As String, StartStrings As Variant) As Variant
    Dim iPos As Long
    Dim j As Long
    Dim StrStart As String
    '
    ' return 0 if stringtocheck fails, else the position of the colon
    CorrectColonPlace = 0
    On Error GoTo FuncFail
    iPos = InStr(StringtoCheck, ":")
    If iPos > 1 Then
        If iPos < Len(Trim(StringtoCheck)) Then
        '' assume that StartStrings is either a Range or a 2-dimension single-column array
        '' containing the strings to be found at the start of stringtocheck
            If IsObject(StartStrings) Then StartStrings = StartStrings.Value2
            StrStart = Trim(Left(StringtoCheck, iPos - 1))
            For j = 1 To UBound(StartStrings)
                If StrStart = Trim(StartStrings(j, 1)) Then
                    CorrectColonPlace = iPos
                    Exit For
                End If
            Next j
        End If
    End If
FuncFail:
End Function

So, the regex approach given as one of the answers formed the basis for my solution. 因此,作为答案之一给出的正则表达式方法构成了我的解决方案的基础。 I copied the code from the supplied link and pasted to another module. 我从提供的链接复制代码并粘贴到另一个模块。 I then created a little wrapper for RegExpFind that basically ran the match and returned a true or false if the pattern was successful or not. 然后我为RegExpFind创建了一个小包装器,它基本上运行了匹配,如果模式成功与否则返回true或false。

Function RegExpTest(FindIn, FindWhat As String, _
        Optional IgnoreCase As Boolean = False)

    Dim n As Long
    Dim resultsArray As Variant     ' Defined as single variant for the benefit of excel 97
    Dim result As Boolean

    ' Don't break on errors.  Easier to check if Err<>0
    On Error Resume Next
    Err.Clear

    result = False
    resultsArray = RegExpFind(FindIn, FindWhat, IgnoreCase)

    ' Check if the returned data is an array before proceeding.
    If IsArray(resultsArray) = True Then
        n = UBound(resultsArray)

        If Err.Number = 0 Then
            If LBound(resultsArray) <= UBound(resultsArray) Then
                result = True
            End If
        End If
    End If

    RegExpTest = result

End Function

Now, I cannot use that directly in a custom validation so, given that my worksheets are generated on the fly from metadata (nothing is created beforehand), I ended up following the second suggestion given here . 现在,我不能直接在自定义验证中使用它,因此,考虑到我的工作表是从元数据中动态生成的(事先没有创建),我最后遵循这里给出的第二个建议。

How I did that, was to have the following VBA code (excerpted from the method I have to create my data validation rules): 我是如何做到的,是拥有以下VBA代码(摘自我必须创建数据验证规则的方法):

Range(Cells(firstIndex, validationFormulaCellRef), Cells(lastIndex, validationFormulaCellRef)).Formula = _
    "=RegExpTest(INDIRECT(""D""&ROW()), ""^(FQDN|IP Address)\s*:\s*([\w\d\.]+)$"", TRUE)"

Dim validationFormula As String
validationFormula = "=" & validationFormulaCellName & firstIndex & "=TRUE"

' Now, setup custom validation to check that the referenced cell's value is True
With fieldRange.Validation
    .Delete
    .add Type:=xlValidateCustom, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, _
     Formula1:=validationFormula
    .IgnoreBlank = False
    .InCellDropdown = False
    .InputTitle = ""
    .ErrorTitle = "Input Error"
    .InputMessage = "This field must start with either 'FQDN' or 'IP Address', plus a colon ':'."
    .ErrorMessage = "This field must start with either 'FQDN' or 'IP Address', plus a colon ':'."
    .ShowInput = True
    .ShowError = True
End With

I stick the formula (that actually does the work) into an unused cell (EV [validationFormulaCellName] = 152 [validationFormulaCellRef], far along the row, then set the data cell's custom validation to check if the forumula cell's value is True. The firstIndex value is the number of the first row I'm inserting, so I end up with a validation formula that looks like "=EV10=TRUE". I use the INDIRECT(..) syntax in the validation formula soas to generate a cell reference for that particular row, since a fixed (ie: EV10) cell ref would not be automatically adjusted for each row (all would reference EV10). On the contrary, the validation formula is fixed (ie: =EV10=TRUE) but is adjusted for each row when inserted. I don't understand why those behaviours differ. 我将公式(实际上是完成工作)粘贴到一个未使用的单元格中(EV [validationFormulaCellName] = 152 [validationFormulaCellRef],沿着该行,然后设置数据单元的自定义验证以检查forumula单元格的值是否为True。 value是我插入的第一行的编号,所以我最终得到一个看起来像“= EV10 = TRUE”的验证公式。我在验证公式中使用INDIRECT(..)语法来生成一个单元格引用对于该特定行,因为固定(即:EV10)单元格ref不会针对每一行自动调整(所有都将参考EV10)。相反,验证公式是固定的(即:= EV10 = TRUE)但是调整插入时每行。我不明白为什么这些行为不同。

In the future, it would make sense to stick the values I need to verify (FQDN and IP Address) into a hidden worksheet we have that stores various bits of data - enums and the like. 在将来,将我需要验证的值(FQDN和IP地址)粘贴到我们拥有的存储各种数据位的隐藏工作表(枚举等)中是有意义的。 That way, it can be programatically built up from a list and not hardcoded. 这样,它可以从列表中以编程方式构建,而不是硬编码。

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

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