首页 文章

如何使用 . 在VBA中查找特定的数据类型?

提问于
浏览
0

所以当我尝试在VBA中编程时,我在微软网站(https://msdn.microsoft.com/en-us/library/office/ff839746.aspx)上发现了这个

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

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

我希望我的代码能够在特定范围内找到第一个具有“Date”数据类型的单元格,temp .

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

但我一直得到“对象变量未设置”错误,我认为这意味着它无法在范围内找到日期 . 该范围内肯定有一个日期,但当我鼠标悬停在我输入.Find()的“Date”时,我意识到它显示了今天的日期 .

我认为这段代码可能会试图在范围内寻找今天的日期 . 但我只是想让它找到一个具有通用“日期”数据类型的单元格,有没有办法在不指定具体日期的情况下执行此操作?谢谢!!

3 回答

  • 0

    问题不是'Is there a Date in A63:A70?'而是'What else is in A63:A70?' . 日期实际上并不是一种单独的 Value . 对于大多数意图和目的(稍后将详细介绍),它们被视为数字 . 如果您只想在包含日期,文本,空白但没有其他数字的范围内找到第一个日期类型,那么这应该可以 .

    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 Function . 这可能会考虑a)值的数值性质,b)Range.Value和Range.Value2之间的差异,以及c)确定细胞值是42,149还是25-May-2015的细胞数量格式 . 但是,IsDate函数一次只能检查一个单元,因此需要耗费时间的单元循环 .

    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个单元,所以一个循环不会对性能产生过分的损害,但它肯定会减慢几千个单元格来进行单独检查 .

  • 2

    我不确定您是否可以使用 Find() 来查找任何日期类型的值 . 我想你需要指定你要搜索的实际日期 . 例:

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

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

    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
    
  • 0

    temp 是一个对象 Range . 你必须使用 set - > What does the keyword Set actually do in VBA?

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

    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
    

相关问题