Finding a date (dimmed as string) in entire workbo

2019-08-12 04:03发布

I want to search all worksheets for a date, and when found replace the date by "yes".

I have the code below:

Sub Aftekenen()

Dim Sh As Worksheet
Dim Loc As Range
Dim Datum As String

Datum = "28-12-2015"

For Each Sh In ThisWorkbook.Worksheets
With Sh.UsedRange

    Set Loc = .Cells.Find(What:=Datum)

    If Not Loc Is Nothing Then
        Do Until Loc Is Nothing
            Loc.Value = "Yes"
            Set Loc = .FindNext(Loc)
        Loop
    End If
End With
Set Loc = Nothing
Next

End Sub

However the code runs, however it never reaches the For each loop. When I remove the "-" so the date will become a number it finds it. However when the dashes are present the code does not find any fitting value, however these are present.

1条回答
老娘就宠你
2楼-- · 2019-08-12 05:07

try this, for each ... next method with comparing .Text (not value, because of value of the cell for "28-12-2015" is 42366), it works well but some users have an objection to this method by some reasons, as for me less coding better reading

Sub Aftekenen()
    Dim Sh As Worksheet, Loc As Range, Datum As String
    Application.ScreenUpdating = 0
    Datum = "28-12-2015"
    For Each Sh In ThisWorkbook.Worksheets
        For Each Loc In Sh.UsedRange
            If Loc.Text = Datum Then Loc.Value = "Yes"
        Next Loc
    Next Sh
    Application.ScreenUpdating = 1
End Sub

update

if you prefer .find method then for searching of the dates is required to switch Application.FindFormat.NumberFormat to format of the cells with dates, due to the date in .text is 18-05-2015, but .value is 42142

below is your updated variant

Sub Aftekenen()

Dim Sh As Worksheet
Dim Loc As Range
Dim Datum As String

Application.FindFormat.NumberFormat = "dd-mm-yyyy"

Datum = "28-12-2015"

For Each Sh In ThisWorkbook.Worksheets
With Sh.UsedRange

    Set Loc = .Cells.Find(Datum, , xlValues, , , , True, , True)

    If Not Loc Is Nothing Then
        Do Until Loc Is Nothing
            Loc.Value = "Yes"
            Set Loc = .FindNext(Loc)
        Loop
    End If
End With
Set Loc = Nothing
Next
查看更多
登录 后发表回答