excel 在日期范围内搜索当前日期

sczxawaw  于 2023-05-01  发布在  其他
关注(0)|答案(2)|浏览(141)

单击按钮后,我想检查当前日期是否在单元格范围内。
如果存在,则循环应该结束并且不应该发生任何事情。
如果不存在,则将日期插入该范围中的下一个空单元格。
我尝试了一个“为每个”的方法,但它检查范围内的每个日期,并给出每个单元格的响应。
我只想知道它是否已经存在,而不是对不是当前日期的每个单元格的响应。

Private Function DateUpdateWithCheck()
    Dim ws As Worksheet
    Dim wb As Workbook

    Dim myDate As Date
    Dim searchrange As Range
    Dim cell As Range
    Dim lRow As Long

    myDate = Date

    Set ws = ThisWorkbook.Worksheets("History")
    ws.Activate

    Set searchrange = ws.Range("CA1:CC1")

    For Each cell In searchrange
        If cell.Value = myDate Then
            MsgBox ("Date already in it. End the loop")
            Exit For
        Else
            MsgBox ("Date is not in it. Insert Date.")
            GoTo yesinsert
        End If
    Next

yesinsert:

    With ws
        lRow = Range("C1").End(xlToRight).Offset(0, 1).Select
    
        ActiveCell.Value = Date
        'ActiveCell.EntireColumn.Copy
        'ActiveCell.EntireColumn.PasteSpecial xlPasteValues
    End With
End Function
htzpubme

htzpubme1#

我将用一个例子来进一步解释我的评论。
首先您使用的是private function,没有任何输入。.. function将不作用于细胞;它只输出一个值。您希望使用Subroutine对单元格执行操作。
第二点:在当前代码中,您检查每个单元格,并且在您检查If cell.Value = myDate Then的每个场景中,您都踢出了msgbox。如果你有一个很长的约会清单,那就太多了。您可以通过添加检查值并在整个循环都被检查后才执行msgbox来解决这个问题。
或者,你根本不能做一个循环,而使用Application.Match(),这样(未测试):

Sub DateChecked()
    dim inquiryDate as date:  inquiryDate = ActiveCell.Value
    dim ws as worksheet:  set ws = ThisWorkbook.Sheets("History")
    dim dateRange as range:  set dateRange = ws.Range("CA1:CC1")
    if IsError(Application.Match(inquiryDate, dateRange, 0))=True then
        'Do something when you have no match
    end if
End Sub
bejyjqdl

bejyjqdl2#

这是我的问题的完整答案代码,供将来参考。

Sub HistoryUpdate()

DateUpdateWithCheck

End Sub

Private Function DateUpdateWithCheck()

Dim ws As Worksheet
Dim wb As Workbook

Dim myDate As Date
Dim searchrange As Range
Dim cell As Range
Dim lRow As Long

myDate = Date

Set ws = ThisWorkbook.Worksheets("History")
ws.Activate

Set searchrange = ws.Range(Cells(1, "C"), Cells(1, "C").End(xlToRight))

If IsError(Application.Match(CDbl(myDate), searchrange, 0)) = True Then

With ws
    lRow = Range("C1").End(xlToRight).Offset(0, 1).Select
    
    ActiveCell.Value = Date
    ActiveCell.EntireColumn.Copy
    ActiveCell.EntireColumn.PasteSpecial xlPasteValues

    
End With

End If

End Function

相关问题