【发布时间】:2015-10-06 04:55:07
【问题描述】:
我正在制作一个包含日期列表的电子表格,并在不同的工作表上找到这些日期,并在匹配日期下方的单元格中填充一些信息。要搜索的数据如下所示: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)。找到日期后,在其下方单元格中返回的文本是 Sheet5(A9:A12,A16:A21) 上的“List_HolAbbr”。
目前我被困在这段代码的第 1 阶段:让它运行,只寻找一个日期。
第 2 阶段是让它搜索日期列表。
第 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 个msgboxs 是正确的,但在 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
【问题讨论】:
标签: excel date calendar match vba