Assign formula to cell using VBA? - excel

VBA has been giving me an error 1004 for this code:
Sub UpdateCellsFormula()
Dim FormulaRange As Range
Dim i As Integer
Set FormulaCellsRange = Range("J17", "J95")
i = 17
For Each r In FormulaCellsRange.Cells
r.Formula = Replace("=D17*L21+E17*M21+F17*O21+G17*N21+H17*P21+I17*Q21)/(1+0,85+0,6+0,4+0,37)", "17", i)
i = i + 1
Next
End Sub
Can anyone have a look at it?

Formulas assigned with .Formula must be in En-US locale. The decimal dot in numbers must therefore be ., not , (1+0.85+0.6+0.4+0.37).
Also you have a missing opening parenthesis in the beginning, right after =.
You also might want to learn about absolute references in Excel. That way you can copy the same formula into all cells in FormulaCellsRange without replacing anything:
Sub UpdateCellsFormula()
ActiveSheet.Range("J17", "J95").Formula = "=(D17*$L$21+E17*$M$21+F17*$O$21+G17*$N$21+H17*$P$21+I17*$Q$21)/(1+0.85+0.6+0.4+0.37)"
End Sub

Related

How to add modification to all formulas from a selected range in excel

I would like to limit all of the formulas in a selected range of cells with an additional if statement.
Is it doable with the use of the VBA?
Let's say:
cell A1 contains =sum(B1;C1) but it can be any formula that a selected cell contains
after applying macro updated formula would be =if(D100>0;sum(B1;C1);0)
=if(D100>0;any formula in a cell ;0)
You can achieve this by using code like this:
Sub ModifyFormulas()
Dim cl As Range, formulas_cells As Range
Const template = "=if(D100>0,#,0)" '# will be replaced by old formula without '='
On Error Resume Next ' handle an error if there are no formulas in the range
Set formulas_cells = Range("A1:A10").SpecialCells(xlCellTypeFormulas)
On Error GoTo 0
If Not formulas_cells Is Nothing Then
For Each cl In formulas_cells
cl.Formula = Replace(template, "#", Mid(cl.Formula, 2))
Next
End If
End Sub
Without vba, I use the following method:
edit / replace the "=" with "xyxy" - this stops excel recalculating
then edit / replace "sum" with "if(D100>0;sum"
then edit / replace ")" with ");0)"
lastly replace "xyxy" with "="
and then it all works, done this often with my sheets when I have to change some calculations...

VBA Issue with Number formatted as text when numbers include comma

