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
Related
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),"" "")"
I have a cell in that contains the following:
=$H$10+1&","&B5+I10&","&(2*$D$2+$E$2)/2
The result of this formula is in this format:
14649,28.25,5.5
I want to use the formula VBA code. I want the number 1 in the $H$10+**1**&" to be the i of the for loop and the I10 in "&B5+I10&" to also change with the loop.
For i=1 to lastrow
.Range("X" & 13+i & "").Formula = "=$H$10+" & i & "" & "," & "B5+I" & i + 10 & "" & "," & "(2*$D$2+$E$2)/2"
Next i
Here code that can be used:
Sub mySub()
'=$H$10+1&","&B5+I10&","&(2*$D$2+$E$2)/2
Dim myRange As Range
Set myRange = Range("H:H").SpecialCells(xlCellTypeLastCell)
Dim myStr As String
'A=10 is for assigning first row in H as your data, hope no data upward from row 9 to row 1
For Baris = 10 To myRange.Row
On Error Resume Next
myStr = "=$H$10+" & Baris - 9 & "&"",""&B5+I" & Baris & "&"",""&(2*$D$2+$E$2)/2"
Range("K" & Baris).Formula = myStr
Next
End Sub
My goal is to be able to "translate" for lack of a better term; each cell in a sheet range into VBA.
This means I can instantly take an existing workbook and produce VBA to recreate it.
So I put this UDF together. It shows a cell as it would appear in VBA. R1C1 format
Function showformula(rng As Range)
If rng.HasArray = True Then
showformula = "{" & rng.Formula & "}"
Else
showformula = "Sheets(""" & ActiveSheet.Name & """). Range(""" & rng.Address & """)" & ".FormulaR1C1 = " & """" & rng.FormulaR1C1 & """"
End If
End Function
So 1)show a user select box for specifying a range. Then Click Proceed and 2) the above UDF reads for every cell in the specified range and 3) prints each cell's result on a new line in cell ZZ.
1 is easy enough to googlefu
but 2) & 3) I do not know how I would write it
https://www.reddit.com/r/excel/comments/brndla/how_to_apply_formula_to_every_cell_in_range_and/
Solution Occurred here
Sub BuildList()
Dim c As Range
Dim rngInput As Range
Dim rngOutput As Range
Dim i As Long
'Ask our user for stuff
Set rngInput = Application.InputBox("What cells do you want to read?", "Input", , , , , , 8)
Set rngOutput = Application.InputBox("Where do you want output to go?", "Output", , , , , , 8)
Application.ScreenUpdating = False
'Write the answers
For Each c In rngInput.Cells
rngOutput.Cells(1).Offset(i).Value = ShowFormula(c)
i = i + 1
Next c
Application.ScreenUpdating = True
End Sub
Function ShowFormula(rng As Range)
If rng.HasArray = True Then
ShowFormula = "{" & rng.Formula & "}"
Else
ShowFormula = "Sheets(""" & ActiveSheet.Name & """). Range(""" & rng.Address & """)" & ".FormulaR1C1 = " & """" & rng.FormulaR1C1 & """"
End If
End Function
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
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.