我正在处理一个电子表格,该表格会记录日期列表,并在不同的工作表上查找这些日期,并在匹配日期下方的单元格中填充一些信息。要搜索的数据看起来像这样:
ROW23: dates generated by formula (formatted: d-mmm)
ROW24: Mix of empty cells and cells with text and numbers.
ROW25: dates generated by formula (formatted: d-mmm)
ROW26: Mix of empty cells and cells with text and numbers.
and so on
此范围称为"日历"并且是Sheet9(B23:O74)。
要搜索的日期列表是" List_Holidays"并且是Sheet5(B9:B12,B16:B21)。找到日期后,要在其下方单元格中返回的文本为" List_HolAbbr"在Sheet5上(A9:A12,A16:A21)。
目前我已经停留在此代码的第1阶段:让它运行只查找一个日期 第二阶段是让它搜索日期列表。 第3阶段是让它只搜索实际包含上述示例日期的行(跳过空单元格和带有文本/ #s的单元格。) 阶段4:让它在找到的日期下填充一些文本。
到目前为止我的尝试:
Sub holidays()
Dim Cal As Range
Dim vholidays As Long
Dim cl As Range
Dim clgcaldate As Range
Set Cal = Sheets("2015_Consolidated").Range("Calendar")
'Find this
Set rgholidays = Worksheets("Holidays_EndPeriods").Range("F10") 'This is the date of the holiday to find in range Calendar
vholidays = DateValue(rgholidays)
MsgBox "vholidays is " & vholidays
'Search this range
MsgBox "g47 is: " & Sheets("2015_Consolidated").Cells(47, "G") 'G47 is the match to the cell in "rgholidays".
For Each cl In Cal
'With Range("List_Holidays)
Set rFound = Cells.Find(what:=vholidays, _
LookIn:=xlValues, _
lookat:=xlWhole, _
SearchOrder:=xlByRows) 'The cell in range Calendar that matches to vholidays
'Match found
If Not rFound Is Nothing Then
MsgBox "rFound is " & rFound
End If
'End With
Next cl
MsgBox "vholidays is " & vholidays & " and is located: " & rFound
End Sub`
前2 msgbox
是正确的,但在G47中找不到匹配。
我也试过这个代码,发现于:Excel VBA - Using Find method on a range of dates
第二次尝试,使用与上面相同的变量。
`MsgBox "vhol is " & vholidays & " rghol is " & rgholidays
For Each cl In Cal
With rgholidays
Set rFound = .Find(vholidays, LookIn:=xlValues, lookat:=xlWhole)
If Not rFound Is Nothing Then
MsgBox cell
End If
End With
Next cl
End Sub`
同样,这不会返回匹配。
http://www.cpearson.com/excel/DateTimeVBA.htm建议使用DateValue()
将日期转换为序列号,这对我来说似乎是合理的,我在第一个示例中尝试过。
我已经找到了其他一些参考资料,但这些参考资料已从我试图做的事情中进一步删除。
有什么建议使这项工作?
编辑:我设置了一个条件来测试搜索值的格式是否相同以及它应该找到的值。它说他们是一样的。 测试电子表格中的查找/替换gui框,"找到"无论查找/替换设置如何,都找不到合适的单元格。
编辑:我尝试过Application.Match。找不到匹配项。这会遍历范围内的每一列,寻找与日期的匹配,但找不到任何内容。
Sub holidays()
Dim Calendar As Range
Dim cl As Range
Dim rFound As Variant
Dim findthis As Double
Dim rng As Range
Dim Cal As Range
Set Cal = Sheets("2015_Consolidated").Range("Calendar")
findthis = CDate(CLng(Sheets("2015_Consolidated").Range("K17"))) '"1/13/2015"
Debug.Print "find this:" & findthis
Debug.Print "cell d23: " & ActiveSheet.Cells(23, 4)
For Each rng In Range("Calendar").Columns
Debug.Print rng.Address
rFound = Application.Match(findthis, rng.Address, 0)
If IsError(rFound) Then
Debug.Print "Not found"
Else
Debug.Print rFound
End If
Next rng
End Sub
答案 0 :(得分:0)
如果您在代码中设置“Cal”和“rgholidays”变量,请尝试:
For each cell in Cal
if format(rgholidays,"m/d/yyyy")=format(cell,"m/d/yyyy") then
'Cell has the same date, do some code
endif
Next cell
使用日期时,使用它们的另一种方法是格式化它们yyyymmdd,然后较大的数字总是晚于小的数字,例如。这应该是你问题的第一阶段,找到日期。第2阶段和第4阶段应该是此代码的某个版本,并与您编写的内容相结合。第3阶段可能很棘手,除非你的非约会行总是不变的。