在不同工作簿的单元格中查找date,然后将行号作为variables返回

我有两个工作簿,第一个工作簿是供员工使用的,这个工作簿在那一周生成报告。 第二个工作簿是包含制作这些报告所需的所有数据的工作簿。

我想要做的是find一周的开始date,并做第二个工作簿VLookupfind一周开始date,并返回find的单元格的“行号”作为variables,我可以使用各种其他事情。

当前的代码返回运行时错误(424):对象必需

这是我迄今为止:

Sub SourceFileLookup() Dim lookFor As Range Dim srchRange As Range Dim book2 As Workbook Dim book2Name As String book2Name = "Report_Data.xlsx" ' Name of Source File Set book2 = Workbooks(book2Name) strdate = GetWeekStartDate(Date) fdate = Format(strdate, "dd/mm/yy") Set lookFor = fdate ' value to find Set srchRange = book2.Sheets("TB").Range("B:B") ' Search Range lookFor = Application.VLookup(lookFor, srchRange, 1, False) Exit Sub End Sub Function GetWeekStartDate(ByVal strdate, Optional ByVal lngStartDay As Long = 2) As String GetWeekStartDate = DateAdd("d", _ -Weekday(CDate(strdate), lngStartDay) + 1, CDate(strdate)) End Function 

Vlookup返回指定单元格的值而不是地址。 使用MATCH获取匹配date的行

 Application.Match(lookFor, srchRange, 0) 

那么你可以使用该行,只要你想

你只设置对象。 您不会使用Set来为variables指定date,并且该variables应该是Datetypes或Variant 。 实际上, GetWeekStartDate函数正在返回一个datetypes值,但是您将它作为一个string来回折腾,然后尝试为其设置一个Range对象。

 Sub SourceFileLookup() Dim fDate As Date Dim rw As Long Dim srchRange As Range Dim book2Name As String, book2 As Workbook book2Name = "Report_Data.xlsx" ' Name of Source File Set book2 = Workbooks(book2Name) fDate = GetWeekStartDate(Date) Set srchRange = book2.Sheets("TB").Range("B:B") ' Search Range If Application.CountIf(srchRange, fDate) Then rw = Application.Match(CLng(fDate), srchRange, 0) 'rw contains the Row Number of the date 'you need to do something with rw Else MsgBox Format(fDate, "dd/mm/yyyy") & " not found." End If End Sub 

你说过你想把行号作为variables返回 。 MATCH函数是最好的select,但最好在检索行号之前确保它带有COUNTIF函数 。

一旦检索到行号,如何处理行号几乎没有。 在上面,它被存储在long型variablesrw

 set lookFor = Application.VLookup(lookFor, srchRange, 1, False)