嗨,我是excel宏的新手。我想为vlookup创建一个宏,以便我可以应用于许多单元格,但它不起作用。
Sub haha()
Dim wb As Workbook
Dim ws, ws1 As Worksheet
Set wb = ActiveWorkbook
Set ws = ActiveWorkbook.Sheets(1)
Set ws1 = ActiveWorkbook.Sheets(2)
wb.Activate
ws1.Select
Range("E1").Formula = "=+VLOOKUP(" & ws1.Range("C6") & "," & ws.Range("c7:d10") & ",2,FALSE)"
End sub
我想在当前工作表中查找一个值到另一个工作表的范围以返回唯一值。请帮忙! :)
答案 0 :(得分:2)
检查一下。
Sub haha()
Dim wb As Workbook
Dim ws As Worksheet, ws1 As Worksheet
Dim rng As Range
Set wb = ActiveWorkbook
Set ws = ActiveWorkbook.Sheets(1)
Set ws1 = ActiveWorkbook.Sheets(2)
wb.Activate
Set rng = ws.Range("c7:d10")
ws1.Range("E1").Formula = "=VLOOKUP(" & ws1.Range("C6").Address & "," & rng.Worksheet.Name & "!" & rng.Address & ",2,FALSE)"
End Sub
答案 1 :(得分:1)
只需替换这3行:
wb.Activate
ws1.Select
Range("E1").Formula = "=+VLOOKUP(" & ws1.Range("C6") & "," & ws.Range("c7:d10") & ",2,FALSE)"
用这个:
ws1.Range("E1").Formula = "=VLOOKUP(C6," & ws.Range("C7:D10").Address(External:=1) & ",2,FALSE)"
在ws1.Range("C6")
部分中,sheet
和address
不需要,在这种情况下,由于单元格位于公式所在的同一工作表中,因此ws1.Range("C6")
将始终返回C6
。
对于ws.Range("c7:d10")
部分,您需要“外部参考”,因为它引用了另一张表。虽然External
的{{1}}引用包含文件名,但当公式放在同一工作簿中时,它会被删除。