+ Reply to Thread
Results 1 to 3 of 3

putting an if statement into a cell

Hybrid View

  1. #1
    Registered User
    Join Date
    01-10-2013
    Location
    New York
    MS-Off Ver
    Excel 2010
    Posts
    21

    putting an if statement into a cell

    Hi All,

    I am struggling with a piece of code. I am trying to put an if statement into a cell as part of a larger macro. My active cell is Q2 and I am trying to place a formula into the active cell. If I were to type the if statement into excel I would want it to read below:

    if(M2=1,"X",if(M2=2,"Y","Z"))

    I am struggling with the syntax needed to input this formula.

    Thanks in advance for the help!

  2. #2
    Valued Forum Contributor
    Join Date
    11-20-2012
    Location
    Seattle, WA USA
    MS-Off Ver
    Excel 2010
    Posts
    597

    Re: putting an if statement into a cell

    activecell.formula = "=if(M2=1,""X"",if(M2=2,""Y"",""Z""))"

    you need double quotes around the values you are looking for

  3. #3
    Registered User
    Join Date
    10-27-2012
    Location
    London
    MS-Off Ver
    Excel 2007-2010
    Posts
    59

    Re: putting an if statement into a cell

    Double quotes is the key.

    Sub InsertIF()
    ActiveSheet.Range("Q2").Value = "=if(M2=1,""X"",if(M2=2,""Y"",""Z""))"
    End Sub

    Alternatively you can use the FormulaR1C1 syntax:
    ActiveCell.FormulaR1C1 = "=IF(RC[-4]=1,""X"",IF(RC[-4]=2,""Y"",""Z""))"

    Or you can write the If statement into the VB code:
    Sub IfVBA()
    If ActiveSheet.Range("M2").Value = "1" Then
    ActiveSheet.Range("Q2").Value = "X"
    ElseIf ActiveSheet.Range("M2").Value = "2" Then
    ActiveSheet.Range("Q2").Value = "Y"
    Else
    ActiveSheet.Range("Q2").Value = "Z"
    End If
    End Sub
    Last edited by Break_Point; 02-27-2013 at 06:15 PM.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

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

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1