参考下面的代码。 find
函数找不到范围内的部分日期。我知道我们可以使用for loop
查找范围内的部分日期,但为什么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
ws
范围
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
答案 0 :(得分:0)
试试这样:
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()
重新构建逻辑。
关于Find()
,尝试构建像这样的小东西:
Public Sub TestMe()
Dim rngRange As Range
Set rngRange = ActiveSheet.Cells.Find("08.2016")
Debug.Print rngRange.Address
End Sub
它应该有用。
答案 1 :(得分:0)
此代码将日期转换为Long
中的搜索,以循环整月,然后转换回Date
。
所以它会在一个月内(缓慢)循环查找。
如果您有庞大的工作簿,则不建议使用。
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:类型不匹配。
答案 2 :(得分:0)
在lookin参数中使用带有XlValues的Find函数来搜索日期范围内的字符串值很复杂。
cell numberformat属性必须是默认日期格式以外的日期格式。
确保列的宽度足够大以避免日期被#####替换也很重要。
您可以使用以下内容:
ThisWorkbook.ActiveSheet.Range("C10").NumberFormat = "d-m-yyyy"
t = Split(ThisWorkbook.ActiveSheet.Range("C10").Text, "-")
monthYear = t(1) & "-" & t(2)
Set ws = ThisWorkbook.ActiveSheet.Range("D3:D30")
ws.NumberFormat = "d-m-yyyy"
Set c = ws.Find(monthYear, LookIn:=xlValues, Lookat:=xlPart)