VBA vlookup 具有定义的范围和其他工作簿中的文件

标签 vba excel

我正在处理工作簿"file"。然后,我打开另一个工作簿(Masterfile),用于查找数据。

Workbooks.Open FileName:=Path & Masterfile

lRowMasterfile = Cells(Rows.Count, "A").End(xlUp).Row
SelectionMasterfile = Range("A1").CurrentRegion.Address

Workbooks(File).Activate

Range("K2").FormulaR1C1 = "=VLOOKUP(RC[-1],'" & Masterfile"' & ! & SelectionMasterfile,1, FALSE)"

Range("K2").AutoFill Destination:=Range("K2:K" & lRowFile)

Workbooks(Masterfile).Close

我定义了 Masterfile 和 Range 以在其他文档中使用它,但不幸的是它不起作用。有人可以帮忙吗?

最佳答案

您处理工作簿就像处理工作簿中的工作表一样。指定外部工作簿很重要,但您要从中检索信息的外部工作簿中的工作表也很重要。

幸运的是,Range.Address property可以通过指定可选的外部参数来处理很多事情。

Dim mwb As Workbook
Dim lRowMasterfile As Long, lRowFile As Long, SelectionMasterfile As String
Dim Path As String, Masterfile As String, File As String

Path = ThisWorkbook.Path            '<~~ set this properly!
Masterfile = "MasterWorkbook.xlsx"  '<~~ set this properly!
File = ActiveWorkbook.Name  '<~~ set this properly!

Set mwb = Workbooks.Open(Filename:=Path & Masterfile)

With mwb
    With .Worksheets("Sheet1")    '<~~ what worksheet are you trying to get information from?!?
        lRowMasterfile = .Cells(Rows.Count, "A").End(xlUp).Row
        SelectionMasterfile = .Range("A1").CurrentRegion.Address(ReferenceStyle:=xlR1C1, external:=True)
    End With
End With

With Workbooks(File)
    With .Worksheets("Sheet1")    '<~~ what worksheet are you trying to put information into?!?

        lRowFile = 0   '<~~ set this properly!

        'this VLOOKUP only checks to see if the value exists, it doesn't lookup anything but the first column
        'in any event, you can put them all in at the saame time
        .Range("K2:K" & lRowFile).FormulaR1C1 = _
            "=VLOOKUP(RC[-1], " & SelectionMasterfile & ", 1, FALSE)"

    End With
End With

mwb.Close False
Set mwb = Nothing

有很多缺失的信息,但如果您正确分配了所有变量,这应该是一个很好的入门框架。

关于VBA vlookup 具有定义的范围和其他工作簿中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32148792/

相关文章:

Excel 行混合

vba - 范围问题

excel - 如何在vba上输入用户决定的变量值?

java - Java计算Excel某列重复行数

sql - 将 Excel 数据导入 PostgreSQL 9.3

ms-access - 以编程方式重命名 access 中的列

Excel Geomean 返回#value!有时?

function - 在递归函数中使用 .Find

excel - 如何根据月份检查单元格的范围/列并复制它们

excel - 从文本字符串中提取最后一个数字