I use a vba script to open another workbook. This workbook is in format .XLS and the content from a DB was stored like:
"Name1" "0" "7,98"
"Name2" "5" "1"
"Name3" "2" "7,1"
When opening the workbook with a VBA script, every cell that includes a comma, is interpreted as text and shows this warning:
The number in this cell is formatted as text or is preceded by an apostrophe
Strangely, if I open the file by double clicking, the numbers are just formatted as text and don't show any error. I guess, Excel is doing some interpretting, which doesn't work.
My code is:
Dim WorkBookImport As Workbook
Name = Application.GetOpenFilename()
If Name <> False Then
Set WorkBookImport = Workbooks.Open(Filename:=Name)
End If
I tried everything from:
Range(mycolumn).Value = Range(mycolumn).Value
For loop with CDbl(.Value)
Range(mycolumn).TextToColumns ...
Nothing works ;( Please help!
Option Explicit
Sub edksg()
Dim c As Range
Set c = Sheet1.Range("D3")
c.Value2 = CDbl(c.Value2)
End Sub
Works fine for me when cell D3 of the worksheet is formatted as text.
Of course, my location uses the comma as decimal separator, so if your location uses a different standard, the issue might be there. In that case, doing something like CDbl(Replace(c.Value2, ",", Application.DecimalSeparator, 1, -1, vbBinaryCompare)) might solve that part of the issue.
If you want to loop through the entirety of some column, the end result might look something like this, assuming the values you want to convert to numbers are in column C.
Option Explicit
Sub edksg()
Dim c As Range
Dim r As Range
Set r = Sheet1.Range("C1:C" & Sheet1.Range("C" & Sheet1.Rows.Count).End(xlUp).Row)
For Each c In r
If Len(c) > 0 Then
c.Value2 = CDbl(Replace(c.Value2, ",", Application.DecimalSeparator, 1, -1, vbBinaryCompare))
End If
Next c
End Sub
It´s a problem with the formating of the cells. You should use NumberFormat to change it.
Sub FormatNumber()
ThisWorkbook.Worksheets("YourWorkbook").Range("YourRange") = CDbl(ThisWorkbook.Worksheets("YourWorkbook").Range("YourRange"))
ThisWorkbook.Worksheets("YourWorkbook").Range("YourRange").NumberFormat = "General"
End Sub
With NumberFormat you can also change it to text if you have the opposite problem, in this case you would use NumberFormat = "#"

Traverse multiple cells not in a range stored in a name using VBA in Excel

I have a name that contains this, for example:
=(B1;C3;E4)
It is stored with the name, "Cells1".
I want to take those cells using VBA and work with them, and change their cell value. I have the following code:
Sub Vaciar_nombres()
Dim R1 As
REM Following line throws a 1004 error.
Set R1 = test_sheet.Names("Cells1").RefersToRange
Debug.Print (VarType(R1))
End Sub
I tried using a Range type variable. It throws a 1004 error.
Also, I don't know if I have to write those cells in that name like:
=(B1;C4;C5)
OR
=B2;C4;C5
Don't take into account the semicolon notation, in my language, it is written like that when I create a name and select different cells using the Ctrl key.
How about this:
Option Explicit
Sub Test()
Dim i As Integer
Dim x As Range
i = 1
For Each x In Range("Cells1")
x.Value = i
i = i + 2
Next x
End Sub

How do I write an WITH statement that loops through rows within the WITH-formula?

I'm building an interactive Gantt chart with many rows (which is why I use VBA) and I'm having trouble with formatting my cells. Basically I just want the cells to have color based on an AND-formula. The formula is referring to other cells, so the formatting is not based on the cells own value.
The tricky part is that my formula needs to change according to the specific row that it's looping through. I managed to build a code that correctly loops through each row, but I can't get the formula to change as well. Right now my code gives me an syntax error in the formula-part of my with-expression.
I hope you guys can help!
I figured that the problem might be that the concatenate-trick might not work with with-statements. But I don't know how I can do the formatting in any other way.
Public Sub FormatTest()
Dim Sheet As Object
Dim Area As Range, r As Range
Dim i As Integer
Set Area = Sheets("Styregruppe - Tester").Range("H11:BK58")
For Each r In Area.Rows
For i = 11 To 58
With r.FormatConditions
.Delete
With .Add(Type:=xlExpression, Formula1:="=OG(("C" & i)<=H8;("D" & i)>=H8)")
.Interior.Color = RGB(0, 176, 240)
.StopIfTrue = False
End With
End With
Next i
Next r
End Sub
This line: .Add(Type:=xlExpression, Formula1:="=OG(("C" & i)<=H8;("D" & i)>=H8)")
Has improper quotes you took the C out of the quotes so it thinks its a variable and the ampersand is within the quotes so is being interpreted as a string character and not as the concatenation character.
You want something like: .Add(Type:=xlExpression, Formula1:="=OG((C" & i & ")<=H8;(D" &
i & ")>=H8)")

Replace integer value excel sheet

I'm tyring to replace integer 7,6 in an excel by 8. However, following code is not really working as expected. It seems to subsitute strings. I have written a similar piece of code using the replace functionality but even that didn't produce the results I'm expecting. What am I doing wrong?
Sub MacroTest()
'
Dim rng As Range, cell As Range
Set rng = Sheets("Naomi").Range("H1:H10000")
For Each cell In rng
If cell > 0 Then
cell = WorksheetFunction.Substitute(cell, "7,6", "8")
End If
Next
End Sub
Thanks for guiding me.
I guess Taosique provided the best way to do it.
This answers why it returns String instead of Number.
You already figure it out that Substitute returns a string when you try it inside WS.
Try using Val Function then to convert the value to a Number as in below.
With Application.WorksheetFunction
For Each cell in rng
If cell > 0 Then
cell = Val(.Substitute(cell, 7.6, 8))
End If
Next
End With
Or you can use Evaluate as well like this:
If cell > 0 Then
cell = Evaluate("Value(Substitute(" & cell & ",7.6,8))")
End If
No need to enclose 7.6 with "".
Substitute accepts numbers as arguments.
Use this:
If cell.Value = 7.6 Then
cell.Value = 8
End If

Resources