Results 1 to 5 of 5

Thread: VBA - Use variable from InputBox in formula?

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #2
    VBAX Sage
    Joined
    Apr 2007
    Location
    United States
    Posts
    8,888
    Location
    You need to construct the formulas a little differently:

    This is what you end with the way you have it

    "=IF(ISNUMBER(FIND(sReturn,RC[-1])),LEFT(RC[-1],FIND(sReturn,RC[-1])-1),"")"
    In VBA, you use 2 double quotes embed a double quote as a character in a string or use Chr(34)


    BTW, since I find building formulas a little finicky, I like to build the formula using a separate, testable variable (like sFormula below). It just seems easier to me

    Option Explicit
    Sub test()
        Dim sReturn As String, sFormula As String
        Dim i As Long
        Range("C3").Select
        i = 0
        sReturn = "ABCDEF"
        
        'wrong
        sFormula = "=IF(ISNUMBER(FIND(sReturn,RC[-1])),LEFT(RC[-1],FIND(sReturn,RC[-1])-1),"""")"
        Debug.Print 1 & " -- " & sFormula
        MsgBox sFormula
        
        'right (I think) :-)
        sFormula = "=IF(ISNUMBER(FIND(" & Chr(34) & sReturn & Chr(34) & ",RC[-1])),LEFT(RC[-1],FIND(" & Chr(34) & sReturn & Chr(34) & ",RC[-1])-1),"""")"
        Debug.Print 2 & " -- " & sFormula
        MsgBox sFormula
        
        
        'right (I think) :-)
        sFormula = "=IF(ISNUMBER(FIND(""" & sReturn & """,RC[-1])),LEFT(RC[-1],FIND(""" & sReturn & """,RC[-1])-1),"""")"
        Debug.Print 3 & " -- " & sFormula
        MsgBox sFormula
        
    End Sub


    Debug output:


    1 -- =IF(ISNUMBER(FIND(sReturn,RC[-1])),LEFT(RC[-1],FIND(sReturn,RC[-1])-1),"")
    2 -- =IF(ISNUMBER(FIND("ABCDEF",RC[-1])),LEFT(RC[-1],FIND("ABCDEF",RC[-1])-1),"")
    3 -- =IF(ISNUMBER(FIND("ABCDEF",RC[-1])),LEFT(RC[-1],FIND("ABCDEF",RC[-1])-1),"")
    Last edited by Paul_Hossler; 11-01-2018 at 01:19 PM.
    ---------------------------------------------------------------------------------------------------------------------

    Paul


    Remember: Tell us WHAT you want to do, not HOW you think you want to do it

    1. Use [CODE] ....[/CODE ] Tags for readability
    [CODE]PasteYourCodeHere[/CODE ] -- (or paste your code, select it, click [#] button)
    2. Upload an example
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) / Upload Files / Done
    3. Mark the thread as [Solved] when you have an answer
    Thread Tools (on the top right corner, above the first message)
    4. Read the Forum FAQ, especially the part about cross-posting in other forums
    http://www.vbaexpress.com/forum/faq...._new_faq_item3

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •