为什么FindFunction无法在范围中find部分date – VBA

请参阅以下代码。 find函数没有find范围内的部分date。我知道我们可以使用for loopfind范围内的部分date,但为什么find函数不能find部分date? 问题很简单,但我无法在谷歌find答案…

 Sub Demo() Dim day As Long Dim monthYear As String Dim ws As Range monthYear = Right(ThisWorkbook.ActiveSheet.Range("C10"), 7) ' monthYear = 08-2017 Set ws = ThisWorkbook.ActiveSheet.Range("D3:D30") Set c = ws.Find(monthYear, Lookat:=xlPart) End Sub 

范围

 11-01-2016 29-02-2016 28-03-2016 27-04-2016 27-05-2016 27-06-2016 29-08-2016 29-08-2016 27-09-2016 27-10-2016 28-11-2016 27-12-2016 27-01-2017 27-02-2017 27-03-2017 27-04-2017 29-05-2017 27-06-2017 13-08-2017 28-08-2017 

尝试像这样:

 monthYear = Right(CStr(ThisWorkbook.ActiveSheet.Range("C10")), 7) 

尝试运行这个:

 Public Sub TestMe() Dim rngCell as Range For Each rngCell In Range("D3:D30") If Year(rngCell) = 2017 Then Debug.Print rngCell.Address End If Next rngCell End Sub 

然后使用Year()重新构build逻辑。

关于Find() ,尝试构build一个像这样的小东西:

 Public Sub TestMe() Dim rngRange As Range Set rngRange = ActiveSheet.Cells.Find("08.2016") Debug.Print rngRange.Address End Sub 

它应该工作。

此代码将date转换为在Longsearch以在该月进行循环,然后转换回Date 。 所以它循环查找整个月(慢)。

如果你有一个巨大的工作簿,不build议。

 Sub Demo() Dim monthYear As Date Dim rng As Range, rng2 As Range, cellFound As Range Dim ws As Worksheet Dim i As Long, lastrow As Long Set ws = ThisWorkbook.Sheets(1) lastrow = ws.Cells(ws.Rows.Count, "D").End(xlUp).Row Set rng = ws.Range(ws.Cells(3, 4), ws.Cells(lastrow, 4)) monthYear = (Right(ThisWorkbook.ActiveSheet.Range("C10"), 7)) ' monthYear = 08-2017 intDaysInMonth = day(DateSerial(Year(monthYear), Month(monthYear) + 1, 0)) For i = 0 To intDaysInMonth - 1 LookingFor = CLng(monthYear) + i LookingForString = CStr(CDate(LookingFor)) With rng Set cellFound = .Find(what:=LookingForString, LookIn:=xlValues, MatchCase:=False) If Not cellFound Is Nothing Then FirstAddress = cellFound.Address Do Debug.Print cellFound.Address Set cellFound = .FindNext(cellFound) Loop While Not cellFound Is Nothing And cellFound.Address <> FirstAddress End If End With Next i End Sub 

这是混乱的,有更好的方法来优化它。 我认为你收到错误13:types不匹配。

在lookin参数中使用Find函数与XlValues来在date范围内searchstring值是很复杂的。

单元格数字格式属性必须是默认date格式以外的date格式。

确保列的宽度足够大以避免date被#####取代也很重要。

你可以使用这样的东西:

 ThisWorkbook.ActiveSheet.Range("C10").NumberFormat = "dm-yyyy" t = Split(ThisWorkbook.ActiveSheet.Range("C10").Text, "-") monthYear = t(1) & "-" & t(2) Set ws = ThisWorkbook.ActiveSheet.Range("D3:D30") ws.NumberFormat = "dm-yyyy" Set c = ws.Find(monthYear, LookIn:=xlValues, Lookat:=xlPart)