How to break up a long formula in VBA? - excel

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:
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!

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 & ")"
Range("A3").Formula = 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

'Split' a Long Formula
Option Explicit
Sub WriteFormula()
Const LastRow As Long = 20 ' just to make it compile
Dim Formula As String: Formula = "" _
& "=IFERROR(VLOOKUP(E2,Scores[[Values]:[Score]],2,FALSE),0)" & vbLf _
& "+IFERROR(VLOOKUP(H2,Scores[[Values]:[Score]],2,FALSE),0)" & vbLf _
& "+IFERROR(VLOOKUP(I2,Scores[[Values]:[Score]],2,FALSE),0)" & vbLf _
& "+IFERROR(VLOOKUP(J2,Scores[[Values]:[Score]],2,FALSE),0)" & vbLf _
& "+IFERROR(VLOOKUP(K2,Scores[[Values]:[Score]],2,FALSE),0)" & vbLf _
& "+IFERROR(VLOOKUP(L2,Scores[[Values]:[Score]],2,FALSE),0)" & vbLf _
& "+IFERROR(VLOOKUP(M2,Scores[[Values]:[Score]],2,FALSE),0)"
'Debug.Print Formula
Sheet3.Range("D2:D" & LastRow).Formula = Formula
End Sub
Result in the Formula Bar For Cell D2
=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)

Related

Object Defined Error 1004 and Formula won't come out

Got a code from a member here (thanks a lot), but got an error with Pop-out error code 1004 on
With wsTarget
.Range("A6").FormulaR1C1 = strFormulaCOA
.Range("D6").FormulaR1C1 = strFormulaStatus
End With
Any idea to fix the problem?
I try to give "" between the strFormulaCOA resulting the code to just insert strFormulaCOA word on the destinated range. Another thing, I also try to change the FormulaR1C1 to value and formula but still no good.
here's the code I use
Option Explicit
Sub insertCOAandStatusFormulas()
'Pattern of each formula part - $1 as placeholder for sheetname
Dim strPartCOA As String, strPartStatus As String
strPartCOA = "IFERROR(INDEX('$1'!R6C:R2000C,MATCH(RC3,'$1'!R6C3:R2000C3,0)),INDEX('$1'!R6C:R2000C,MATCH(RC3,'$1'!R6C5:R2000C5,0)) "
strPartStatus = "IFERROR(VLOOKUP(RC3,'$1'!R6C3:R2000C12,4,0),VLOOKUP(RC3,'$1'!R6C5:R2000C12,2,0) "
Dim wsTarget As Worksheet
Dim wsTarget2 As Worksheet
Set wsTarget = ThisWorkbook.Worksheets("Rekap Capex") '--> adjust this to your needs
Set wsTarget2 = ThisWorkbook.Worksheets("Depreciation")
'build sheet-specific part per formula
Dim strFormulaCOA As String, strFormulaStatus As String
Dim cntSheets As Long, i As Long
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If Not ws.Name = wsTarget.Name And Not ws.Name = "Depreciation" Then
strPartCOA = strFormulaCOA & Replace(strPartCOA, "$1", ws.Name) & vbCrLf
strPartStatus = strFormulaStatus & Replace(strPartStatus, "$1", ws.Name) & vbCrLf
cntSheets = cntSheets + 1
End If
Next
'add equal-sign, remove last comma and add closing brackets
strFormulaCOA = "=" & strPartCOA & String(cntSheets, ")")
strFormulaStatus = "=" & strPartStatus & String(cntSheets, ")")
With wsTarget
.Range("A6").FormulaR1C1 = strFormulaCOA
.Range("D6").FormulaR1C1 = strFormulaStatus
End With
End Sub
Edit:
Below is the target of the formula (the blank cells) in which I want to add index match and vlookup formula
the problem is that the sheet of the data is not always the same, as we know that vlookup and index match formula need to state the sheet name(the first and second sheet always the same).
this is what my vlookup formula looks like
this is what my index match formula looks like
First of all I highly recommended to use formulas A1 instead R1C1 because it's easyly to understand. To insert in this formula a listname follow the example:
fformula = "=FormulaExample(" & Chr(39) & lst1 & Chr(39) & "!$B$3:$B$" & (n + 3) & "," & Chr(39) & lst1 & Chr(39) & "!L3:L" & (n + 3) & ",$C$2,$D$2,$E$2,$F$2,$B$7," & Chr(39) & lst1 & Chr(39) & "!$AA$3:$AA$" & (n + 3) & ")"
where lst1 = "listexample"
chr(int) returns an ASCII symbol
chr(39) returns dot
Remember that formula inserts with "," instead of ";" (A1,B1 not A1;B1)
That code will be like this:
=FormulaExample('listexample'!$B$3:$B$88000;'listexample'!L3:L88000;$C$2;$D$2;$E$2;$F$2;$B$7;'listexample'!$AA$3:$AA$88000;J2)
And to insert:
with wsTarget:
.Range("A1").Formula = fformula
Please edit your code with A1 code style or give me a picture of sheet/file and I will help you to code

