Create visible formula through VBA - vba

My challenge is to code a visible formula into cells that end-users can read the reference. Highlighted yellow line of code causes error "Application Defined or Order defined error". The requirement is that in cells are simple formula like below, which takes first number from workbook where actual result will be and other one comes from different workbook. Actual code locates in a third excel.
=5/78
Variables
Private AR As New Dimension
Private UR As New Dimension
UR.KeySheet --> Sheet 1
AR.KeySheet --> DivederNumbers
UR.Wb --> myWorkbook.xlxs
AR.Wb --> myOtherWorkbook.xlxs
.
Dim test As String
If AR.Wb.Sheets(AR.KeySheet).Cells(Cell3.Row, Cell2.Column) > 0 Then
test = AR.Wb.Path & "\" & AR.Wb.Name
'**THIS LINE CAUSES ERROR:
UR.Wb.Sheets("RESULT").Cells(Cell1.Row, Cell1.Column).Formula = _
"='" & UR.KeySheet & "'!" & Cells(Cell1.Row, Cell1.Column).Address & "/" _
& "'" & [test] & AR.KeySheet & "'!" & Cells(Cell1.Row, _
Cell1.Column).Address(External:=True)
Exit For
End If

You can't reference a sheet like that. AR.KeySheet is only valid as part of the Sheets() collection.
Here is a solution for referencing the sheet name: Get a worksheet name using Excel VBA
You would need to use:
"='" & Application.Caller.Worksheet.Name & "'!" & Cells(Cell1.row, Cell1.column).Address & "/" _

Related

Excel VBA - insert formula in a set of rows with variable reference directly or replacing a string for example "\=" with "="

I have the goal to write a formula in a set of rows. Some references in the formula have to change each row.
I implemented the following script:
Dim i As Integer
Dim formcolM As String
Dim temprng As String
For i = 0 To 100
formcolM = "NUMBERVALUE(IF(Q" & i & "=""Bedarf kum."";A" & i & ";IF(Q" & i & "=""Ist"";OFFSET(A" & i & ";-1;0);IF(Q" & i & "=""Lz."";OFFSET(A" & i & ";-2;0);IF(Q" & i & "=""Ist+Lz.-Bedarf"";OFFSET(A" & i & ";-3;0);)))))"
Let temprng = "M" & i
Range(temprng).Select
ActiveCell.Value = "\=" & formcolM
next i
With this script I am writing a string each row in my excel table at column M.
I noticed that if the formula hasn't the symbol "\" , you can find an error .
In order to avoid the error I thought to leave the symbol "\" and to use a trick deleting it after (because I don't know how to solve with R1C1 formula. I read some answers on Stackoverflow, but unfortunately I did not understand )
The replacing script after the for cycle:
Columns("M:M").Replace What:="\=", Replacement:="=", LookAt:=xlPart
The strange thing is that the macro doesn't delete it.
Infact when the script finishes , it seems that nothing happened, without errors. But if I want substitute "\=" with another symbol, for example "*", the replacing script works.
I did not understand if the problem is :
the replace method did not recognized the symbol "=" to search
I cannot use the replace method because the symbol "=" disturbs in some way , I don't know in what.
OR, is there another simplest way to get this task done?
Someone could help me in order to fix? I should have the formula working in the column M , automatically with vba (not with another formula in the excel sheet) .
Thanks in advance for your time.
We can apply the formula directly. The issue is that vba is very US-EN Centric and all formula when using the .Formula needs to be in that format.
Also since your formula refers to values in a row 3 above the one in which it is put we need to start the loop at 4 not 0. There is no row 0
There are two ways, in US-En format with English functions and , as the deliminator using .Formula:
Dim i As Integer
For i = 4 To 100
Range("M" & i).Formula = "=NUMBERVALUE(IF(Q" & i & "=""Bedarf kum."",A" & i & ",IF(Q" & i & "=""Ist"",OFFSET(A" & i & ",-1,0),IF(Q" & i & "=""Lz."",OFFSET(A" & i & ",-2,0),IF(Q" & i & "=""Ist+Lz.-Bedarf"",OFFSET(A" & i & ",-3,0),)))))"
Next i
Or using .FormulaLocal and the formula as you would write it in your native tongue.
Dim i As Integer
For i = 4 To 100
Range("M" & i).FormulaLocal = "=NUMERO.VALORE(SE(Q" & i & "=""Bedarf kum."";A" & i & ";SE(Q" & i & "=""Ist"";SCARTO(A" & i & ";-1;0);SE(Q" & i & "=""Lz."";SCARTO(A" & i & ";-2;0);SE(Q" & i & "=""Ist+Lz.-Bedarf"";SCARTO(A" & i & ";-3;0);)))))"
Next i
By the time I got this worked out, Scott already had an answer. I just wanted to post your original code modified to work. I would suggest his method.
Sub TestScript()
Dim i As Integer
Dim formcolM As String
Dim temprng As String
For i = 4 To 100
formcolM = "NUMBERVALUE(IF(Q" & i & "=" & "Bedarf kum." & ";A" & i & ";IF(Q" & i & "=" & "Ist" & ";OFFSET(A" & i & ";-1;0);IF(Q" & i & "=" & "Lz." & ";OFFSET(A" & i & ";-2;0);IF(Q" & i & "=" & "Ist+Lz.-Bedarf" & ";OFFSET(A" & i & ";-3;0);)))))"
temprng = "M" & i
Sheets("Sheet1").Range(temprng).Select
ActiveCell.Value = " = " & formcolM
Next i
End Sub

How to apply vlookup on the different workbook range?

