对于输入日期,请查找具有相同月份和年份的日期单元格



在我的 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

最新更新