Replace integer value excel sheet - excel

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

Related

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

Excel vba for each loop with if statement and structured references

I want to change the value in a column of a table based on the value of another column in the same table using structured references. So far I have something like:
Sub Test
For Each cell In Worksheets("FNM_DB").Range("DB_SS[Resource_Loc_Type]")
If cell.Value = "TH" Then
Worksheets("FNM_DB").Range("DB_SS[Resource]") = Worksheets("FNM_DB").Range("DB_SS[SOURCE_AND_SINK_NAMES]")
End If
Next cell
End Sub
I know I could do this without the structured reference, but I want the code to be more readable. Is there a way to loop through all the values? I know the # refers to a specific row, but I don't know how to use it in this instance.
The above statement
The # sign refers to the current row, but that syntax only works inside a worksheet cell, not within a VBA.
is false.
This works:
[tblActualsWithFacts[#1c]].Select
these work too:
Range("tblActualsWithFacts[#1c]").Select
For i = 1 to 12
Range("tblActualsWithFacts[" & i & " c]").Select
Next i
however, the combination of the above techniques i.e. concatenating a structured reference which makes use of "#" does not work, therefore this does NOT work
For i = 1 to 12
Range("tblActualsWithFacts[#" & i & " c]").Select
Next i
While it is possible to use structured references in VBA, addressing the current row is different. The # sign refers to the current row, but that syntax only works inside a worksheet cell, not within a VBA.
If you are concerned about readability, I'm not sure the long syntax is helpful at all. My suggestion is to create variables that represent the offset of the table column name from the current column. Something like this:
Sub test()
Dim Height As Integer, Width As Integer, Result As Integer
Result = 3
Height = 1
Width = 2
For Each cel In Worksheets("Sheet1").Range("SizingTable[Colour]")
If cel.Value = "red" Then
cel.Offset(0, Result) = cel.Offset(0, Height) * cel.Offset(0, Width)
End If
Next cel
End Sub

Assign formula to cell using VBA?

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

Use current cell value to calculate and replace in cell

I'm very new to VBA in excel and I've tried searching for my question already.
I'm trying to calculate an answer based off the value of the cell and have the calculated value replace the current value upon macro execution. For example if A2 has an initial value of 30 I'd like too replace A2 with =A2*3 so that A2 would read 90 as its new value.
Is there any way to do this without having to copy and paste everything somewhere else first?
Thanks for any help.
Try something like this. First, make sure you have selected at least one cell, and then run the macro from the macros menu:
Sub MultiplyBy30()
Dim rng as Range
Dim cl as Range
Set rng = Range(Selection.Address)
For each cl in rng.Cells
If IsNumeric(cl.Value) And Len(cl.Value) > 0 Then
cl.Formula = "=" & cl.Value & "*30"
End If
Next
End Sub

Excel User Defined Function: change the cell's color [duplicate]

This question already has answers here:
Excel VBA: Answer gets "stuck"
(1 answer)
Using a UDF in Excel to update the worksheet
(3 answers)
Closed 1 year ago.
I have a user defined function in Excel. It is called as a formula function from spreadsheet cells and works fine.
I'd like the function to be able to change the cell's color depending on the value that it returns. Essentially, changing the cell's color is a side effect of the function.
I tried
Application.ThisCell.Interior.ColorIndex = 2
But it fails.
Here's a demonstration of how a VBA UDF can change the colouring of a sheets contents rather than using conditional formatting.
As long as both sheets have rows and columns sorted in the same order then this will compare for differences in every cell between two seperate Excel sheets.
You can add this into as many cells as you need to on a third sheet to detect differences between the same two cells on the two sheets with data on: =DifferenceTest(Sheet1!A1,Sheet2!A1)
And the function to be stored in the VBA editor as follows:
Function DifferenceTest(str1 As String, str2 As String) As String
If str1 = str2 Then
Application.Caller.Font.ColorIndex = 2
Else
Application.Caller.Font.ColorIndex = 3
DifferenceTest = str1 & " vs " & str2
End If
End Function
This cannot be done. User defined functions cannot change the state of the workbook/worksheet etc.
Use Conditional Formatting to achieve what you are trying.
EDIT: This is more of a suggestion, not a real answer.
No, you cannot alter a cell's color using a Function(). You can, however, alter it in a Sub() routine.
Simply write a Sub() that will run your function on the cells you wish it to be run on, then after each is run, put an If-statement to see if you want to color it based on the value it returns.
You could create a vba code that runs automatically after there is a change in your sheet.
Instead of hving the code in a seperate module you have to embed it in the sheet itself.
Right click on the sheet tab, choose View Code, and create the following code:
Private Sub Worksheet_Change(ByVal Target As Range)
For Each cell In Range("A1:B8") 'change cell range as needed
Select Case cell.Value
Case 8
cell.Interior.ColorIndex = 4 'cell color becomes green when cell value is 8
Case ""
cell.Interior.ColorIndex = 1 'cell color becomes black when cell is empty
Case Is < 6
cell.Interior.ColorIndex = 7 'cell color becomes pink when cell value is smaller than 6
Case Else
cell.Interior.ColorIndex = 0 'all other cells get no color
End Select
Next cell
End Sub
Function HexToLongRGB(sHexVal As String) As Long
Dim lRed As Long
Dim lGreen As Long
Dim lBlue As Long
lRed = CLng("&H" & Left$(sHexVal, 2))
lGreen = CLng("&H" & Mid$(sHexVal, 3, 2))
lBlue = CLng("&H" & Right$(sHexVal, 2))
HexToLongRGB = RGB(lRed, lGreen, lBlue)
End Function
Function setBgColor(ByVal stringHex As String)
Evaluate "setColor(" & Application.Caller.Offset(0, 0).Address(False, False) & ",""" & stringHex & """)"
setBgColor = ""
End Function
Sub setColor(vCell As Range, vHex As String)
vCell.Interior.Color = HexToLongRGB(vHex)
End Sub
I tried the Evaluate method, which worked but immediately crashed (2007). The help mentions caching the address, so that's my approach - store the cell and color in a collection, then change the color after the calculation.
Dim colorCells As New Collection
Function UDF...
UDF = <whatever>
color = <color for whatever>
colorCells.Add (Application.Caller)
colorCells.Add (color)
End Function
Sub SetColor()
While colorCells.Count <> 0
colorCells(1).Interior.Color = colorCells(2)
colorCells.Remove (1)
colorCells.Remove (1)
Wend
End Sub
Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
SetColor
End Sub

Resources