比较 2 张 vba 中的日期

Compare Dates in 2 sheets vba

提问人:Amy 提问时间:11/16/2023 最后编辑:ZygDAmy 更新时间:11/16/2023 访问量:50

问:

我有 2 个名为“控制”和“组合”的工作表。在控制表 M5 = YYYY-MM-DD
在组合表中,我有一个名为 SD 的列,其中有日期。我想检查控件 M5 中的日期是否 = 组合 SD 列中的所有日期(理想情况下应该是),如果没有抛出一个消息框说日期不匹配 我有代码,但即使日期匹配,它仍然会抛出不匹配的错误 还有谁能帮我用 2 个星号来帮我用红色的线

我的代码:

    Dim ws as Worksheet
    Dim sDate, c as Range
    Dim bMatch as Boolean, sMsg as String

    Const START_ROW = 2
    sDate = Sheets("Control").Range("m5").Value
    For Each ws in ActiveWorkbook.Worksheets
        If ws.Name <> "Control" Then
            bMatch = True
            With ws
                **For each c in .Range**
                    If not c.value = sDate Then
                        bMatch = False
                        Exit For
                    End If
                Next
                If bMatch Then
                    Call Macro9
                Else
                    smsg = "Date Mismatch"
                End If
            End With
        End If
    Next
End Sub
Excel VBA

评论

0赞 taller 11/16/2023
column called SD是 SD 列还是标题单元格有字符串? 是从第 1 行还是第 2 行开始?SDAll the dates in Combined SD Column
0赞 Amy 11/16/2023
列标题位于名为 SD 的第 1 行中。所有日期从第 2 行开始
0赞 taller 11/16/2023
您需要动态定位 col SD 吗?如果不是(这意味着列的位置是固定的),col SD的列号是多少?
0赞 Amy 11/16/2023
动态定位 pls

答:

0赞 taller 11/16/2023 #1

请尝试。

Option Explicit
Sub demo()
    Dim ws As Worksheet
    Dim sDate, c As Range, dateRng As Range
    Dim bMatch As Boolean, sMsg As String
    Dim lastRow As Long
    Const START_ROW = 2
    Const KEYCOL = "SD"
    sDate = Sheets("Control").Range("m5").Value
    For Each ws In ActiveWorkbook.Worksheets
        If ws.Name <> "Control" Then
            bMatch = True
            With ws
                ' Locate col SD
                Set c = .Rows(1).Find(KEYCOL, LookIn:=xlValues, lookat:=xlWhole)
                If Not c Is Nothing Then
                    ' Get the last data row#
                    lastRow = .Cells(.Rows.Count, c.Column).End(xlUp).Row
                    ' Get the date range
                    Set dateRng = .Cells(START_ROW, c.Column).Resize(lastRow - START_ROW + 1)
                    ' Validate each date
                    For Each c In dateRng.Cells
                        If Not c.Value = sDate Then
                            bMatch = False
                            Exit For
                        End If
                    Next
                    If bMatch Then
                        Call Macro9
                    Else
                        sMsg = "Date Mismatch"
                    End If
                Else
                    MsgBox "Can't find column SD"
                End If
            End With
        End If
    Next
End Sub