Loop Variable inside a Formula Function

I am looping thru a column in which i need to add one to the loop variable within the FORMULA
My problem is how to write the correct FORMULA to go to the next cell using the lrow variable
Attached is a snippet of my code
Dim LastRow As Long
For lrow = 1 To 20
If Worksheets("cars").Range("P" & lrow) = "1" Then
Worksheets("cars").Range("a" & lrow).Formula = _
"=RIGHT(h & lrow ,FIND(""."",h & lrow))"
How do i concatenate the lrow variable within the formula ?
I have also tried "=RIGHT("h" & lrow ,FIND(""."","h" & lrow))"
Sometimes using Replace() can avoid a lot of concatenation and quote-balancing:
Worksheets("cars").Cells(lrow, "A").Formula = _
Replace("=RIGHT(H<rw>,FIND(""."",H<rw>))", "<rw>", lrow)
You can build the string, inserting the variables where necessary.
Worksheets("cars").Range("a" & lrow).Formula = _
"=RIGHT(h" & lrow & ",FIND(""."",h" & lrow & "))"
Note the extra quotation marks and (ampersands) that I have placed to expose the variable from the rest of the string.

Excel VBA - Passing a Dynamic Range to a Function

I created a function in Excel VBA:
Function codeList(Criteria As String, LookupRange As Range, ValueRange As Range, delimiter As String)
It works great when I pass hard coded ranges to it like this:
ActiveCell.FormulaR1C1 = "=codelist(RC[2],R2C4:R84C4,R2C3:R84C3,"","")"
I would like the rows to be dynamic, so instead of saying C2:C84 or D2:D84 I would like to make the C84 / D84 vary based on the number of columns that have data.
I tried to compute the last row and concatenate the ranges to make them dynamic when I call the function, but I get a compile syntax error :
Dim lastRow As Long
lastRow = Range("C" & Rows.Count).End(xlUp).Row
ActiveCell.FormulaR1C1 = "=codelist(RC[2],"R2C4:R" & lastrow &"C4", "R2C3:R" & lastrow & "C3"),"","")"
Any suggestions on how to make this work?
When you want to include double quotes inside a string, you have to use two double quotes to escape them.
ActiveCell.FormulaR1C1 = "=codelist(RC[2],R2C4:R" & lastRow & "C4, R2C3:R" & lastRow & "C3,"""")"
The four double quotes near the end convert to two double quotes (the empty string your looking for).
This way is longer, but I tend to use offsets in formulas. I find it easier to read than trying to determine where the strings begin and end
Const DBLQTE As String = """"""
ActiveCell.FormulaR1C1 = "=codelist(RC[2]," & _
Range("D2").Resize(lastRow - 1).Address(, , xlR1C1) & _
"," & _
Range("C2").Resize(lastRow - 1).Address(, , xlR1C1) & _
"," & _
DBLQTE & _
")"
Update
For a comma delimeter
ActiveCell.FormulaR1C1 = "=codelist(RC[2],R2C4:R" & lastRow & "C4, R2C3:R" & lastRow & "C3,"","")"
and
Const COMMA As String = ""","""
ActiveCell.FormulaR1C1 = "=codelist(RC[2]," & _
Range("D2").Resize(lastRow - 1).Address(, , xlR1C1) & _
"," & _
Range("C2").Resize(lastRow - 1).Address(, , xlR1C1) & _
"," & _
COMMA & _
")"
Qualify the parent worksheet and resize according to the column's populated limit. Resize every associated range that needs to be the same size.
Function codeList(Criteria As String, LookupRange As Range, ValueRange As Range, delimiter As String)
with LookupRange.parent
set LookupRange = .range(LookupRange.cells(1), .cells(.rows.count, LookupRange.cells(LookupRange.cells.count).column).end(xlup))
set ValueRange = ValueRange.cells(1).resize(LookupRange.rows.count, LookupRange.columns.count)
end with
'all the rest of the code
end function
Never use ActiveSheet or ActiveCell in a worksheet's UDF. The originating cell where the formula is in is the Application.Caller.

VBA Formula creation uses the name of the Variable rather than the value

Im trying to create a code which will allow me to pull the average of 6 rows from a sheet called 'Raw Data' and dump it into a cell in a different worksheet, and then pull the average of the next 6 rows from 'Raw Data' and so on.
E.G. average('RawData'! A1:A6) in a new sheet A1
then
average('Raw Data'! A7:A12) In new sheet A2
etc.
So far I have managed to make the code loop in a way that I want however Im having trouble writing the actual formula in new sheet A1 and A2.
so far I have tried:
Dim address13 As String
address13 = "'Raw Data'" & "!" & Cells(start_row, RPM1300).Address & ":" & _
Cells(end_row, RPM1300).Address
ActiveCell.Offset(0, -4).Select
'1300
ActiveCell.Formula = "=Average(""" & address13 & """)"
However this returns the correct formula but with "" around it - rendering it useless.
I have also tried:
Sheets("Raw Data").Select
Dim address9 As Range
Set address9 = Range(Cells(start_row, RPM900).Address(), Cells(end_row, RPM900).Address())
Sheets("New Sheet").Select
rCell.Activate
ActiveCell.Offset(0, -5).Select
ActiveCell.Formula = "=Average(address9)"
However this just returns the name of the variable address9 in the formula rather than the actual range.
Note that RPM1300, RPM900, start_row, end_row and rCell are all variables in order for the code to loop and paste into the correct places.
Any help would be greatly apreciated
Try replacing your line:
ActiveCell.Formula = "=Average(""" & address13 & """)"
With:
ActiveCell.Formula = "=AVERAGE(" & address13 & ")"
The reason: the variable address13 is already defined as a String, that's why you don't need the extra " inside the brackets.
Code (use your first method:)
Dim address13 As String
address13 = "'Raw Data'!" & Cells(start_row, RPM1300).Address & ":" & _
Cells(end_row, RPM1300).Address
ActiveCell.Offset(0, -4).Select
ActiveCell.Formula = "=AVERAGE(" & address13 & ")"
Note: Try avoid using Select and ActiveCell , instead use referenced Ranges and Worksheets.
For instance, let's say you start from Cell A1, and you want this formula to be in Cell A5, you can use:
Range("A1").Offset(4, 0).Formula = "=AVERAGE(" & address13 & ")"
It is probably a bug in your version of Excel. Instead of
ActiveCell.Formula = "=Average(""" & address13 & """)"
try using
ActiveCell.Formula = '=Average("' & address13 & '")'
(single quotes around strings with double quotes and using only 1 double quote then).
Instead of
ActiveCell.Formula = "=Average(""" & address13 & """)"
Try
ActiveCell.Formula = "=Average("& chr(34) & address13 & chr(34) & ")"
At least here chr(34) returns the quotes you want. This may be tweaked if needed. Just change the number inside the ( )
Try using this:
Sub CellValue()
Dim adr As String
Dim sht As String
sht = "'Raw Data'"
adr = "A1:A3"
ActiveCell.Formula = "=AVERAGE(" & sht & "!" & adr & ")"
End Sub
Hope it helps :)
This formula will give you the same result and you'd be able to autofill it by dragging the cell handle.
=AVERAGE(OFFSET('Raw Data'!$A$2,ROW(A1)*6-7,0,6,1))
Filling in both formulas
Sub FillFormulas()
Const BASE_FORMULA = "=AVERAGE('Raw Data'!#Address)"
Dim lastRow As Long, x As Long
Dim Formulas
With Worksheets("Raw Data")
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row / 6
End With
ReDim Formulas(1 To lastRow, 1 To 1)
With Worksheets("New Sheet")
For x = 1 To lastRow
Formulas(x, 1) = Replace(BASE_FORMULA, "#Address", .Cells((x * 6) - 5, 1).Resize(6).Address)
Next
.Range("A1").Resize(lastRow).Formula = Formulas
.Range("C1").Resize(lastRow).Formula = "=AVERAGE(OFFSET('Raw Data'!$A$2,ROW(A1)*6-7,0,6,1))"
End With
End Sub

Apply IF condition to a range Excel VBA

I have written this code but it doesnt seems to be working , Why?
Dim oRo As String
Dim nRo As String
Lastro = ActiveSheet.Cells(Rows.Count, 2).End(xlUp).Row
oRo = "J2:O" & Lastro
nRo = "Q2:V" & Lastro
Range("C2:G" & Lastro).Select
With Range("C2:G" & Lastro)
.Range("C2:G" & Lastro).Formula = "=IF(oRo*nRo<0,ROUNDUP(oRo*1.3,-2),IF(ABS(oRo) <=ABS(nRo),nRo,ROUNDUP(oRo*1.3,-2)))"
End With
End Sub
Your best bet for maintainability is to embrace R1C1 notation when you write formulas to Excel from VBA. I still can't read R1C1, but I use it exclusively to write formulas from VBA. Here's how:
Let's say you want this formula in G2
=IF(J2*Q2<0,ROUNDUP(J2*1.3,-2),IF(ABS(J2)<=ABS(Q2),Q2,ROUNDUP(J2*1.3,-2)))
So type that in G2, select G2, and open the Immediate Window (Ctrl+G in VBE). In the IW, type
?activecell.FormulaR1C1
That will give you all that you need. You don't have to be able to read it, you just have to be sure you typed the right formula (in A1 notation) in cell G2. Now you can have super simple code like
Dim lRow As Long
Dim sh As Worksheet
Set sh = ActiveSheet
lRow = sh.Cells(sh.Rows.Count, 2).End(xlUp).Row - 1
sh.Range("G2").Resize(lRow, 1).FormulaR1C1 = "=IF(RC[3]*RC[10]<0,ROUNDUP(RC[3]*1.3,-2),IF(ABS(RC[3])<=ABS(RC[10]),RC[10],ROUNDUP(RC[3]*1.3,-2)))"
All I did was copy the R1C1 formula from the Immediate Window and paste it into the code.
.Range("C2:G" & Lastro).Formula = "=IF(" & oRo & "*" & nRo & "<0,ROUNDUP(" & oRo & "*1.3,-2),IF(ABS(" & oRo & ") <=ABS(" & nRo & ")," & nRo & ",ROUNDUP(" & oRo & "*1.3,-2)))"
You are hardcoding the phrases "oRo" and "nRo"
When you get to this line to write the formula, you are not writing out the values of oRo and nRo, so excel is expectin them to be defined within name manager.
.Range("C2:G" & Lastro).Formula = "=IF(oRo*nRo<0,ROUNDUP(oRo*1.3,-2),IF(ABS(oRo) <=ABS(nRo),nRo,ROUNDUP(oRo*1.3,-2)))"
If you want to write out the calculated values of oRo and nRo, you will have to alter the code slightly:
Dim oRo As String
Dim nRo As String
Lastro = ActiveSheet.Cells(Rows.Count, 2).End(xlUp).Row
oRo = "J2:O" & Lastro
nRo = "Q2:V" & Lastro
Range("C2:G" & Lastro).Formula = _
"=IF(" & oRo & "*" & nRo & "<0,ROUNDUP(" & oRo & _
"*1.3,-2),IF(ABS(" & oRo & ") <=ABS(" & nRo & _
")," & nRo & ",ROUNDUP(" & oRo & "*1.3,-2)))"
End Sub
notice no select is required, and as you are only dealing with one range, no with is required either. I would also suggest you add in Option Explicit to the top of your procedure to ensure all variables are declared and spelled correctly.

Resources