提问人:Amy 提问时间:11/16/2023 最后编辑:ZygDAmy 更新时间:11/16/2023 访问量:50
比较 2 张 vba 中的日期
Compare Dates in 2 sheets vba
问:
我有 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
答:
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
评论
column called SD
是 SD 列还是标题单元格有字符串? 是从第 1 行还是第 2 行开始?SD
All the dates in Combined SD Column