Excel VBA .Trim function changes . to , - excel

Earlier today I was cleaning up data, using the .trim() vba function. Though it caused . to be changed to , and I have no idea why.
Cells(rw, j).Value = Trim(Cells(rw, j).Value)
Is all I did, and it changed values as follows:
5.2 -> 5,2
One might think that is due to the local settings, though the same column contains values like 3(6.1) which are not messed up.
Thanks in advance

Go to File - Options - Advanced and look for Use system separators. You want the decimal separator to be . and the Thousands separator to be ,
You can also change these in VBA using the following code:
Application.DecimalSeparator = "."
Application.ThousandsSeparator = ","
Application.UseSystemSeparators = False
As you don't want to changes these setting, change your code to:
Cells(rw, j).Value = "'" & Trim(Cells(rw, j).Text)
.Text will give you the string version of what is in the cell rather than attempt to convert it to a number (if it looks like a number).

If you don't want to change your global system/excel settings for this one application, you could try forcing the value to text with something like:
With Cells(rw, j)
.NumberFormat = "#"
.Value = Trim(Cells(rw, j).Value)
End With
Alternatively, based on your comment:
With Cells(rw, j).Value = "'" & Trim(Cells(rw, j).Value)

You can try this:
Dim temp As String
temp = Cells(rw, j).Value
temp = Trim(temp)
Cells(rw, j).Value = temp
Unfortunately I can't test it.

Related

Formula inside a variable

I have the following question, is it posible to insert a formula inside a variable in VBA Excel to use this variable after?
For example:
MinO = "=MIN(" & .Cells(3, 7 + NumSheet).Address(False, False) & ":" & .Cells(3, 9 + NumSheet).Address(False, False) & ")"
For N = 1 To NumSheet + 1
.Cells(4, 5 + N).Value = 80 * ((.Cells(3, 8 + NumSheet).Value - .Cells(3, 5 + N).Value) / (.Cells(3, 8 + NumSheet).Value - MinO))
.Cells(4, 5 + N).Font.Bold = True
Next N
So MinO is a variable with a formula inside, I know in Range().Formula it works but how can I make it work using a variable?
I know there is also the Application.WorksheetFunction.Min but I want to see if it's posible doing it the other way as WorksheetFunction sometimes give me some errors.
Thank you so much for your answers!
You can do this, but therefore you need the Evaluate() function. (The URL refers to the official documentation of that function)
So, in your case, you might use: (seems not to be completely correct, so I'll put it in comment)
' .Cells(4, 5 + N).Value = 80 * ((.Cells(3, 8 + NumSheet).Value - .Cells(3, 5 + N).Value) / (.Cells(3, 8 + NumSheet).Value - Evaluate(MinO)))
As mentioned in below comments, the following seems to be the correct approach:
MinO = Evaluate("=MIN(" & .Cells(3, 7 + NumSheet).Address(False, False) & ":" & .Cells(3, 9 + NumSheet).Address(False, False) & ")")
Usually when I work with formulas from excel i write them in cell (check that everything works) and then in VBA immediate window (CTRL+G) I type
? Activecell.Formula
or
? Activecell.FormulaR1C1
And it displays formula that you need... That is good start then you start changing parts to reflect your desired variable changes.
Remember that this output is string and in code needs to start and end with 1x", when you want to add string in formula you need to add "" also sometimes you need to add """" and """ for strings in string... :)
I don't think this will work, as it is basically just a text string. I believe that you try to look into why the Application.WorksheetFunction is giving errors instead, or creating your own function if you have some special cases that the worksheet function cannot handle.

Inserting a formula using a macro

I am attempting to insert an IF formula using a macro and I can't seem to get the syntax correct. Trying to insert quotes has me confused, attempting to insert "" I have to use """"".
This is the IF function I need to insert
=IF(P14&Q14&R14<>"","<>","")
The macro creates a new row every time it is called, therefore the next formula inserted under it would be
=IF(P15&Q15&R15<>"","<>","")
I get the next empty row using
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows,
_ SearchDirection:=xlPrevious, LookIn:=xlValues.Row + 1
Yet using this insert method and syntax I get a type mismatch error.
.Cells(iRow, 3).Value = "=IF(P" + iRow + "&Q" + iRow + "&R" + iRow + "<>"""""," + ""<>"",""""")"
Can someone please advise as to why I am receiving a type mismatch error?
Thanks for your help!
Firstly, do not use + for concatenation. Use &. In some particular cases, you may have problems.
Secondly, it is good to use .Formula instead of .Value...
And the formula string should be:
.Cells(iRow, 3).Formula = "=IF(P" & iRow & "&Q" & iRow & "&R" & iRow & "<>""""," & """<>"","""")"
Five """"" makes sense only at the end of the string... Four to double the existing one and the fifth for string termination.
You could use:
.Cells(iRow, 3).Value = Replace("=IF(PX&QX&RX<>"""",""<>"","""")", "X", iRow)

