2017-10-20 120 views
0

嘗試使用此vlookup時出現此錯誤1004。我使用一個窗口來選擇一個文件,然後在vlookup中使用該文件。我在另一個宏中使用它,我使用了基本相同的代碼。但由於某種原因,這一個不工作。任何人都可以看到任何明顯的問題?我無法弄清楚我做錯了什麼。使用vlookup錯誤1004應用程序定義或對象定義的錯誤?

我上第一VLOOKUP公式錯誤後右側的「使​​用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 
+0

您確定x =您認爲應該如何? –

+0

好問題我猜這可能是什麼,但我從我的其他代碼複製它,這些工作。我會再看看它。 – Robillard

+1

你不需要'.Range(「M2」)。Formula =「= VLOOKUP($ K2,'」&X&「]」&shtName&「'!$ B $ 2:$ E $ 99999,4,0) 「'作爲'shtName'是一個變量? – SJR

回答

0

看來我的問題與我嘗試使用VLOOKUP的範圍有關。它看起來像我一次將99999改爲只有9999,那麼它看起來像VLOOKUP的工作。我仍然不確定爲什麼,但我很肯定這是它。當我降低數字範圍時,我沒有收到任何錯誤消息。我猜測是因爲它超出了實際工作表的範圍。

1

另一種方式來繞去使用從另一個工作簿中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 
相關問題