如何使用VBA在excel中查找日期或后续日期
我正在编写一个宏来查找工作表上下一周的所有条目,并选择第一行以匹配最早的日期。 我可以让宏查找第一个日期(一周前),但如果第一个日期未返回匹配项,则无法确定如何查找后续日期 例如。 今天日期:2016年3月28日。宏将回顾7天(2016年3月21日)。如果2016年3月21日没有条目,请查找2016年3月22日的第一条条目。如果该日期没有日期,则为2016年3月23日,以此类推 这可能吗 以下是迄今为止的代码:如何使用VBA在excel中查找日期或后续日期,vba,excel,macros,Vba,Excel,Macros,我正在编写一个宏来查找工作表上下一周的所有条目,并选择第一行以匹配最早的日期。 我可以让宏查找第一个日期(一周前),但如果第一个日期未返回匹配项,则无法确定如何查找后续日期 例如。 今天日期:2016年3月28日。宏将回顾7天(2016年3月21日)。如果2016年3月21日没有条目,请查找2016年3月22日的第一条条目。如果该日期没有日期,则为2016年3月23日,以此类推 这可能吗 以下是迄今为止的代码: Private Sub CommandButton1_Click() Dim
Private Sub CommandButton1_Click()
Dim strFilename As String
Dim rngRange As Range
Dim strfind As String
Set strfind = Worksheets("Report").Range("J1")
Set rngRange = Worksheets("Report").Range("B:B")
If opt1.Value = True Then
Cells.Find(what:=strfind, after:=ActiveCell, LookIn:=xlValues, Lookat:=xlPart, _
searchorder:=xlByRows, searchdirection:=xlNext, MatchCase:=False, searchformat:=False).Activate
If opt2.Value = True Then
Cells.Find(what:=strfind, after:=ActiveCell, LookIn:=xlValues, Lookat:=xlPart, _
searchorder:=xlByRows, searchdirection:=xlNext, MatchCase:=False, searchformat:=False).Activate
End If
'Range("A1:H100").Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Desktop\Obs Diary Report week starting " & strFilename & ".pdf", Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End Sub
谢谢
Christian很难判断数据中的工作方式,但您所需要做的就是在
Find
中循环,每次将要搜索的日期增加一个,直到找到今天的日期或查找某个内容为止
以下是一个您可以根据需要进行调整的示例:
Option Explicit
Sub OneWeekAgo()
Dim dtEarliest As Date
Dim WS As Worksheet
Dim R As Range
Set WS = ActiveSheet
dtEarliest = Date - 7
With WS.Cells
Do Until Not R Is Nothing
Set R = .Find(dtEarliest)
dtEarliest = dtEarliest + 1
If dtEarliest > Date Then
Debug.Print "No Dates in Last Week"
Exit Sub
End If
Loop
End With
If Not R Is Nothing Then
Debug.Print R.Address, R.Text
End If
End Sub
我相信这是可能的。您的数据在电子表格中的结构如何?您能发布到目前为止您拥有的宏吗?Alex P,电子表格中的数据显示为每个条目都在其自己的行中,由以下人员组织:姓名日期时间标题观察等。上面添加了宏代码。