簡體   English   中英

對於輸入日期,查找具有相同月份和年份的日期單元格

[英]For an input date, find a date cell with same month and year

在我的 VBA 代碼中,我目前正在使用輸入框來獲取格式為 mm/dd/yy 的用戶輸入日期。 我想要做的是搜索一個文件並找到一個日期格式單元格,其日期與輸入的月份和年份匹配。 所以比如說用戶輸入是 5/20/20,那么我想要一個任何日期為 5/??/20 的單元格,在哪里?? 代表一個月中的任何一天。 最后我想記錄單元格的列。

到目前為止,這是我的代碼。 它只搜索/查找確切的輸入日期,這不是我想要的。

Sub FindMonthandYear ()  
Dim day As Date
Dim inp As String  
    inp = InputBox("enter date", "Date format dd/mmyy", _ Format(Date,"dd/mm/yy"))  
    day = Format(CDate(inp),"mm/dd/yy")
  
Dim col_date_cell As Range  
Dim col_date As Long
Set col_date_cell = Cells.Find(what:=day, LookIn:=xlFormulas, LookAt:=xlWhole)  
    If Not col_date_cell Is Nothing Then  
        col_date = col_date_cell.Columns(col_date_cell.Columns.Count).Column  
    Else  
        MsgBox "Date not found in file!"  
        Exit Sub  
    End If  
End Sub

任何幫助,將不勝感激!

編輯:我想重申我在評論中所說的話,希望能澄清一些事情。 我將此代碼應用於多個文件,每個文件都有一個單元格,其中包含我正在搜索的月份內的日期(因此一個文件可能有一個單元格為 5/3/20,而另一個文件將有 5/4/20 )。 在每個文件中都有一行以 mm/dd/yy 為數字格式的日期,並且這一行因文件而異。 日期從文件之間的不同列開始。 日期的順序在文件之間也會發生變化,因此在一個文件中,最近的日期在最左邊的單元格中,而在另一個文件中,最近的日期在最右邊的單元格中。

謝謝蒂姆威廉姆斯的回答!

嘗試這個:

Sub FindMonthandYear()

    Dim inp As String, c As Range, rng As Range, v, my As String
    
    inp = InputBox("enter date", "Date format dd/mm/yyyy", Format(Date, "dd/mm/yyyy"))
    my = Format(CDate(inp), "m-yyyy")
    
    On Error Resume Next 'ignore error if no cells matched
    Set rng = ActiveSheet.Cells.SpecialCells(xlCellTypeConstants)
    On Error Resume Next
    
    For Each c In rng.Cells
        v = c.Value
        If IsDate(v) Then
            If Format(v, "m-yyyy") = my Then
                Debug.Print c.Address
            End If
        End If
    Next c
 
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM