我正在尝试使用不同工作簿中的表格在VBA中执行VLOOKUP。
我试过了:
width = Application.VLookup(code, Workbooks("T:\Data\Dimensions.xlsx").Sheets("Main").Range("A61:G1500"), 7, False)
其中code
是我已设置的变量,但它只返回“下标超出范围”。
我确定你可以看到我正在尝试做什么,但我猜我在vlookup中的语法错误。
感谢。
答案 0 :(得分:1)
确保打开目标工作簿。试试这个:
Set src = Workbooks.Open("T:\Data\Dimensions.xlsx")
width = Application.VLookup(code, src.Sheets("Main").Range("A61:G1500"), 7, False)
答案 1 :(得分:0)
下面的代码有点长,但它会逐步完成,定义和设置所有对象(请参阅代码本身中的注释)。
您还需要处理Vlookup
无法在指定的code
中找到Range
的方案,
<强> 代码 强>
Option Explicit
Sub VlookupClosedWorkbook()
Dim Width, code
Dim WorkbookName As String
Dim WB As Workbook
Dim Sht As Worksheet
Dim Rng As Range
WorkbookName = "Dimensions.xlsx"
' set the workbook object
On Error Resume Next
Set WB = Workbooks(WorkbookName) ' first try to see if the workbook already open
On Error GoTo 0
If WB Is Nothing Then ' if workbook = Nothing (workbook is closed)
Set WB = Workbooks.Open("T:\Data\" & WorkbookName)
End If
' set the worksheet object
Set Sht = WB.Sheets("Main")
' set the Range object
Set Rng = Sht.Range("A61:G1500")
' verify that Vlookup found code in the Range
If Not IsError(Application.VLookup(code, Rng, 7, False)) Then
Width = Application.VLookup(code, Rng, 7, False)
Else
MsgBox "Vlookyp Error finding " & code
End If
End Sub
答案 2 :(得分:-1)
您必须打开该工作簿或使用单元格从关闭的工作簿中获取值
range("A1").formula = "=vlookup(" & code & ",'T:\Data\[Dimensions.xlsx]Main'!A61:G1500,7,0)"
range("A1").calculate
width = range("A1").value