Apply IF condition to a range Excel VBA - excel

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.

Related

VBA vlookup iferror formula error '1004' while inserting a formula to cell

I have a short code about inserting a formula to the cell instead of obtaining values but when I tried to use that with VLOOKUP and/or IFERROR, I get error 1004. I did it with SUB, SUBTOTAL before but couldn't achieved with these functions. If you may help, that would be amazing.
GerçekStok = 0
Set StokBook = ActiveWorkbook
Set BticinoBook = Workbooks("BTICINO.xlsm")
NoS = BticinoBook.Sheets.Count
For k = 1 To NoS
If BticinoBook.Sheets(k).Name = "DRAFT" Then
DNumber = k
Exit For
End If
Next k
TotalRow = BticinoBook.Sheets(DNumber).Cells(Rows.Count, 4).End(xlUp).Row
If GerçekStok = 0 Then
For i = 2 To TotalRow
BticinoBook.Sheets(DNumber).Cells(i, 2) = "=IFERROR(VLOOKUP(D" & i & ";'[" & StokBook.Name & "]Sheet2'!$A:$E;3;FALSE);" & Chr(34) & Chr(48) & Chr(34) & Chr(41)
Next i
Else
For i = 2 TotalRow
BticinoBook.Sheets(DNumber).Cells(i, 2) = "=IFERROR(VLOOKUP(D" & i & ";'[" & StokBook.Name & "]Sheet2'!$A:$E;4;FALSE);" & Chr(34) & Chr(48) & Chr(34) & Chr(41)
Next i
End If
You need to use .Formula to enter a formula into a cell.
Range("B10").Formula = "=SUM(B4:B9)"
If your string contains another string with double quotes, then you need to type the double quote twice, like this:
... whatever... ;FALSE);""0"")"
Using Chr() instead of the typed characters doesn't really fix the issue.
BticinoBook.Sheets(DNumber).Cells(i, 2).formula = "=IFERROR(VLOOKUP(D" & i & ";'[" & StokBook.Name & "]Sheet2'!$A:$E;3;FALSE);""0"")"
Of course, there is no reason to put a zero inside of double quotes, so you could simply use
BticinoBook.Sheets(DNumber).Cells(i, 2).formula = "=IFERROR(VLOOKUP(D" & i & ";'[" & StokBook.Name & "]Sheet2'!$A:$E;3;FALSE);0)"

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

Vlookup in filtered Range with Varaible Lookup Value, Variable Lookup Range VBA

I am trying to apply Vlookup on a filtered range with Variable Lookup Value(Changing according to the row number) and Variable Lookup Range(From a user browsed workbook). But, the formula bar after running the code shows the formula as :-
=IFERROR(VLOOKUP(#Sri Lanka15-#a_One-#Time Base Rent,'[C_Rent Report_25082020.xlsx]Sheet 1'!$J$1:$N$968,4,0)," ")
I am not sure where these "#" signs are coming from. The lookup value for this particular row is :-Sri Lanka15-a_One-Time Base Rent.
Below is the code:-
Dim LR As Long ' Defined as Last row in source file
Dim nlr As Long 'Defined as Last row in Macro Workbook where vlookup is applied
Dim Filename As String
Filename = Application.GetOpenFilename(FileFilter:="All Files(*.xls; *.xlsx; *.csv),*xls,*.xlsx, *csv", Title:="Select File To Be Opened")
Workbooks.Open Filename:=Filename
sourcefile = Dir(Filename)
With ActiveSheet
Range("A1:AQ" & nlr).AutoFilter Field:=25, Criteria1:="One-Time Base Rent"
For Each cell In Range("AA2:AA" & nlr).SpecialCells(xlCellTypeVisible)
lookupvalue = Cells(cell.Row, "Z").Value
cell.Formula = "=IFERROR(VLOOKUP(" & lookupvalue & ",'[" & sourcefile & "]Sheet 1'!$J$1:$N$" & LR & ",4,0),"" "")" ' The problem seems to be here in lookup value as rest are appearing as fine in formula
Next
End With
Since i need to apply subsequent filters after this. i would like to keep the lookup value as variable.
I have tried WorksheetFunction.Vlookup too, but i am not sure how to define the range from a file chosen by user in worksheetfunction
Any help is highly appreciated !!
Thanks
Please, try replacing of
cell.Formula = "=IFERROR(VLOOKUP(" & lookupvalue & ",'[" & sourcefile & "]Sheet 1'!$J$1:$N$" & LR & ",4,0),"" "")"
with
cell.Formula = "=IFERROR(VLOOKUP(" & cells(cell.Row, "Z").Address & ",'[" & sourceFile & "]Sheet 1'!$J$1:$N$" & lr & ",4,0),"" "")"

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.

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

Resources