【问题标题】:Data validator VBA excel- compare a value within a string in one cell to a value in another数据验证器VBA excel-将一个单元格中的字符串中的值与另一个单元格中的值进行比较
【发布时间】:2014-05-15 21:22:34
【问题描述】:

找不到适合我需要的东西。

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

【问题讨论】:

    标签: date excel vba


    【解决方案1】:

    必须是 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
    

    【讨论】:

    • 这在技术上确实做了我想要的,但是它实际上并没有替换存储在 U 列中的值,只是重新格式化它。如果实际值未更改,则此工作表仍可能上传不正确的数据。如果文本从日期以外的其他内容更改,则将无法上传。
    • U 列或 L 列中是否有空白单元格?
    • 是的,但是如果L中有值,U中一定有值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多