VLOOKUP Formula places Apostrophe in front of text

2019-08-23 02:58发布

问题:

I am writing a macro which inserts some formulas into a column array. I am trying to automate a weekly process, so the input files are variable and are selected through the msoFileDiaglogFilePicker application.

Dim wb_Final As Workbook, nameFinal As String
Set wb_Final = Workbooks.Open(Filename:=Final_Directory)
nameFinal = wb_Final.Name



Dim wb_Summary As Workbook, nameSummary As String
Set wb_Summary = Workbooks.Open(Filename:=Summary_Directory)
nameSummary = wb_Summary.Name

wb_Summary.Sheets("Sheet 1").Activate
With Sheets("Sheet 1")
.Range("AT4:AT5000").Formula = "=IF(OR(AX1=""Open"",AX1=""Won"",AX1=""Won - Pending""),""Yes"",""No"")"
.Range("AU4:AU5000").Formula = "=VLOOKUP(W:W,LOVs!H:I,2,FALSE)"
.Range("AV4:AV5000").Formula = "=IF(IFERROR(VLOOKUP($A:$A,'[" & nameFinal & "]DATA'!$A:$AK,34,FALSE),0)=0,"",VLOOKUP($A:$A,'[" & nameFinal & "]DATA'!$A:$AK,34,FALSE))"
.Range("AW4:AW5000").Formula = "=IF(IFERROR(VLOOKUP($AV:$AV,'[" & nameFinal & "]DATA'!$AH:$CX,48,FALSE),0)=0,"",VLOOKUP($AV:$AV,'[" & nameFinal & "]DATA'!$AH:$CX,48,FALSE))"
'....More formulas similar to above
End With

The first two formulas get placed into the cells and compute with no problem.

The third formula gets placed into the cells as a text with an apostrophe in the front of it in excel. (i.e. '=IF(IFERROR(VLOOKUP...)

The fourth formula generates a Run-time error '1004'

I have tried all the different formula types:

.Formula .FormulaR1C1 .FormulaLocal .FormulaR1C1Local

And still receive the same error.

I think I am experiencing a similar issue as stated in this article, but I'm not if I can use the Application.Vlookup function without redefining all the arrays and column references in my current VLOOKUP functions (which would take a VERY long time).

Any help would be much appreciated

回答1:

You cannot use apostrophes in formulas; instead use quotation marks, and in your case, you'll need to escape it like you did in your prior formulas, example:

VLOOKUP($A:$A,""[" & nameFinal & "]DATA""!$A:$AK,34,FALSE)


回答2:

Try

With Worksheets("Sheet 1") '>== or Sheet1 depending on actual name
    .Range("AW4:AW5000").Formula = "=IF(IFERROR(VLOOKUP($AV:$AV,[" & nameFinal & "]DATA!$AH:$CX,48,FALSE),0)=0,"""",VLOOKUP($AV:$AV,[" & nameFinal & "]DATA!$AH:$CX,48,FALSE))"
End With