我需要使用vba进行vlookup的帮助,因为我无法在网络上找到解决方案 情况是我有三张纸
您可以参考这些图片以更好地理解
所以工作表1中的值是我的查找值,姓氏必须打印在工作表3中,表数组在工作表2中
我尝试过的代码是
Sub nameloopkup()
Dim name As String
Dim result As String
Dim myrange As Range
name = Worksheets("Sheet1").Range("B3").Value
myrange = Worksheets("Sheet2").Range("A:B").Value
result = Application.WorksheetFunction.VLookup(name, myrange, 2, False)
' the query does not run and i don't know how can i print the result in sheet 3
End sub
对于周围的许多人来说,这可能很简单。但是考虑到我对VBA的熟悉程度,我需要与此相关的一些指导。
任何帮助或建议都会受到赞赏。
答案 0 :(得分:0)
这里是您可以做的2 ...有2个选项,如果您只需要输入1个数据,或者您需要完整的数据数组并每次从中选择所需内容:
Option Explicit
Sub nameloopkup()
Dim C As Range, LastRow As Long, EmptyRow As Long, i As Long, arrData
Dim DictData As New Scripting.Dictionary 'You need to check Microsoft Scripting Runtime from references for this
Dim wsNames As Worksheet, wsTable As Worksheet, wsSurnames As Worksheet
'First thing, reference all your sheets
With ThisWorkbook
Set wsNames = .Sheets("Sheet1") 'change this as needed
Set wsTable = .Sheets("Sheet2")
Set wsSurnames = .Sheets("Sheet3")
End With
'Keep all the data in one dictionary:
With wsTable
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 'last row on Sheet2
i = .Cells(1, .Columns.Count).End(xlToLeft).Column 'last column on Sheet2
arrData = .Range(.Cells(1, 1), .Cells(LastRow, i)).Value 'keep the data on the array
'This will throw an error if there are duplicates
For i = 2 To UBound(arrData)
DictData.Add arrData(i, 1), i 'keep tracking of every name's position ' also change for arrData(i, 2) if you only need the surname
Next i
End With
With wsNames
LastRow = .Cells(.Rows.Count, 2).End(xlUp).Row 'last row on Sheet1
For Each C In .Range("B3:B" & LastRow)
EmptyRow = wsSurnames.Cells(wsSurnames.Rows.Count, 1).End(xlUp).Row
wsSurnames.Cells(EmptyRow, 2) = DictData(C.Value) 'if you used arrData(i, 2) instead i
wsSurnames.Cells(EmptyRow, 2) = arrData(DictData(C.Value), 2) 'If you used i
Next C
End With
End Sub
答案 1 :(得分:0)
myrange = Worksheets("Sheet2").Range("A:B").Value
result = Application.WorksheetFunction.VLookup(name, myrange, 2, False)
这是您的错误。 Vlookup
的第二个参数是范围,而不是字符串。由于范围是对象,因此还需要Set
:
Set myrange = Worksheets("Sheet2").Range("A:B")
result = Application.WorksheetFunction.VLookup(name, myrange, 2, False)
答案 2 :(得分:0)
Actuall所有您需要做的是:
Sub nameloopkup()
Dim Name As String
Dim Result As String
Dim SearchIn As Variant 'variant to use it as array
Name = Worksheets("Sheet1").Range("B3").Value
SearchIn = Worksheets("Sheet2").Range("A:B").Value 'read data into array
On Error Resume Next 'next line errors if nothing was found
Result = Application.WorksheetFunction.VLookup(Name, SearchIn, 2, False)
On Error Goto 0
If Result <> vbNullString Then
Worksheets("Sheet3").Range("B3").Value = Result
Else
MsgBox "Nothing found"
End If
End Sub
或者只是写一个公式:
Sub NameLookUpFormula()
Worksheets("Sheet3").Range("B3").Formula = "=VLOOKUP(Sheet1!B3,Sheet2!A:B,2,FALSE)"
End Sub