简体   繁体   中英

VBA Run-time Error 1004 for Special Characters in Soft-coded Vlookup Function

When I was trying to throw a vertical bar "|" into my vlookup function, I got a 1004 error. I am not sure where it came from.

Initially the data table looks like this:

原版的

And my code was like this:

Sheets("Sheet 1").Cells(i, 2).Formula = "=VLOOKUP($A" & i & ",Data!$A$1:$B$" & LastRow & "," & ColmNum & ",0)"

Everything worked fine till the format of the data table got changed to:

新格式

So I had to throw the vertical bar "|" into my code. My new code was like this:

NewKey = Sheets("Sheet 1").Cells(i, 1).Value & "|" & Sheets("Data").Cells(i, 2).Value
Sheets("Sheet 1").Cells(i, 3).Formula = "=VLOOKUP(" & NewKey & ",Data!$A$1:$B$" & LastRow & "," & ColmNum & ",0)"

Apparently Excel 2010 did not like my codes and threw me a 1004 error. I am wondering if anyone knows a solution to this. Thank you in advance for your help.

NewKey needs to be in quotes when the formula is placed on the sheet, so you need to include the quotes in the string:

NewKey = Sheets("Sheet1").Cells(i, 1).Value & "|" & Sheets("Sheet1").Cells(i, 2).Value
Sheets("Sheet1").Cells(i, 3).Formula = "=VLOOKUP(""" & NewKey & """,Data!$A$1:$B$" & LastRow & "," & ColmNum & ",0)"

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