交叉工作簿Vlookup

时间:2017-09-29 08:44:59

标签: excel vba excel-vba

嘿伙计们试图通过跨工作簿执行vlookup。我试图用这种方式写它..但似乎没有使用" x"和" x2" ..

Folder = ActiveWorkbook.Path + "\"

Dim OptioneeManWb As Workbook
Dim TransOutWb As Workbook
Dim TransOutWs As Worksheet
Dim TermWb As Workbook
Dim TermWs As Worksheet

Set OptioneeManWb = Workbooks("optionee statement manual.xlsx")
Set TransOutWb = Workbooks.Open(Folder & "employee transfer out.xlsx")
Set x = TransOutWb.Worksheets("out").Range("A:C")
Set TermWb = Workbooks.Open(Folder & "employee terminated listing.xlsx")
Set x2 = TermWb.Worksheets("terminated").Range("A:C")


OptioneeManWb.Sheets("manual optionee stmt").Range("C6:C" & lastrow2).Formula = "=VLOOKUP(B:B,x,3,0)"
OptioneeManWb.Sheets("manual optionee stmt").Range("D6:D" & lastrow2).Formula = "=VLOOKUP(B:B,x2,3,0)"
OptioneeManWb.Sheets("manual optionee stmt").Range("C6:C" & lastrow2, "D6:D" & lastrow2).NumberFormat = "m/d/yyyy"
OptioneeManWb.Sheets("manual optionee stmt").Range("C:F").Copy
OptioneeManWb.Sheets("manual optionee stmt").Range("C:F").PasteSpecial xlPasteValues

TransOutWb.Close
TermWb.Close

2 个答案:

答案 0 :(得分:2)

VLOOKUP等待范围的地址作为第二个参数。

.Formula = "=VLOOKUP(B:B," & x.Address(External:=True) & ",3,0)"

在您的情况"=VLOOKUP(B:B,x,3,0)"中,x无法识别为变量,因为它位于字符串中。此外,您需要在此处填写地址(以外部格式填写,以便识别不同的工作簿)。另请参阅Range.Address Property (Excel)了解相关信息。

同时声明变量以确保过程顶部的类型为范围:Dim x As Range, x2 As Range

OptioneeManWb.Sheets("manual optionee stmt").Range("C6:C" & lastrow2).Formula = "=VLOOKUP(B:B," & x.Address(External:=True) & ",3,0)"
OptioneeManWb.Sheets("manual optionee stmt").Range("D6:D" & lastrow2).Formula = "=VLOOKUP(B:B," & x2.Address(External:=True) & ",3,0)"

答案 1 :(得分:0)

首先你必须像这样声明变量x和x2:

Dim x作为范围 将x2调为范围