VBA,具有一定价值的转到单元格(types:date)

我有代码如下:

Sub Find_First() Dim FindString As String Dim Rng As Range FindString = Range("A1") If Trim(FindString) <> "" Then With Sheets("Kalendarz").Range("A5:LY5") Set Rng = .Find(What:=FindString, _ After:=.Cells(.Cells.Count), _ LookIn:=xlValues, _ LookAt:=xlWhole, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False) If Not Rng Is Nothing Then Application.Goto Rng, True Else MsgBox "Nothing found" End If End With End If End Sub 

但它不符合date格式,任何build议?

更多细节:在A1单元格中,我将input一个date,在5.行中,我在2016年每天都有一个列表。我想要(在运行macros之后)从单元格A1到date单元格。

在Excel VBA中使用Findfunctionfind一个date是非常棘手的。 该function依赖于您的searchdate被格式化为Excel的默认设置相同的方式。 另外,您需要确保使用CDate将searchstring转换为Find函数中的date。 Ozgrid有一个很好的文章: http ://www.ozgrid.com/VBA/find-dates.htm

为了适应这些要求,我修改了下面的代码,并添加了一个额外的With Sheets...语句,以确保FindString使用目标工作表中的Range

但是,由于用户调整date格式的不可预测性,我更喜欢使用Excel的数值表示date的Value2的VBA循环,所以不能弄乱。 Ozgrid文章不希望使用VBA循环时Find函数是如此之快,但我想这是一个个人喜好的问题,我觉得一个定制的循环更可靠。

由你决定哪一个。

Find方法:

 Sub Find_First() Dim FindString As String Dim Rng As Range With Sheets("Kalendarz") FindString = .Range("A1") If Trim(FindString) <> "" Then With .Range("A5:LY5") Set Rng = .Find(What:=CDate(FindString), _ After:=.Cells(1), _ LookIn:=xlValues, _ LookAt:=xlWhole, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False) If Not Rng Is Nothing Then Application.Goto Rng, True Else MsgBox "Nothing found" End If End With End If End With End Sub 

VBA循环方法:

 Sub Find_First_VBA_Loop() Dim dateVal As Long Dim cell As Range With Sheets("Kalendarz") dateVal = .Range("A1").Value2 For Each cell In .Range("A5:LY5").Cells If dateVal = cell.Value2 Then Application.Goto cell, True Exit For End If Next End With End Sub