我有一个Sub
,可以在Excel中为整列执行vlookup
。
Option Explicit
Sub Vlookup() ' performs Vlookup of all entries in sheet1 with keys from sheet2
Dim wbk1 As Workbook
Set wbk1 = ActiveWorkbook ' wbk1 is master table
With wbk1.Sheets("sheet1") 'define sheet in master table
.Range("AA2:AA" & .Range("C" & .Rows.Count).End(xlUp).Row).Formula = _
"=VLOOKUP(C2,sheet2!$A$2:$B$14,2,FALSE)" 'Actual vlookup
End With
End Sub
vlookup本身效果很好。但是,生成的列AA:AA
缺少标题。
如何使用VBA将名称(字符串)分配给空的Excel列标题?
答案 0 :(得分:1)
请检查一下:
选项明确
Sub Vlookup() ' performs Vlookup of all entries in sheet1 with keys from sheet2
Dim wbk1 As Workbook
Dim lastRow As Long
Set wbk1 = ActiveWorkbook ' wbk1 is master table
With wbk1.Sheets("sheet1") 'define sheet in master table
lastRow = .Range("C" & .Rows.Count).End(xlUp).Row
.Range("AA2:AA" & lastRow).Formula = _
"=VLOOKUP(C2,sheet2!$A$2:$B$14,2,FALSE)" 'Actual vlookup
.Range("AA1").Value = Sheet2.Range("b1").Value
End With
End Sub