Loop Variable inside a Formula Function - excel

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.

Related

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),"" "")"

Excel-Vba : Code for Applying Formula until Last Row not working

I'm new to VBA so sorry if this seems to be a simple question.
I'm trying to create a macro which will formate and include a couple of formulas in a sheet but when I try to include the formula until the last row I get a error "Run Time Error 1004 - Application-Defined or Object Defined Error" at the following code:
ActiveSheet.Range("U2:U" & LastRow).Formula = "=L2/86400"
If I change the "Last Row" for a number the Macro works normally. Below is the whole code.
Sheets("DLASpotPlacement").Select
Dim LastRow As Double
LastRow = Sheets("DLASpotPlacement").Cells(Rows.Count, 1).Rows
Range("A1").Select
ActiveSheet.Range("U:U, V:V, W:W").NumberFormat = "[h]:mm:ss;#"
ActiveSheet.Range("U2:U" & LastRow).Formula = "=L2/86400"
ActiveSheet.Range("V2:V" & LastRow).Formula = "=VALUE(H2)"
ActiveSheet.Range("W2:W" & LastRow).FormulaLocal = "=IF(AND(H2>0,0416666666666667;H2<=0,249988425925926);""01 - 06"";IF(AND(H2>=0,25;H2<0,4166551);""06 - 10"";IF(AND(H2>=0,4166667;H2<0,4999884);""10 - 12"";IF(AND(H2>=0,5;H2<0,7499884);""12 - 18"";""18 - 01""))))"
Thanks for all the help
Copy Excel Formulas
The error occurs because of two reasons:
You forgot End(xlUp) in the LastRow Calculation, e.g.:
LastRow = Sheets("DLASpotPlacement").Cells(Rows.Count, 1).End(xlUp).Row
and it has to be declared as a whole number e.g.:
Dim LastRow as Long
The Code
Option Explicit
Sub CopyFormulas()
Const cCol As Variant = "A" ' Last Row Column Letter/Number
Const cFirstR As Long = 2 ' First Row Number
Dim LastRow As Long ' Last Row Number
With ThisWorkbook.Worksheets("DLASpotPlacement")
LastRow = .Cells(.Rows.Count, cCol).End(xlUp).Row
'.Cells(1, cCol).Select ' uncomment if necessary
' You don't need to format the entire columns.
.Range("U" & cFirstR & ":W" & LastRow).NumberFormat = "[h]:mm:ss;#"
.Range("U" & cFirstR & ":U" & LastRow).Formula = "=L2/86400"
.Range("V" & cFirstR & ":V" & LastRow).Formula = "=VALUE(H2)"
.Range("W" & cFirstR & ":W" & LastRow).FormulaLocal = _
"=IF(AND(H2>0,0416666666666667;H2<=0,249988425925926);""" _
& "01 - 06"";IF(AND(H2>=0,25;H2<0,4166551);""06 - 10"";IF(" _
& "AND(H2>=0,4166667;H2<0,4999884);""10 - 12"";IF(AND(H2>=0" _
& ",5;H2<0,7499884);""12 - 18"";""18 - 01""))))"
End With
End Sub
Remarks
Using FormulaLocal is a nice 'trick' to remember.
#Mike; Your problem is in this line:
LastRow = Sheets("DLASpotPlacement").Cells(Rows.Count, 1).Rows
You made the LastRow an array, not a number. Also, is not a Double but an Iteger (mathematically). However, the Integer datatype is too small and you will get an "Overflow" error if you declare it "As Integer". Here are the two changes you need to make it all work:
Dim LastRow As Long
LastRow = Sheets("DLASpotPlacement").Rows.Count
...
For LastRow, use the Worksheet.UsedRange property.
You could also use the Range.Resize property to select the range, and replace the "Select" with "With".
Dim LastRow As Double
With Sheets("DLASpotPlacement")
LastRow = .UsedRange.Rows.count
.Range("U:W").NumberFormat = "[h]:mm:ss;#"
.Range("U1").Resize(LastRow - 1).Formula = "=L2/86400"
.Range("V1").Resize(LastRow - 1).Formula = "=VALUE(H2)"
.Range("W1").Resize(LastRow - 1).FormulaLocal = "..."
End With

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