简体   繁体   中英

How to use vlookup (the formula) to search for string in VBA

Hi everyone I have a problem with VBA when I try to use vlookup formula like this:

Range("H21").Formula = "=VLOOKUP("cleared",'mortgage'!A2:F12,4,FALSE)"

it keeps telling me the part "cleared" is an syntax error. Can someone tell me how to deal with that? Thank you in advance.

双引号:

Range("H21").Formula = "=VLOOKUP(""cleared"",'mortgage'!A2:F12,4,FALSE)"

Your VBE thinks the word cleared is not part of the string as you've terminated it with double-quotes beforehand . You then appear to be starting a new string immediately after the word cleared.

To use double quotes (aka speech-marks) within a string, you'll need to double them up like so:

Range("H21").Formula = "=VLOOKUP(""cleared"",'mortgage'!A2:F12,4,FALSE)"

Use single quotes around cleared (DOES NOT WORK) :

Range("H21").Formula = "=VLOOKUP('cleared','mortgage'!A2:F12,4,FALSE)"

EDIT : Correction made by OP :

Excel uses single quotes only on the sheet name, not to denote a string literal

Or another option:

  1. Write the working formula in Excel.
  2. Select the cell with the formula.
  3. Run the following code:

Sub TestMe
     debug.print selection.formula
End Sub

  1. Check the immediate window - that's the formula you are using in Excel.
  2. If you want useful formula, that you can actually copy+paste in your VBA code, use this:

Option Explicit

Public Sub PrintMeUsefulFormula()

    Dim strFormula  As String
    Dim strParenth  As String

    strParenth = """"

    strFormula = Selection.Formula
    strFormula = Replace(strFormula, """", """""")

    strFormula = strParenth & strFormula & strParenth
    Debug.Print strFormula

End Sub

  1. Check the immediate window.

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