简体   繁体   English

在vlookup公式上excel宏vba

[英]excel macro vba on vlookup formula

Hi I am new to excel macro. 嗨,我是excel宏的新手。 I wanted to create a macro for vlookup so that I can apply to many cells but it doesn't work. 我想为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

I wanted to look up a value in my current sheet to another sheet's range to return a unique value. 我想在当前工作表中查找一个值到另一个工作表的范围以返回唯一值。 Please help! 请帮忙! :) :)

Check this out. 看一下这个。

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

Just replace these 3 lines: 只需替换这3行:

wb.Activate
ws1.Select
Range("E1").Formula = "=+VLOOKUP(" & ws1.Range("C6") & "," & ws.Range("c7:d10") & ",2,FALSE)"

with this: 有了这个:

ws1.Range("E1").Formula = "=VLOOKUP(C6," & ws.Range("C7:D10").Address(External:=1) & ",2,FALSE)"

In the ws1.Range("C6") part the sheet and address are not needed, in this case, as the cell is in the same sheet where the formula goes so ws1.Range("C6") will always return C6 . ws1.Range("C6")部分中,不需要工作sheetaddress ,在这种情况下,由于单元格位于公式所在的同一工作表中,因此ws1.Range("C6")将始终返回C6

As for the ws.Range("c7:d10") part you need the "external reference" because it refers to another sheet. 对于ws.Range("c7:d10")部分,您需要“外部参考”,因为它引用另一个工作表。 Although the External reference of the Range.Address Property includes the filename, it gets dropped as the formula goes in the same workbook. 虽然Range.Address PropertyExternal引用包含文件名,但是当公式放在同一工作簿中时,它会被删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM