数据验证器VBA excel-将一个单元格中字符串中的值与另一个单元格中的值进行比较

时间:2014-05-15 21:22:34

标签: date excel-vba vba excel

无法找到符合我需求的任何内容。

我有两列值(L和U)。列L包含一个文件名,其中包含MM-DD-YYYY格式的日期(例如yadayadayada thru(03-15-2015).pdf)列U包含日期。我需要做的是让宏将文件名中的日期与U列中的日期进行比较。其他日期可能会出现在L列的文本中,但我需要比较的日期总是在" thru&之后#34;并在括号中后跟文件扩展名。如果它们不匹配,我需要突出显示U列中的值并替换为文本" FAIL"。我将继续搜索,但非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

它必须是VBA吗?这可以通过条件格式来完成。 将此条件格式公式应用于列U:

=AND(U1<>"",L1<>"",U1<>--TRIM(MID(SUBSTITUTE(TRIM(RIGHT(SUBSTITUTE(L1," ",REPT(" ",255)),255)),")",REPT(" ",255)),2,255)))

并使用黄色(或您选择的高亮颜色)填充将数字格式设置为自定义"FAIL"

修改

如果它必须是VBA,那么这应该适合你:

Sub tgr()

    Const HeaderRow As Long = 1 'Change to your actual header row

    Dim ws As Worksheet
    Dim rngFail As Range
    Dim rngFiles As Range
    Dim FileCell As Range
    Dim dDate As Double

    Set ws = ActiveWorkbook.ActiveSheet
    Set rngFiles = ws.Range("L" & HeaderRow + 1, ws.Cells(Rows.Count, "L").End(xlUp))
    If rngFiles.Row < HeaderRow + 1 Then Exit Sub 'No data

    For Each FileCell In rngFiles.Cells
        If Len(Trim(FileCell.Text)) > 0 Then
            dDate = 0
            On Error Resume Next
            dDate = CDbl(CDate(Trim(Mid(Replace(Trim(Right(Replace(FileCell.Text, " ", String(255, " ")), 255)), ")", String(255, " ")), 2, 255))))
            On Error GoTo 0
            If dDate <> ws.Cells(FileCell.Row, "U").Value2 Then
                Select Case (rngFail Is Nothing)
                    Case True:  Set rngFail = ws.Cells(FileCell.Row, "U")
                    Case Else:  Set rngFail = Union(rngFail, ws.Cells(FileCell.Row, "U"))
                End Select
            End If
        End If
    Next FileCell

    If Not rngFail Is Nothing Then
        rngFail.Value = "FAIL"
        rngFail.Interior.ColorIndex = 6
    End If

End Sub