有关应用程序Vlookup的问题

我有两个文件中有不同的数据:

  1. wbTarget文件 – 我开始macros的一个
  2. wbSource文件 – 我selectfind它的一些值

我需要做什么的解释:

  1. 在wbTarget文件第2列中取第一个值
  2. 在wbSource文件的L列中find这个值
  3. 如果find – 从wbSource文件中取一个合适的值列并把它放到wbTarget列中

目前我有这样的代码:

Sub knew() Dim VipFile As String 'the file we choose Dim wbSource As Workbook 'vip file Dim wbTarget As Workbook 'this file Dim Rws As Long, Rng As Range, c As Range Dim finalrow_A As Integer Dim finalrow_D As Integer Dim i As Integer 'counter for values Application.DisplayAlerts = False 'turn blinking off. With Application.FileDialog(msoFileDialogFilePicker) .AllowMultiSelect = False .Title = "Select the file you saved as xlsx" .ButtonName = "Select" .InitialFileName = "C:\" If .Show = -1 Then 'ok clicked VipFile = .SelectedItems(1) Set wbTarget = ActiveWorkbook Set wbSource = Workbooks.Open(VipFile) finalrow_A = wbSource.Sheets(1).Cells(Rows.Count, 12).End(xlUp).Row finalrow_D = wbTarget.ActiveSheet.Cells(Rows.Count, 2).End(xlUp).Row For i = 1 To finalrow_D runner = wbTarget.ActiveSheet.Cells(i, 2).Value If Not Application.IsError(Application.VLookup(runner, wbSource.Sheets(1).Range("A1:M" & finalrow_A), 12, False)) Then wbTarget.Sheets(1).Range("A" & i) = Application.VLookup(runner, _ wbSource.Sheets(1).Range("A1:M" & finalrow_A), 1, False) End If Next i wbSource.Close End If End With Application.DisplayAlerts = True 'turn blinking back on. End Sub 

我在这里得到一个错误:

 finalrow_D = wbTarget.ActiveSheet.Cells(Rows.Count, 2).End(xlUp).Row 

并在vlookup部分的一些错误是可能的。

在这里输入图像说明

将感谢您的帮助! 非常感谢你!

我怀疑你的错误来自这样一个事实,一个工作簿是一个xlsx格式,另一个是xls,所以行数是不同的。 但是,更大的问题是, Vlookup在这里不起作用,因为查找值在数据表中要返回的值的右侧。 你需要使用Match来代替:

 Sub knew() Dim VipFile As String 'the file we choose Dim wbSource As Workbook 'vip file Dim wbTarget As Workbook 'this file Dim Rws As Long, Rng As Range, c As Range Dim finalrow_A As Long Dim finalrow_D As Long Dim i As Long 'counter for values Dim vMatch As Variant Dim runner Application.DisplayAlerts = False 'turn blinking off. With Application.FileDialog(msoFileDialogFilePicker) .AllowMultiSelect = False .Title = "Select the file you saved as xlsx" .ButtonName = "Select" .InitialFileName = "C:\" If .Show = -1 Then 'ok clicked VipFile = .SelectedItems(1) Set wbTarget = ActiveWorkbook Set wbSource = Workbooks.Open(VipFile) finalrow_A = wbSource.Sheets(1).Cells(wbSource.Sheets(1).Rows.Count, 12).End(xlUp).Row finalrow_D = wbTarget.ActiveSheet.Cells(wbTarget.ActiveSheet.Rows.Count, 2).End(xlUp).Row For i = 1 To finalrow_D runner = wbTarget.ActiveSheet.Cells(i, 2).Value vMatch = Application.Match(runner, wbSource.Sheets(1).Range("L1:L" & finalrow_A), 0) If Not IsError(vMatch) Then wbTarget.Sheets(1).Range("A" & i).Value = wbSource.Sheets(1).Range("A" & vMatch) End If Next i wbSource.Close End If End With Application.DisplayAlerts = True 'turn blinking back on. End Sub