Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to break up a long formula in VBA?

I have a macro that’s adding a very long formula to one of the cells.

I’m wondering if there’s a way to break this formula up in the VBA editor up to make it easier to view and edit for other users the road.

Here’s the code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Sheet3.Select

Dim lastrow As Long

    Range("D2").Formula = "=SUM(IFERROR(VLOOKUP(E2,Scores[[Values]:[Score]],2,FALSE),0)+IFERROR(VLOOKUP(H2,Scores[[Values]:[Score]],2,FALSE),0)+IFERROR(VLOOKUP(I2,Scores[[Values]:[Score]],2,FALSE),0)+IFERROR(VLOOKUP(J2,Scores[[Values]:[Score]],2,FALSE),0)+IFERROR(VLOOKUP(K2,Scores[[Values]:[Score]],2,FALSE),0)+IFERROR(VLOOKUP(L2,Scores[[Values]:[Score]],2,FALSE),0)+IFERROR(VLOOKUP(M2,Scores[[Values]:[Score]],2,FALSE),0))"
    Range("D2").AutoFill Destination:=Range("D2:D" & lastrow), Type:=xlFillDefault

It looks like this:

I’m trying to get it to look more like this:

A space and underscore didn’t work.

I could add a carriage return but that just adds it to the formula, I’m trying to make it easier to view inside the VBA editor.

I’ve also tried yelling at it but that hasn’t worked either.

I’m wondering if some kind of CONCAT might do it? I’m pretty new to VBA (this is someone else’s work that I’m modifying) so I’m not too well versed in what options are available.

Appreciate any insights!

>Solution :

The simple, direct answer is to build your formula first, by itself. Below is an artificial and contrived example but it should show the main idea.

Clearly you might better find a different way to write that formula as it seems repetitive which might mean there are ways to improve it, but I thought to start with this basic answer to your question about what your were trying to do that wasn’t working.

dim myFormula as string
myFormula = "=SUM("
myFormula = myFormula & "A2"
myFormula = myformula & ",B2"
myFormula = myFormula & ",C2"
myFormula = myFormula & ")"

This will also work in VBA if you prefer to use line continuations:

Dim myFormula As String
myFormula = _
    "=SUM(A2" _
    & ",B2" _
    & ",C2" _
    & ")"

Range("A3").Formula = myFormula
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading