我遇到了这种类型的错误,直到现在才能解决它。当我在VBA中使用VLookUp函数时会发生这种情况。
“无法获取WorksheetFunction类的VLookup属性”错误
这是我的完整代码:
Dim wbSLW as Workbook
Dim wbSLWDir as String
wbSLWDir = "C\Documents\test.xlsx" 'not constant directory
set wbSLW = Workbooks.Open(wbSLWDir)
Thisworkbook.Activate
With Thisworkbook.Sheets(1)
' line Error
.Range("AE2").Formula = _
WorksheetFunction.vlookUp(.Range("I2").Value, wbSLW.FullName & "Sheet3!E:F", 2, 0)
End With
你能帮我解决一下吗?
答案 0 :(得分:1)
Dim wbSLW As Workbook
Dim wbSLWDir As String
wbSLWDir = "C\Documents\test.xlsx" 'not constant directory
Set wbSLW = Workbooks.Open(wbSLWDir)
ThisWorkbook.Activate
With ThisWorkbook.Sheets(1)
'''To get only the value
.Range("AE2").Value = _
WorksheetFunction.VLookup(.Range("I2").Value, wbSLW.Sheets("Sheet3").Range("E:F"), 2, 0)
'''----OR-----
'''To insert the formula
''' Syntax : .Formula = _
"=VLOOKUP(Range-of-the-value-to-find" & _
",'Path[FileName.xl*]SheetName'!Range-of-Array-To-Search" & _
",Column-in-Array-to-output, FALSE)"
'''With a Range reference using .Address (btw If you change 0 to 1, you'll have a $)
.Range("AE2").Formula = _
"=VLOOKUP(" & .Range("I2").Address(0,0) & ",'" & wbSLW.Path & "\[" & wbSLW.Name & "]" & "Sheet3'!E:F, 2, FALSE)"
'''Or directly with address of the Range
.Range("AE2").Formula = _
"=VLOOKUP(I2,'" & wbSLW.Path & "\[" & wbSLW.Name & "]" & "Sheet3'!E:F, 2, FALSE)"
End With
答案 1 :(得分:0)
我发现在使用VBA输入公式时,首先在Excel中输入公式以确认它是否有效。如果test.xlsx已打开,那么在Sheet1 AE2中你将拥有
=VLOOKUP(I2,[test.xlsx]Sheet3!$E:$F, 2, 0)
如果test.xlsx已关闭,则公式为:
=VLOOKUP(I2,'C:\Documents\[test.xlsx]Sheet3'!$E:$F, 2, 0)
由于公式中没有双引号,您只需将其复制并粘贴到代码中即可:
.Range("AE2").Formula = "=VLOOKUP(I2, [test.xlsx]Sheet3!$E:$F, 2, 0)"
现在我们需要更改查找范围以引用您的wbSLW对象:
.Range("AE2").Formula = "=VLOOKUP(I2, [" & wbSLW.Name & "]Sheet3!$E:$F, 2, 0)"
请注意,您不需要引用wbSLW.FullName或wbSLW.Path,因为test.xlsx仍处于打开状态。关闭test.xlsx时,Excel将插入路径。
所以完整的代码:
Sub lookup()
Dim wbSLW As Workbook
Dim wbSLWDir As String
wbSLWDir = "C\Documents\test.xlsx" 'not constant directory
Set wbSLW = Workbooks.Open(wbSLWDir)
ThisWorkbook.Activate
With ThisWorkbook.Sheets(1)
.Range("AE2").Formula = "=VLOOKUP(I2,'[" & wbSLW.Name & "]Sheet3'!$E:$F, 2, 0)"
End With
End Sub