VBA,Combine .Formula with VBA

I have the following vba code which puts a formula in a cell.
.Range("D" & lastrow + 1).Formula = "=INDEX(Spread!$C:$C, MATCH(1,INDEX((A330 = Spread!$A:$A) * (""Stack"" =Spread!$B:$B),),0))"
How can I change A330 in my formula to vba code like Worksheets("Manager").Range("C2").Value
Just concate it like a normal string using the & operator. Since you are not joining text ,but rather a VBA object, do not wrap quotes around the object.
"=INDEX(Spread!$C:$C, MATCH(1,INDEX((" & Worksheets("Manager").Range("C2").Value & "= Spread!$A:$A) * (""Stack"" =Spread!$B:$B),),0))"
You can also store the data in a variable and use it instead of A330. This way you can always use newly created variable inside your code anytime anywhere in your code
myData = Worksheets("Manager").Range("C2").Value
.Range("D" & lastrow + 1).Formula = "=INDEX(Spread!$C:$C, MATCH(1,INDEX((myData = Spread!$A:$A) * (""Stack"" =Spread!$B:$B),),0))"

Excel VBA edit IP-adresses and store into variables

Store values in varaibles instead of printing it to a cell.
Below code uses IP-address from a cell in one sheet and changes the last octet with +2 then print it in a cell.
I would like to use that IP-address and add +1 and store in one variable lets say called IP-AddressGateway and then +2 (from original IP-address) to another variable called IP-AddressController.
I donĀ“t want to print the values to a cell just keep them in variables.
For Each c In w1.Range("D2", w1.Range("D" & Rows.Count).End(xlUp))
FR = Application.Match(c, w2.Columns("A"), 0)
If IsNumeric(FR) Then
v = Split(w2.Range("K" & FR).Value, ".")
v(3) = v(3) + 2
c.Offset(, 10).Value = Join(v, ".")
End If
Next c
I need the For Each since I have a lot of other code depending of this. The values stored in the variables will then be used in another module of which I use to print to txt.
Simply remove this line from the code:
c.Offset(, 10).Value = Join(v, ".")
This is what prints them in Excel.
Depending on what exactly do you need, you may add:
FR = Join(v, ".") instead of the c.Offset(,10)...

get the differences between 2 Integer columns into third column

I have to calculate the difference between the values of 2 columns(firstCol and lastCol) and set those differences in a different column(NextColumn). The row count keeps changing, so I have to calculate the rowCount before calculating the difference. I'm trying to write a loop using Range so that the difference can be calculated but it doesn't seem to work.
For i = 3 To lastRow
Range(Cells(3, NextColumn), Cells(lastRow, NextColumn)).FormulaR1C1 = "=Range(Cells(i, firstCol),Cells(i,firstCol)).Value - Range(Cells(i, lastCol),Cells(i,lastCol)).Value"
Next i
Any help would be greatly appreciated!
Thank you
Nick
For any input of "i" into the formula, you need to use " & i & " when using using a formula="", such as:
"=A" & i & "+B" & i
When you change to just a formula that doesn't input a formula to the cell (math happens in VBA), you can ignore the Excel formatting and "" blocking, such as:
= Cells(i,"A").Value + Cells(i,"B").Value
Make sure to use your loop variable where appropriate, so that you would have an outcome in a loop like:
Dim i as Long
For i = 1 to 10
Cells(i,"C").Formula = Cells(i,"A").Value + Cells(i,"B").Value
Next i
Why looping ? Unless I misunderstood the question, something like this should do the trick:
Range("X3:X"& lastrow).Formula = "=C3-D3"
The formula will adjust.
vba needs to be outside the quotes and you do not need the loop:
Range(Cells(3, NextColumn), Cells(lastRow, NextColumn)).Formula = "=" & Cells(3, firstCol).Address(0, 0) & "-" & Cells(3, lastCol).Address(0, 0)
No loop needed. Excel will change the relative references as needed.

Resources