Range.Find日期与自定义数字格式

时间:2015-04-15 23:58:35

标签: excel vba

这是我的代码的相关部分,我遇到了麻烦。

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)包含一般格式的日期。 A / B列中的定期单元格将是包含相同数字的合并单元格,但是采用自定义数字格式" dddd"。如果我将数字格式更改为常规,则find命令有效,但是否则找到Nothing。

我试过玩FindFormat选项,但那里没有运气。

2 个答案:

答案 0 :(得分:0)

问题有点不清楚,所以我假设您在单元格I1中有一个数字,并且您希望在该月的同一天找到第一个单元格。假设情况如此,您可以直接遍历范围并直接与日期进行比较:

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中的日期。

答案 1 :(得分:0)

.Find需要LookAt:=xlFormulas并查找日期类型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

无论是否将其格式化为 dddd 或其他任何内容,您都可以轻松找到匹配的日期变量。

相关问题