Range.Find与自定义数字格式的date

以下是我遇到的有关代码的相关部分。

Sub Find_Target() Dim DayNum As Long Dim TargetName As String Dim TargetDay As Range Dim found As Variant DayNum = Cells(1, 9) Set TargetDay = ActiveWorkbook.Sheets("3-2015").Range("A1:B440") TargetDay.Activate Set found = TargetDay.Find(DayNum, LookIn:=xlValues) If found Is Nothing Then MsgBox "Nothing found!" Else TargetDay.Select End If End Sub 

列A包含合并和未合并单元的组合。 单元格(1,9)包含通用格式的date。 定期在A / B列将是一个合并单元格包含相同的号码,但在自定义数字格式“dddd”。 如果我将数字格式更改为常规,则find命令有效,但在其他情况下找不到。

我试着玩FindFormat选项,但没有任何运气。

这个问题有点不清楚,所以我假设你在单元格I1中有一个数字,并且你想在这个月的同一天find第一个单元格。 假设是这种情况,你可以循环遍历范围,并直接与当天比较:

 Sub Find_Target() Dim DayNum As Long Dim TargetDay As Range Dim found As Range DayNum = Cells(1, 9) Set TargetDay = ActiveWorkbook.Sheets("3-2015").Range("A1:B440") Dim row As Long, col As Long For row = 1 To TargetDay.Rows.Count For col = 1 To TargetDay.Columns.Count If IsDate(TargetDay.Cells(row, col).Value) Then If Day(CDate(TargetDay.Cells(row, col).Value)) = DayNum Then Set found = TargetDay.Cells(row, col) Exit For End If End If Next col If Not found Is Nothing Then Exit For Next row If found Is Nothing Then MsgBox "Nothing found!" Else found.Select End If End Sub 

如果I1是别的东西,修改它应该是微不足道的 – 关键是明确地将单元格值视为VBA中的date。

你需要寻找LookAt:=xlFormulas并寻找Datetypes的var,而不是Long。 在你的数据抛出以下内容。

 Sub Find_Target() Dim iDayNum As Long, sDayNum As String, dDayNum As Date Dim foundI As Variant, foundS As Variant, foundD As Variant Dim TargetDay As Range iDayNum = Cells(1, 9) sDayNum = Format(Cells(1, 9), "mm/dd/yyyy") dDayNum = Cells(1, 9) 'I might even use CDate(Cells(1, 9).Value) as a reminder Set TargetDay = ActiveWorkbook.Sheets("3-2015").Range("A1:B440") Set foundI = TargetDay.Find(iDayNum, LookIn:=xlFormulas, LookAt:=xlWhole) Set foundS = TargetDay.Find(sDayNum, LookIn:=xlFormulas, LookAt:=xlWhole) Set foundD = TargetDay.Find(dDayNum, LookIn:=xlFormulas, LookAt:=xlWhole) If foundI Is Nothing Then MsgBox "As a Long - Nothing found!" Else MsgBox "As a Long - Found!" End If If foundS Is Nothing Then MsgBox "As a String - Nothing found!" Else MsgBox "As a String - Found!" End If If foundD Is Nothing Then MsgBox "As a Date - Nothing found!" Else MsgBox "As a Date - Found!" End If End Sub 

你应该没有问题find匹配的datevar无论是格式化为dddd或其他。