简体   繁体   中英

excel macro vba on vlookup formula

Hi I am new to excel macro. I wanted to create a macro for vlookup so that I can apply to many cells but it doesn't work.

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:

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 .

As for the ws.Range("c7:d10") part you need the "external reference" because it refers to another sheet. Although the External reference of the Range.Address Property includes the filename, it gets dropped as the formula goes in the same workbook.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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