简体   繁体   English

使用列名而不是数字在 VLOOKUP function 中使用 VBA 返回一个值

[英]Use column name instead of a number to return a value in the VLOOKUP function using VBA

I've managed to write a Vlookup function that works perfectly across multiple sheets using VBA.我已经设法编写了一个 Vlookup function,它使用 VBA 在多张纸上完美运行。

However, I have to deal with new workbooks weekly so I'm having to slightly alter my code to ensure the Vlookup in my macro pulls data from the correct columns as these can change.但是,我必须每周处理新的工作簿,因此我必须稍微更改我的代码,以确保我的宏中的 Vlookup 从正确的列中提取数据,因为这些可能会发生变化。

My code is:我的代码是:

Set my_sheet1 = ThisWorkbook.Worksheets("Sheet1") 
Set my_sheet2 = ThisWorkbook.Worksheets("Sheet2") 

last_row = my_sheet1.Range("A" & Rows.Count).End(xlUp).Row 
last_row1 = my_sheet2.Range("A" & Rows.Count).End(xlUp).Row

Set dataRange = my_sheet2.Range("A2:BA" & last_row1) '//range for data in second worksheet that Vlookup will use to locate third column

On Error Resume Next

  For x = 2 To last_row1

  my_sheet1.Range("D" & x).Value = Application.WorksheetFunction.VLookup(my_sheet1.Range("A" & x).Value, dataRange, 3, 0) 

  Next x

So this VLOOKUP pulls data from Column 3 ("Worker_Name") in Sheet2 into Column D on Sheet1.因此,此 VLOOKUP 将 Sheet2 中的第 3 列(“Worker_Name”)中的数据提取到 Sheet1 的 D 列中。

Is it possible to use "Worker_Name" instead of 3 in my VLOOKUP?是否可以在我的 VLOOKUP 中使用“Worker_Name”而不是 3? Or do I have to use another function such as MATCH?还是我必须使用另一个 function 例如 MATCH?

You can use Match()您可以使用Match()

Sub Tester()
    
    Dim my_sheet1 As Worksheet, my_sheet2 As Worksheet
    Dim last_row1 As Long, last_row2 As Long, x As Long
    Dim DataRange As Range, colHeader As String, m, res
    
    Set my_sheet1 = ThisWorkbook.Worksheets("Sheet1")
    Set my_sheet2 = ThisWorkbook.Worksheets("Sheet2")
    
    last_row1 = my_sheet1.Range("A" & Rows.Count).End(xlUp).Row
    last_row2 = my_sheet2.Range("A" & Rows.Count).End(xlUp).Row
    
    Set DataRange = my_sheet2.Range("A2:BA" & last_row2)
    
    colHeader = "Worker_Name"  'column to return results from
    
    'find the column position
    m = Application.Match(colHeader, DataRange.Rows(1), 0)
    
    If Not IsError(m) Then      'got a match?
        For x = 2 To last_row1
            'use the found column
            res = Application.VLookup(my_sheet1.Range("A" & x).Value, DataRange, m, False)
            my_sheet1.Range("D" & x).Value = IIf(IsError(res), "", res) 'check for no match
        Next x
    Else
        MsgBox "Column header '" & colHeader & "' not found", vbExclamation
    End If
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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