使用vlookup错误1004应用程序定义或对象定义的错误?

当试图使用这个vlookup时,我得到这个错误1004。 我使用一个窗口来select一个文件,然后在vlookup中使用该文件。 我在另一个macros中做了这个,我使用了基本相同的代码。 但由于某种原因,这一个不工作。 任何人都可以看到任何明显的问题? 我无法弄清楚我做错了什么。

我在第一个VLOOKUP公式的右边出现“With ws”

Dim iRet As Integer Dim strPrompt As String Dim strTitle As String Dim shtName As String ' Prompt strPrompt = "Please select the last Kronos Full File before the dates of this Report." & vbCrLf & _ "For example, if the date of this report is 9-8-17, you would want to use the closest date Kronos Full File." & vbCrLf & _ "If one was not ran in the past couple days, then run a new Kronos Full File, and then choose that file." ' Dialog's Title strTitle = "Latest Kronos Full File" 'Display MessageBox iRet = MsgBox(strPrompt, vbOK, strTitle) Dim Window2 As String Dim X As String Dim lNewBracketLocation As Long Dim wb2 As Workbook Window2 = Application.GetOpenFilename( _ FileFilter:="Excel Files (*.xls*),*.xls*", _ Title:="Choose the Newest Kronos Full File", MultiSelect:=False) Set wb2 = Workbooks.Open(Filename:=Window2, ReadOnly:=True) shtName = wb2.Worksheets(1).name wb2.Close MsgBox "You selected " & Window2 'Find the last instance in the string of the path separator "\" lNewBracketLocation = InStrRev(Window2, Application.PathSeparator) 'Edit the string to suit the VLOOKUP formula - insert "[" X = Left$(Window2, lNewBracketLocation) & "[" & Right$(Window2, Len(Window2) - lNewBracketLocation) With ws .Range("M2").Formula = "=VLOOKUP($K2,'" & X & "]shtName'!$B$2:$E$99999,4,0)" .Range("N2").Formula = "=VLOOKUP($K2,'" & X & "]shtName'!$B$2:$C$99999,2,0)" .Range("O2").Formula = "=VLOOKUP($K2,'" & X & "]shtName'!$B$2:$U$99999,20,0)" .Range("P2").Formula = "=VLOOKUP($K2,'" & X & "]shtName'!$B$2:$Q$99999,16,0)" .Range("Q2").Formula = "=VLOOKUP($K2,'" & X & "]shtName'!$B$2:$S$99999,18,0)" End With 

从另一个工作簿中使用Range的地址的另一种方法是设置范围,稍后可以使用Range.Address(True, True, xlR1C1, xlExternal) 。 如果需要,第四部分将添加工作表和工作簿的名称。

 Dim Rng1 As Range ' new Range Object Window2 = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls*),*.xls*", _ Title:="Choose the Newest Kronos Full File", MultiSelect:=False) Set wb2 = Workbooks.Open(Filename:=Window2, ReadOnly:=True) 'shtName = wb2.Worksheets(1).Name '<-- not necessary Set Rng1 = wb2.Worksheets(1).Range("B2:E99999") wb2.Close With ws .Range("M2").Formula = "=VLOOKUP($K2," & Rng1.Address(True, True, xlR1C1, xlExternal) & ",4,0)" ' define more ranges for the other formulas End With 

看来我的问题与我尝试使用VLOOKUP的范围有关。 看起来就像我把99999改成只有9999一样,看起来就像VLOOKUP一样。 我仍然不清楚为什么,但我确定是这样。 当我降低数字范围时,我没有收到错误信息。 我猜测是因为它正在走出实际工作表的范围之外。