Excel VBA – 在一系列date中使用Find方法

我试图找出某个date是否在一个date范围内。 这是date范围:

01/01/2013 11/02/2013 29/03/2013 20/05/2013 01/07/2013 05/08/2013 02/09/2013 14/10/2013 11/11/2013 25/12/2013 26/12/2013 

这里是VBA代码:

  ' Format Holiday Rows ' With ConfigData.Range("B8:B18") Set holidays = .Find(s1.Cells(row_count, 1)) If Not holidays Is Nothing Then MsgBox s1.Cells(row_count, 1) End If End With 

在上面的代码中,popup的第一个MsgBox显示“11/01/2013”​​。 这绝对没有意义,因为这个价值不在范围内。

注意:ConfigData.Range(“B8:B18”)是指上面显示的date范围。

此外:此代码位于for循环中,用于递增s1.Cells(row_count,1)的值。 从2013年1月1日至2013年12月31日

如果您只想确认系列中的日历日是在假期列表中,那么您甚至可以使用vlookup

 Dim strFound As String On Error Resume Next strFound = Application.Vlookup(s1.Cells(row_count, 1), .Range("B8:B18"), 1, 0) If IsError(strFound) Then MsgBox "Not Found" Else '-- Found End If On Error GoTo 0 

以下代码适用于我:

 Sub thing() Dim cell As Range, _ holidays As Range For Each cell In Range("D1:D365") With Range("A1:A11") Set holidays = .Find(cell.Value, LookIn:=xlValues, lookat:=xlWhole) If Not holidays Is Nothing Then Debug.Print cell.Value End If End With Next cell End Sub 

如果这不起作用,我会build议可能你有一个单元格格式问题。 select一个date单元格。 转到立即窗口(Alt + F11,然后从Excel中Ctrl + G),键入? Selection.Value2 ? Selection.Value2并按回车。 这是否返回一个数值(〜41000)?

或者,您也可以在一张全新的表格中重新inputdate(手动input第一对,然后向下拖动,不要复制和粘贴,因为格式化也会被复制),然后再试一次。 这至less应该删除奇怪的格式,作为一个潜在的问题。

注意到excel使用美式date格式很重要。 即mm / dd / yyyy,因此让.Find()函数正常工作可能有点棘手。 确保你的variables正确的形成,以便excel能够希望给你你正在寻找的东西:

 Dim strdate As String Dim aCell As Range strdate = ActiveSheet.Cells(1,1) strdate = Format(strdate, "Short Date") On Error Resume Next Set aCell = Cells.Find(What:=CDate(strdate), After:=Range("A1"), LookIn:=xlFormulas , LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False) If rCell Is Nothing Then MsgBox("Date cannot be found. Try Again") End If End Sub 

当然,在date格式化过程中会出现很多令人讨厌的事情,但是这是假设您在“短date”格式中查找的date。

'要在工作表的其他地方find与参考单元具有相同特定date的单元格:'首先将所有date复制到其左侧的单元格中。 '将复制的单元格格式化为“常规”'运行此代码 – 然后使用dateRow和DateColvariables(例如,在vlookup中)'在Excel 2013中工作(不能隐藏“常规”列 – 通过背景颜色格式隐藏)

 Dim dateVal Dim DateRow Dim DateCol dateVal = Range("j8").Value 'must be in general format Cells.Find(What:=dateVal, After:=ActiveCell, LookIn:=xlValues, LookAt:= _ xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _ , SearchFormat:=False).Activate DateRow = ActiveCell.Row DateCol = ActiveCell.Column MsgBox (DateRow & " " & DateCol) End Sub