I am trying to apply VLOOKUP to get the data from a workbook named LPDwith sheet RAS(Offshore) having my lookup range. I want to look for the column A which is present in a different workbook named fresher with sheet as DestSh.So I want the results after applying VLOOKUP in the sheet DestSh in column z.
I have tried
iSCount = 2
For Each cell In DestSh.Range("Z2:Z" & lstRowofIpSheet)
With DestSh
sFormula = "=VLOOKUP(DestSh!$A" & iSCount & ",'" & sLPDFileName & "]RAS(Offshore)'!$B:$F,5,false)"
.Range("Z" & iSCount).Formula = sFormula
iSCount = iSCount + 1
End With
Next cell
But I am getting the error as: Application defined or Object defined error.
Any help or suggestions shall be highly appreciated.
In this line:
sFormula = "=VLOOKUP(DestSh!$A" & iSCount & _
",'" & sLPDFileName & "]RAS(Offshore)'!$B:$F,5,false)"
Missing an opening square bracket:
sFormula = "=VLOOKUP(DestSh!$A" & iSCount & _
",'[" & sLPDFileName & "]RAS(Offshore)'!$B:$F,5,false)"

Excel vba error name in formula

I'm trying to pass one formula from vba excel to a cell i have this code
atmFecha = "=IF(L" & tmLastRow & "=0," & Chr(34) & " " & Chr(34) & ",'ws2'!$E$3)"
.Cells(tmLastRow, "H").Value = atmFecha
this instruction insert in the cell the correct formula but display #NAME? I have to press "F2" and then "Enter" to Excel recognize the formula and display the correct value.
I use the instructions formula and formulaR1C1 but the result is the same.
what can i do to recognize automaticly the correct value of the formula ?
After your code, add this line:
Application.Calculate
It sounds like you are set to Manual Calculation, so that line will refresh everything. If you're setting a number of formulas, wait until they're all inserted, then execute that line.
I don't know how it fix but now is working, I was testing with the second file I made this is the code"
Sub btnCalculate()
Dim atmFecha As String
Dim tmLastRow As Integer
With Worksheets("ws1")
tmLastRow = 1
atmFecha = "=IF(C1=0," & Chr(34) & " " & Chr(34) & ",'ws2'!$A$1)"
.Cells(tmLastRow, "A").Value = atmFecha
End With
End Sub

VBA Set Cell value to text containing ' not working

I'm trying to get a macro to type out a heap of formulae for me. The formula goes something like this:
=COUNTIF('other_sheet'!A:A,"hello*")
The user can specify A and other_sheet, so I select the cell and then go
ActiveCell.Value = "=COUNTIF('" & othercell & "'!" & column & ":" & _
column & """,hello*"")"
But it keeps giving me errors like:
1004: Object Defined Error
I have tried using ActiveCell.Text, ActiveCell.Formula etc. and they all don't work.
It needs to be ActiveCell.Formula and ", is the wrong way around next to Hello. It should be:
ActiveCell.Formula= "=COUNTIF('" & othercell & "'!" & column _
& ":" & column & ",""hello*"")"
Apparently you can only put proper, completed answers into a cell.
i.e. if the output turns out to be "=sum(A:A" and a bracket isn't closed, then the application throws an error just as if you typed it in manually.

Run-time error '1004' when applying formula to Range.FormulaR1C1 in VBA

I'm trying to apply a big nested formula to a range using the code below. Basically, if the value in cell A of the active row exists in the column A of another workbook and if the cell in column E of the active row is not empty, I want the active cell to display the cells to display the value of the equivalent cell in a separate workbook.
This needs to be applied to several worksheets so I'm using the variables lrow (which is an int with the last row of the active worksheet in workbook#1) and tlrow (which is an int equal to the last row of the active worksheet in workbook#2). When I step through the sub, these variables both return the numbers I would expect them to.
Likewise, this is inside of a for loop so I also use Worksheets(i).Name where I is an int.
When I run the code, I get the run-time error "'1004': Application-defined or object-defined error".
I'm assuming it's a syntax issue.
Code:
Range("B15:B" & lrow).FormulaR1C1 = _
"=IF(OR(RC1="""",RC5=""""),"""",IF(ISERROR(VLOOKUP(RC1,'[temp.xlsx]" & _
Worksheets(i).Name & _
"'!A15:D" & tlrow & ",3,FALSE)),""0"",VLOOKUP(RC1,'[temp.xlsx]" & _
Worksheets(i).Name & "'!A15:D" & tlrow & ",3,FALSE))))"
Try using this:
Range("B15:B" & lrow).FormulaR1C1 = _
"=IF(OR(RC1="""",RC5=""""),"""",IF(ISERROR(VLOOKUP(RC1," & _
Worksheets(i).Range("A1:D" & lrow).Address(ReferenceStyle:=xlR1C1, External:=True) & _
",3,FALSE)),""0"",VLOOKUP(RC1," & _
Worksheets(i)..Range("A1:D" & tlrow).Address(ReferenceStyle:=xlR1C1, External:=True) & _
",3,FALSE)))"
What version of Excel are you running? In more recent versions you can use the Iferror function in this formula to really chop down the size.
It would be something like this:
Range("B15:B" & lrow).FormulaR1C1 = _
"=IF(OR(RC1="""",RC5=""""),"""",IFERROR(VLOOKUP(RC1," & " & Worksheets(i).Range("A1:D" & _
tlrow).Address(ReferenceStyle:=xlR1C1, External:=True) & ",3,0),""0"")"
Thanks for your help. I was able to resolve the problem by defining my vlookup range in a Range variable and then inputting the variable name in L42's equation in place of
worksheets(i).Range("A1:D" & lrow)
Really apprecaite the responses! Thanks again.