如何使用。在VBA中find一个特定的数据types?
所以我在微软网站( https://msdn.microsoft.com/en-us/library/office/ff839746.aspx )上find了这个,当时我正在用VBA
expression式.Find(What,After,LookIn,LookAt,SearchOrder,SearchDirection,MatchCase,MatchByte,SearchFormat)expression式表示Range对象的variables。
什么:要search的数据。 可以是string或任何Microsoft Excel数据types。
我希望我的代码在一定范围内find第一个“Date”数据types的单元格。
Dim temp As Range, next_date As Range temp = Range("A63:A70") Set next_date = temp.Find(Date) Debug.Print (next_date)
但我一直得到“对象variables没有设置”的错误,我认为这意味着它无法find范围内的date。 确实有一个date范围,但是当我将鼠标放在.Find()中input的“Date”上时,我意识到它显示了今天的date。
我认为这个代码可能试图在范围内寻找今天的date。 但我只是希望它find一个通用的“date”数据types的单元格,有没有办法做到这一点,而不指定具体的date? 谢谢!!
问题不在于“A63中有date:A70”吗? 但是“A63:A70还有什么? 。 date并不是一个单独的价值types。 对于大多数意图和目的(稍后会有更多介绍),它们被视为数字。 如果你想在包含date,文本,空白但没有其他数字的范围内find第一个datetypes,则应该这样做。
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函数一次只能检查单个单元格,因此需要耗费一个循环单元格。
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个单元,所以一个循环不会对性能造成太大的负面影响,但是肯定会减慢几千个单元的速度。
我不确定您可以使用Find()
来查找任何datetypes的值。 我认为你需要指定你正在search的实际date。 例:
Set FoundCell = Range("A1:A10").Find (what:="7/18/1998")
另一种select是一个简单的循环:
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
temp
是一个对象Range
。 你必须使用set
– > 关键字Set在VBA中究竟做了什么?
我认为你不能find使用.Find()
数据types,但是,你可以尝试查找表明我们正在处理date的格式:
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