VLOOKUP适用于FormulaR1C1,但不适用于常规公式?

时间:2017-10-20 20:10:31

标签: excel vba excel-vba

我之前发布了另一个与此问题相近的问题但实际上并不相同。我有这个VLOOKUP代码,它从用户获取输入以获取文件以使用VLOOKUP。当我运行整个事情时它在我的一个宏中工作,但如果我自己运行私有子,我在第一个VLOOKUP行上得到一条错误消息1004。然后我尝试更改代码以使用FormulaR1C1,它最终使用该版本正常工作。为什么使用我当前的代码不起作用,但是当我使用FormulaR1C1时它会起作用?

Sub NEWTRY()
'
' Create_VLOOKUP_Using_Old_Kronos_Full_File Macro
'

'

Dim iRet As Integer
Dim strPrompt As String
Dim strTitle As String

' Promt
strPrompt = "Please select the last Kronos Full File before the dates of this HCM Report." & vbCrLf & _
    "This will be used to find the Old Position, Org Unit, and Old Cost Center." & vbCrLf & _
    "For example, if the date of this report is 7-28-17 thru 8-25-17, the closest Kronos Full File you would want to use is 7-27-17."

' Dialog's Title
strTitle = "Last Kronos Full File for Old Positions"

'Display MessageBox
iRet = MsgBox(strPrompt, vbOK, strTitle)

Dim LR As Long
Dim X As String
Dim lNewBracketLocation As Long

X = Application.GetOpenFilename( _
    FileFilter:="Excel Files (*.xls*),*.xls*", _
    Title:="Choose the Kronos Full File.", MultiSelect:=False)

Dim wbk As Workbook
Set wbk = Workbooks.Open(Filename:=X, ReadOnly:=True)

Dim shtName As String
shtName = wbk.Worksheets(1).name
wbk.Close

MsgBox "You selected " & X
'Find the last instance in the string of the path separator "\"
lNewBracketLocation = InStrRev(X, Application.PathSeparator)
'Edit the string to suit the VLOOKUP formula - insert "["
X = Left$(X, lNewBracketLocation) & "[" & Right$(X, Len(X) - lNewBracketLocation)

Range("T2").FormulaR1C1 = "=VLOOKUP(RC11,'" & X & "]'!R3C2:R9846C49,13,0)"
ActiveWorkbook.ActiveSheet.Range("U2").Formula = "=VLOOKUP($E2,'" & X & "]'!$B$1:$AP$99999,41,0)"
Range("V2").Formula = "=VLOOKUP($E2,'" & X & "]shtName'!$B$1:$AP$99999,18,0)"

问题是我相信最后3行,或者它是如何读取X并将其放在那里。 VLOOKUPS的最后3行是错误的,除了现在R1C1的第一行实际上有效。我正在尝试其他版本的其他版本,但它们不起作用。

我宁愿不使用R1C1,但除非我使用它,否则它不想工作。

1 个答案:

答案 0 :(得分:1)

那么,您是否尝试在名称是所选路径的最后一部分的工作表上进行查找?

在您的查找之前添加一行msgbox x,这样您就可以确保按照您的意图计算x ...对我来说它返回了:

c:\path\[filename.xlsm

x的例子是什么? ...粘贴的3个公式是:

=VLOOKUP(RC11,'c:\path\[filename.xlsm]'!R3C2:R9846C49,13,0)
=VLOOKUP($E2,'c:\path\[filename.xlsm]'!$B$1:$AP$99999,41,0)
=VLOOKUP($E2,'c:\path\[filename.xlsm]shtName'!$B$1:$AP$99999,18,0)