【发布时间】:2015-09-11 12:55:05
【问题描述】:
我有两个单独的工作簿,其中包含数据。我正在尝试使用 vlookup 查找单元格值匹配项。
工作簿 1 中的列包含字母数字数据,与工作簿 2 中的列进行比较。
我有以下代码来尝试确定匹配项:
Sub VirtualHostLookUp()
'TO DO: iterate through all required workbooks and do lookup
'open the workbook of interest
'Workbooks.Open ("C:\Documents and Settings\1147808\My Documents\Pete\Data\tester.xlsx")
'define this workbook
Dim campus As Workbook
Set campus = Workbooks(1)
'define the lookup range - currently opens the first second open workbook
Dim rng As range
If Workbooks.Count > 1 Then
With Workbooks(2)
Set rng = .Worksheets(2).UsedRange
End With
End If
'initialise starting point
Dim currRow, currCol As Integer
currRow = 3
currCol = 19
'get first value to compare
Dim currVal As Variant
currVal = Cells(currRow, currCol).Value
'find the number of rows in the column
Dim totalRows As Long
With campus.Worksheets(1)
totalRows = .Cells(.Rows.Count, "S").End(xlUp).Row
End With
campus.Activate
'iterate through the rows
For i = currRow To totalRows
Dim cell As Variant
Set cell = campus.Worksheets(1).Cells(currRow, currCol + 2)
If currVal <> Empty Then
cell.Value = Application.VLookup(currVal, rng, 2, False)
If Not IsError(cell.Value) Then
If cell.Value = Empty Then
cell.Value = "MATCH"
End If
End If
End If
'cell.Value = ""
currRow = currRow + 1
currVal = Cells(currRow, currCol).Value
Next
End Sub
我知道两列之间存在匹配,但总是返回值“#N/A”,我不知道为什么?
我已将范围定义为 Workbook2 中的 UsedRange,这可以正常工作并返回正确的值。要匹配的数据在 Workbook 2 的第 2 列中。
我做错了什么?!?!
【问题讨论】:
-
currVal 定义在哪里?
-
for 循环上方 - 现在已添加整个子例程(见上文)
-
currVal = Cells(currRow, currCol).Value您应该始终使用特定的工作表参考来限定Cells()。您可能没有得到正确的currVal值 -
我已经调试并在那里放置了一个断点,它被分配了正确的值!
-
是您尝试与 UsedRange 中最左边的列匹配的列吗?