Share via

VBA Code to Wrap Formula in an =IF()?

Anonymous
2015-07-21T23:14:23+00:00

Hello,

I'm looking to use VBA to quickly insert the formula in my selected cell(s) in an =IF().

For example, if my cell formula is =[Formula], I want to change it to =IF( ([Formula] = 0), "", [Formula])

This is the code I have so far, but I keep getting a Run-Time Error '1004': Application-defined or object-defined error..


Sub Add_IF_Selection()

  Dim myCell As Range    

    For Each myCell In Selection.Cells

      If myCell.HasFormula And Not myCell.HasArray Then           

        myCell.Formula = "=IF(" & myCell.Formula & "=0,""," & myCell.Formula & ")"

      End If

  Next

End Sub


I think I'm very close or making a very silly mistake. Anyone know how I can solve this? Thanks!

Microsoft 365 and Office | Excel | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

Anonymous
2015-07-21T23:32:27+00:00

Hi Nitsuj5,

Try:

'=========>>

Sub Add_IF_Selection()

  Dim myCell As Range

  Dim sStr As String

    For Each myCell In Selection.Cells

      If myCell.HasFormula And Not myCell.HasArray Then

      sStr = Mid(myCell.Formula, 2)

         myCell.Formula = "=IF(" & sStr & "=0,""""," & sStr & ")"

      End If

  Next

End Sub

'<<=========

Note that you need to allow for the initial = sign and you need to double up internal quotes.

===

Regards,

Norman

Was this answer helpful?

3 people found this answer helpful.
0 comments No comments

4 additional answers

Sort by: Most helpful
  1. Anonymous
    2015-07-23T00:49:18+00:00

    Hi Nitsuj5,

    Thank you for your kind feedback.

    ===

    Regards,

    Norman

    Was this answer helpful?

    0 comments No comments
  2. Anonymous
    2015-07-22T16:31:04+00:00

    Thank you very much, it works! I didn't know there was a need to make a new string variable and use Mid().

    Was this answer helpful?

    0 comments No comments
  3. Anonymous
    2015-07-22T16:30:21+00:00

    I apologize as I lost the link to my question in the other forum and I assumed my question didn't get posted, so I asked it here. Won't happen again

    Was this answer helpful?

    0 comments No comments
  4. Anonymous
    2015-07-22T00:38:58+00:00

    Posted under "JHHui"  and answered (twice) in the "Visual Basic for Applications Forum".

    Was this answer helpful?

    0 comments No comments