简体   繁体   中英

VBA Code for Vlookup across multiple worksheets within the same workbook

I'm relatively new to coding, therefore require some assistance.

I have a workbook with multiple worksheets, which hold Names in column A & addresses in column B.

I am attempting to do the following:

If worksheets("Input").Range("A1").Value

is present on any of the other worksheets (A to Z) then

worksheets("Input").Range("B1").Value = Cell.value

that is next to cell that matches

worksheets("Input").Range("A1").Value

ie-

if worksheet("B").Range("A1").Value = worksheets("Input").Range("A1").Value,  
   then worksheets("Input").Range("B1").Value = worksheet("B").Range("B1").Value

Can anyone explain how I would do this in vba without having to use a lot of IFs per worksheet?

Thanks

Andrew

I have tested it with a small example with one 'input' sheet and two other sheet (A and B as in you case) the layout is something like thissheet_input-before , 工作表input_after , 表A , 表-B the loop for vlookup starts for the 2nd row of the column A of input sheet...

Sub foo()

Dim wks As Worksheet
Dim wkb As Workbook
Dim key As String
Dim rowIndex As Integer
Dim wksName As Variant
Dim LastRow As Integer


Set wkb = ThisWorkbook

With wkb.Sheets("Input")
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row ' totol number of entries in col A of input sheet
End With

' for each name in input sheet's column-A search the name in all sheets other then input sheet
For rowIndex = 2 To LastRow Step 1
  key = wkb.Worksheets("Input").Cells(rowIndex, 1).Value ' name to search
    For Each wks In wkb.Worksheets ' loop through all the sheets
        If Not wks.Name = "Input" Then ' avoid searching in input sheet itself
          On Error Resume Next ' to search next sheet when not found in current one
          wkb.Worksheets("Input").Cells(rowIndex, 2).Value = Application.WorksheetFunction.VLookup(key, wks.Range("A:B"), 2, False)
       End If
    Next wks
Next rowIndex

End Sub

update 1 >

Sub foo()

Dim wks As Worksheet
Dim wkb As Workbook
Dim key As String
Dim rowIndex As Integer
Dim wksName As Variant
Dim LastRow As Integer


Set wkb = ThisWorkbook



' for name in input sheet's A1 cell, search the name in all sheets other then input sheet

  key = wkb.Worksheets("Input").Range("A1").Value ' name to search
    For Each wks In wkb.Worksheets ' loop through all the sheets
        If Not wks.Name = "Input" Then ' avoid searching in input sheet itself
          On Error Resume Next ' to search next sheet when not found in current one
          wkb.Worksheets("Input").Range("B1").Value = Application.WorksheetFunction.VLookup(key, wks.Range("A:B"), 2, False)
       End If
    Next wks

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM