Change Value in Excel from String to Number - vba

I wrote a script in VBA where numbers from a text file will be inserted into a worksheet. After inserting the values, Excel advises me to convert the values from strings to numbers. Inside the cell, a green triangle appears. After selecting the cell, there are different options you can select to format the value inside the cell.
I also tried to convert the values to double in VBA with CDbl(string) but nothing happens.
Changing the NumberFormat also doesn't work. I tried different values in VBA and also in Excel.
I also tried to record a macro while selecting the method but there was nothing saved inside the makro.
Anybody know how to do this?

Try this. I have taken cell A1 as an example. Also if there are decimal values then instead of Long use a Double and change the NumberFormat accordingly.
Sub Sample()
Dim clVal As Long
With Sheet1.[a1]
clVal = Val(.Value)
.NumberFormat = "0"
.ClearContents
.Formula = clVal
End With
End Sub

It might seem a bit silly, but have you tried Range("A1").Value = Range("A1").Value?
More generally, you can loop through myrange, assuming it is the range you want to fix:
For Each c in myrange
c.Value = c.Value
Next

Related

Embedded "IF" formula breaks occasionally, VBA alternative?

I have a very large embedded IF formula that appears to occasionally break for no reason. Opening and closing the page a few times eventually gets it working again. I am wondering if there is a VBA alternative for it. Here is the IF formula I am running.
=IF(ISNUMBER(SEARCH("76210",E125)),"_012_00762_10",IF(ISNUMBER(SEARCH("76220",E125)),"_012_00762_20",IF(ISNUMBER(SEARCH("76900",E125)),"_012_00769_00",IF(ISNUMBER(SEARCH("76901",E125)),"_012_00769_01",IF(ISNUMBER(SEARCH("85702",E125)),"_012_00857_02",IF(ISNUMBER(SEARCH("85710",E125)),"_012_00857_10",IF(ISNUMBER(SEARCH("100800",E125)),"_012_01008_00",IF(ISNUMBER(SEARCH("100900",E125)),"_012_01009_00",IF(ISNUMBER(SEARCH("123100",E125)),"_012_01231_00",IF(ISNUMBER(SEARCH("124600",E125)),"_012_01246_00",IF(ISNUMBER(SEARCH("124601",E125)),"_012_01246_01",IF(ISNUMBER(SEARCH("124640",E125)),"_012_01246_40",IF(ISNUMBER(SEARCH("124641",E125)),"_012_01246_41",IF(ISNUMBER(SEARCH("142301",E125)),"_012_01423_01",IF(ISNUMBER(SEARCH("158801",E125)),"_012_01588_01",IF(ISNUMBER(SEARCH("158900",E125)),"_012_01589_00",IF(ISNUMBER(SEARCH("159203",E125)),"_012_01592_03",IF(ISNUMBER(SEARCH("159303",E125)),"_012_01593_03",IF(ISNUMBER(SEARCH("159401",E125)),"_012_01594_01",IF(ISNUMBER(SEARCH("159410",E125)),"_012_01594_10",IF(ISNUMBER(SEARCH("159420",E125)),"_012_01594_20",IF(ISNUMBER(SEARCH("159501",E125)),"_012_01595_01",IF(ISNUMBER(SEARCH("169000",E125)),"_012_01690_00",IF(ISNUMBER(SEARCH("186900",E125)),"_012_01869_00",IF(ISNUMBER(SEARCH("213200",E125)),"_012_02132_00",IF(ISNUMBER(SEARCH("213300",E125)),"_012_02133_00",IF(ISNUMBER(SEARCH("215400",E125)),"_012_02154_00",IF(ISNUMBER(SEARCH("220100",E125)),"_012_02201_00",IF(ISNUMBER(SEARCH("223800",E125)),"_012_02238_00",IF(ISNUMBER(SEARCH("225600",E125)),"_012_02256_00",IF(ISNUMBER(SEARCH("230700",E125)),"_012_02307_00",IF(ISNUMBER(SEARCH("230701",E125)),"_012_02307_01",IF(ISNUMBER(SEARCH("231800",E125)),"_012_02318_00",IF(ISNUMBER(SEARCH("235000",E125)),"_012_02350_00",IF(ISNUMBER(SEARCH("235020",E125)),"_012_02350_20",IF(ISNUMBER(SEARCH("242000",E125)),"_012_02420_00",IF(ISNUMBER(SEARCH("246400",E125)),"_012_02464_00",IF(ISNUMBER(SEARCH("292900",E125)),"_012_02929_00",""))))))))))))))))))))))))))))))))))))))
Basically it is built so a serial number is scanned and it populates a cell for the users who use this sheet with its results from the search. I am already running one macro in this sheet as well. Here is that...
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range
Set rng = Intersect(Range("A2:A500, J2:J500"), Target) ' define range of interest
If Not rng Is Nothing Then ' check it's not "nothing"
If WorksheetFunction.CountA(rng) = rng.Count Then 'check for all of its cells being not empty
On Error GoTo safe_exit 'add error control
Application.EnableEvents = False 'don't do anything until you know something has to be done
rng.Offset(, 1).Value = Date 'write Date next to all relevant changed cells
End If
End If
safe_exit:
Application.EnableEvents = True
End Sub
Maybe there is a better way to build this search using a formula that isn't using embedded IF statements, but i couldn't think of another way to do it. Thanks in advance.
This may be what you're looking for:
=IF(ISNA(MATCH(1,IF(ISERR(SEARCH($A$5:$A$42,$E$125)),0,1),0)),"",INDEX($B$5:$B$42,MATCH(1,IF(ISERR(SEARCH($A$5:$A$42,$E$125)),0,1),0)))
entered as an array formula (CTRL-SHIFT-ENTER).
Here $A$5:$A$42 contains 76210, 76220, ... , 292900 (entered as text, not numbers); and $B$5:$B$42 contains _012_00762_10, _012_00762_20, ... , _012_02929_00.
Hope that helps.
Any time you have to go more than 2 deep on an IF you may want to rethink the usage.
What you can do is build a table from your values. Then reference that table as part of your lookup. Assuming your list of value is in range D8:E45 you could use the formula =VLOOKUP(E125,$D$8:$E$45,2).
The beginning of your table would look like what's seen below. The input result cell is referencing your input value and pulling the match of the second column.
To get your table you can take your source formula and replace (Find and Replace - Ctrl+H) some characters with unique delimiting characters. Then use Text To Columns Alt+D+E and delimit and Copy>Paste special>Transpose to quickly have it close to the format you need.

How to highlight a cell based on another cells value VBA?

This question has been asked before but I went about doing it another way. I am trying to highlight a cell if it is greater than the value of another cell.
Here is my code:
Sub Error_Search()
Dim Summary As Worksheet
Dim lr As Long
Set Summary = Worksheets("Summary")
lr = Cells(Rows.Count, 20).End(xlUp).Row
With Summary
For i = lr To 3 Step -1
If Range("L" & i).Value > Range("$Q$2:$R$3").Value Then Range("L" & i).Font.Color = -16776961
Next i
End With
End Sub
Range("$Q$2:$R$3") is a merged cell and it is the cell I want to compare the cell I want to highlight to.
I keep getting a mismatch error.
Any help would be greatly appreciated.
Thanks,
G
As mentioned in the comments, the problem is that a multiple-cells Range doesn't have a single Value, even if the cells are merged: Range.Value yields a 2D variant array whenever more than a single cell is involved. So you can fix the bug by only referring to the top-left cell of the merged range instead.
That said...
You don't need any VBA code to do this; conditional formatting handles it quite neatly.
=$C4>$M$3
Note the $ dollar signs: $M$3 would be your merged cell (only the leftmost cell matters), and $C4 is just the first cell you're defining the conditional format into; leaving the row non-absolute (i.e. no $ on the row number) allows you to apply the format to an entire range of cells by specifying the Applies to range:
Note that the format formula is the same regardless of whether we're looking at $M$3 or $M$3:$N$3 merged cells.
Conditional formats will perform much better than any VBA code you can write.

VBA - How to convert value of cell from text to number

I have to columns with exported numbers, which are stored as text.
I tried to convert those data to numbers with this code.
Sub FormatColumns()
Columns(9).NumberFormat = "0"
Columns(10).NumberFormat = "0"
End Sub
It has done the job correctly (or it seems so), but I am still not able to work with those data as with numbers, but Excel tell me, that it is stored as number.
But when I verify it via formula =ISTEXT(), it always shows me TRUE
Could you help me with it, please? All tutorials and advices, which I've found on Google was via Formating cells or =VALUE(), but VALUE fucntion doesnt work for me, it shows me #VALUE.
Thank you in advance!
Another solution is:
Sub Macro1()
Range("A:A").Select 'Range of values you need converted
For Each Cell In Selection
Cell.Value = (Cell.Value * 1)
Next
End Sub
A non-vba equivalent solution is to have a "1" entered in a cell, copy that cell, select the range you would like converted to numbers, right click and press Paste Special -> Multiply.
This will leave all values in that range as numbers without changing the format. Tested with ISTEXT.
Make sure your settings also match with commas replacing decimals otherwise it may continue to have issues.
you must replace "," ~~> "."
Sub FormatColumns()
With Columns("i:j")
.Replace ",", "."
.NumberFormat = "#,###.00"
End With
End Sub
Check entire relevant region is set to Number format first.
Selection the relevant region and do a global replace of for nothing ("space" to "leave empty"). Then depending upon your locale try a global replace of , to ..
Next enter 1 in a spare cell, copy that cell, select the entire relevant region and Paste Special, Option, Multiply.
If that does not work switch . back to , and repeat the Paste Special.
Its the comma, needs to be . so 405,90 = 405.90
Converting numbers stored as text to numbers via Macro
Sub macro()
Range("F:F").Select 'specify the range which suits your purpose
With Selection
Selection.NumberFormat = "General"
.Value = .Value
End With
End Sub
Hilight the numbers you with to "fix" and run:
Sub fixNumbers()
With Selection
.NumberFormat = "General"
.Value = .Value
End With
End Sub

Deleting a ' from a cell which is not being retrieved in .Value in VBA

I need to find out how to delete a ' which is at the very beginning of every cell in the A column in a Excel but I can't figure out how to do it.
If I perform a Replace with
Replace(ActiveWorkbook.Worksheets("MAIN").Cells(2, 1).Value, "'", "")
or just showing the cell value with a MsgBox it just shows the number itself, without the '.
Any idea about how to delete that character if I couldn't even access it?
P.S: I've tried a basic "find and replace" with same result, even saying I have no matches...
Thanks in advance.
EDIT: Pressing F2 on the "A2" cell to see the formula shows this:
You will not see ' in VBA, neither can you remove it with Excel replace dialog – this is a special symbol that forces numeric values to be treated as text.
You can just reassign formulas and this will remove ':
ActiveWorkbook.Worksheets("MAIN").Range("A1").Formula = ActiveWorkbook.Worksheets("MAIN").Range("A1").Formula
try this:
Sub main()
Dim cell As Range
For Each cell In Range("A1", Cells(Rows.Count, 1).End(xlUp))
cell.Value = Val(cell.Value)
Next
End Sub

Macro for removing conditional formatting fill color Red

I have a large excel report and I am trying to make life easier for my technicians.
I have cells where if a number is not within 10% of another cell then that cell will highlight in RED. My problem is I do NOT want my customers to see the red highlight in my report. I have to convert my excel reports to PDF.
Is there a Macro code that would only take out the conditional formatting for highlight RED?
I have other conditional formatting in my report and that's why I cannot use the Macro code that deletes all conditional formatting.
Also, is there a Macro code that will make it go back to RED?
Any help on this is appreciated. Thanks
The answer is yes. First you need to identify the range you're working on.
Then check if your range has formatting, delete if yes, apply otherwise (like a toggling).
Below code does just that. Change the lines I've commented and adapt. HTH.
Sub ColorUnColor()
Dim myformat As String
Dim cfr As Range
myformat = "=A1<(0.1*B1)" '~~> change to suit
With Sheet2 '~~> change to suit
Set cfr = .Range("D1:D10") '~~> change to suit
If cfr.FormatConditions.Count = 0 Then
.Range("A1").FormatConditions.Add xlExpression, , myformat
With .Range("A1").FormatConditions(1)
.Interior.Color = RGB(255, 0, 0)
.ModifyAppliesToRange cfr
End With
Else
cfr.FormatConditions.Delete
End If
End With
End Sub
Result:
Important: You can assign conditional formatting in any Range, but it will be applied to what you set in ModifyAppliedToRange which I discussed in here.
You could use this to clear any cell on the sheet that is colored red (255). Not sure if that's exactly what you need.
Sub testes()
Dim SrchRng As Range
Set SrchRng = ActiveSheet.UsedRange
For Each Source In SrchRng
If Source.Interior.Color = 255 Then
Source.Interior.Color = xlNone
End If
Next Source
End Sub
As for going back to red couldn't you just run the macro you already have?
Try this:
Selection.FormatConditions.Delete