VBA:在由date组成的正上方的行上使用匹配function自动select单元格

我是Vba的初学者

我想根据当前的date自动select一个单元格。 为此,我有我想要在第8行select的值和第7行按时间顺序排列的date。

我试了下面的代码:

Sub selectvalues() Dim rtc As Double Dim ystdy As Date Dim tdy As Date szToday = Format(Date, "YYYYMMDD") tdy = szToday ystdy = WorksheetFunction.WorkDay(tdy, -1) rtc = WorksheetFunction.Match(ystdy, Range("A7", "ZZ7"), 0) Cells(8, rtc).Select End Sub 

但是我明白了

执行时间错误13,types不匹配

任何人都可以帮我吗?

非常感谢你。

在你的情况,因为你正在寻找一个连续的特定值, Findfunction可以更好地工作。

试试下面的代码,在代码的注释里面的解释:

 Option Explicit Sub selectvalues() Dim rtc As Variant Dim ystdy As Date Dim tdy As Date Dim FindRng As Range tdy = Date ystdy = WorksheetFunction.WorkDay(tdy, -1) ' use Find function Set FindRng = Range("A7", "ZZ7").Find(What:=ystdy, LookIn:=xlValues, lookat:=xlWhole) If Not FindRng Is Nothing Then ' see that find was successful FindRng.Select Else MsgBox "Error, unable to match " & ystdy & " in the specified range", vbCritical End If End Sub