关于excel:如何在VBA中使用.Find查找特定数据类型?

How to use .Find in VBA to find a specific data type?

因此,当我尝试在VBA中进行编程时,我在Microsoft网站(https://msdn.microsoft.com/zh-cn/library/office/ff839746.aspx)上找到了此文件

表达式.Find(What,After,LookIn,LookAt,SearchOrder,SearchDirection,MatchCase,MatchByte,SearchFormat)
expression代表Range对象的变量。

内容:要搜索的数据。可以是字符串或任何Microsoft Excel数据类型。

我希望我的代码找到在一定范围内(温度)为" Date"数据类型的第一个单元格。

1
2
3
4
Dim temp As Range, next_date As Range
temp = Range("A63:A70")
Set next_date = temp.Find(Date)
Debug.Print (next_date)

但是我一直收到"未设置对象变量"错误,我认为这意味着它找不到范围内的日期。范围内肯定有一个日期,但是当我将鼠标悬停在.Find()中键入的"日期"上时,我意识到它显示了今天的日期。

我认为这段代码可能试图在范围内查找今天的日期。但是我只希望它查找具有通用"日期"数据类型的单元格,是否有任何方法可以在不指定特定日期的情况下进行?谢谢!!


我不确定您可以使用Find()查找日期类型的任何值。我认为您需要指定要搜索的实际日期。例:

1
Set FoundCell = Range("A1:A10").Find (what:="7/18/1998")

另一个选择是一个简单的循环:

1
2
3
4
5
6
7
8
9
10
Sub FindNextDate()
    Dim val As Range

    For Each val In Range("A1:A10")
        If IsDate(val) Then
            Debug.Print"Date:" & val &" found at cell:" & val.Address
            Exit Sub
        End If
    Next val
End Sub

问题不仅仅在于" A63:A70中是否有日期?"但是" A63:A70还有什么?"。日期并不是真正的单独值类型。对于大多数意图和目的(稍后会详细介绍),它们被视为数字。如果您要查找包含日期,文本,空格但没有其他数字的范围内的第一个日期类型,则应该这样做。

1
2
3
4
5
6
7
8
9
    Dim temp As Range
    On Error Resume Next
    Set temp = Range("A63:A70").SpecialCells(xlCellTypeConstants, xlNumbers)
    If Not temp Is Nothing Then
        Set temp = temp.Cells(1, 1) 'reset temp to the 1st date if there are more than one
        Debug.Print temp.Address
    Else
        Debug.Print"no date in range"
    End If

我说大多数意图和目的的原因是因为VBA确实具有IsDate函数。这可能看一下a)值的数字性质,b)Range.Value和Range.Value2之间的差异,以及c)单元格的数字格式,以确定单元格值是42,149还是2015年5月25日。但是,IsDate函数一次只能检查单个单元格,因此必须经过这些单元格进行耗时的循环。

1
2
3
4
5
6
7
8
9
    Dim temp As Range
    For Each temp In Range("A63:A70")
        If IsDate(temp) Then Exit For
    Next temp
    If Not temp Is Nothing Then
        Debug.Print temp.Address
    Else
        Debug.Print"no date in range"
    End If

您的示例只有8个单元,因此循环不会对性能造成太大影响,但是肯定会减慢速度,因为只有数千个单元可以单独检查。


temp是对象Range。您必须使用set->关键字Set在VBA中实际上有什么作用?

我认为您无法使用.Find()查找数据类型,但是,您可以尝试查找表明我们正在处理日期的格式:

1
2
3
4
5
6
7
8
9
10
11
12
13
Sub tt()

Dim temp As Range, next_date As Range
Set temp = Range("A60:A70")

Application.FindFormat.NumberFormat ="m/d/yyyy"

Set next_date = temp.Find("", SearchFormat:=True)

Debug.Print next_date
Debug.Print next_date.Address

End Sub