跨越同一工作簿中的多个工作表的Vlookup VBA代码

时间:2017-09-26 12:14:45

标签: excel-vba vba excel

我对编码比较新,因此需要一些帮助。

我有一个包含多个工作表的工作簿,其中包含A和A列中的名称。 B栏中的地址。

我正在尝试执行以下操作:

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

出现在任何其他工作表(A到Z)上,然后

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

匹配

的单元格旁边
worksheets("Input").Range("A1").Value

即.-

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

任何人都可以解释我如何在vba中执行此操作而不必在每个工作表中使用大量的IF?

由于

安德鲁

1 个答案:

答案 0 :(得分:0)

我已经用一个小例子测试了它,其中有一个输入'工作表和另外两个工作表(在您的情况下为A和B)布局类似于sheet_input-beforeSheet-input_aftersheet-Asheet-B {{1}的循环}从输入表的A列的第2行开始...

vlookup

更新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

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
相关问题