Unwanted change when using "TextToColumns" twice - excel

I have the following issue.
One of my sheets holds a column that contains values stored as text (e.g. value as 1,22 stored as a text). Currently I use the following Code to convert those entries to values:
Sub Convert()
Range(Cells(2, "K"), Cells(Rows.Count, "K").End(xlUp)).TextToColumns DataType:=xlFixedWidth, DecimalSeparator:=","
End Sub
If I run the macro once the result is fine. However if I run to macro a second time (after I already converted the text to values with the code shown above). The numbers change their format from the comma "," as the decimal separator to a dot "." as a decimal separator (e.g. 1,22 --> 1.22).
This is a problem, because my region uses the comma.
Does anybody know how to prevent this from happening?
Kind regards
Sombrero
Here Screenshots:
Original data#
After first time text2columns:
After second time text2columns:

You original data are strings, and running TextToColumns converts them into numbers. When you run TextToColumns a second time, Excel needs to convert those numbers first into strings.
I can only guess about the internal logic of this conversion, but it wouldn't surprise me if this is not using any regional settings.
Anyhow, I would say it's not a good idea to use the TextToColumns command on numeric values. Use a filter to get only the cells containing text:
Dim r As Range
set r = Range(Cells(2, "K"), Cells(Rows.Count, "K").End(xlUp))
On Error Resume Next ' To prevent runtime error "No cells found"
Set r = r.SpecialCells(xlCellTypeConstants, xlTextValues)
If err.Number = 1004 then exit sub
On Error Goto 0
r.TextToColumns DataType:=xlFixedWidth, DecimalSeparator:=","

Related

Code to find cells that contain a constant preceded by = sign

Any suggestions for Excel vba code that will identify cells that contain values but no function. The catch being that the values I'm searching for are preceded by an "=" sign.
I often have to review other people's financial spreadsheets and knowing which cells contain the actual inputs (assumptions) is key. I can easily find cells with just a constant input with a simple:
Selection.SpecialCells(xlCellTypeConstants, 1).Select
The problem is some users have a habit of inputing numbers preceded by an = sign and these cells are treated by excel as containing a function. I know I can search for cells with functions too, but I only want to find the ones that don't actually have a function, but are input starting with an = sign.
In other words, instead of inputing 1000 in a cell the user inputs =1000. It is only these types of cells I am trying to highlight.
Any suggestions on how I can identify these cells?
Exactly this "The problem is some users have a habit of inputing numbers preceded by an = sign" is your problem. Stop people having this habit!
First it is a stupid habit because it slows everything down because Excel has to evaluate those cells that contain something like =1000 to find out the value and
second those cells actually contain a formula and not a value. So there is no built in way to distinguish them.
Those people are just using Excel wrong.
There is only one workaround I can imagine and that is looping through all cells that contain a formula, remove the = sign and check if the rest of the "formula" is numeric IsNumeric(). If so replace the formula by its value.
So for example if the cell is =1000 then 1000 is numeric and it will replace it by the value 1000. If the cell is =1000*2 then 1000*2 is not numeric because it contains a * sign and it will keep the formula.
Note that this workaround is just fighting symptoms but not fixing the root cause. The root cause is those people using Excel wrong! And you should always fix the causes not fight the symptoms.
Option Explicit
Public Sub ReplaceFormluasWithValueIfNoCalculation()
Dim AllCellsWithFormulas As Range
On Error Resume Next ' next line errors if no formulas are found, so hide errors
Set AllCellsWithFormulas = ActiveSheet.Cells.SpecialCells(xlCellTypeFormulas)
On Error GoTo 0 ' re-enable error reporting
If Not AllCellsWithFormulas Is Nothing Then
Dim Cell As Variant
For Each Cell In AllCellsWithFormulas.Cells ' loop through all formulas
Dim ExtractedValue As String ' extract formula right of the `=` sign
ExtractedValue = Right$(Cell.Formula, Len(Cell.Formula) - 1)
' check if extracted formula is only a value, if so replace formula with value
If IsNumeric(ExtractedValue) Then
Cell.Value = ExtractedValue
End If
Next Cell
End If
End Sub
Even the above can be done, I recommend fixing the root cause.
Assuming those inputs only contain number you could use a regex for that and ensure the value only contain "=" and numbers you'll have a code like this :
Dim RegEx As Object, MyString As String
Set RegEx = CreateObject("VBScript.RegExp")
MyString = cell.formulas
With RegEx
.Pattern = "=*[0-9., ]+"
End With
RegEx.test(MyString) 'True if MyString is a number false if it's a function
You'll need to activate "Microsoft VBScript Regular Expression" though.

VBA: Loop Running - Not Throwing Error. Not Performing

Hope you're all well. I am in the process of working through an excel sheet that has 132 rows of data. In Column H of that data I have cells of comma separated values, that contain a list of countries. The problem with the list of countries is that I keep receiving it in a non-standardized format. I am attempting to standardize it now. With some help, I have written a VBA macro that is supposed to loop through column H, with the standardized values, and their non-standardized values in a separate sheet, Sheets(4). In Column A of Sheets4, I have the non-standardized value, in column B of Sheets(4) I have the standardized values, which I desire to be brought over and then replaced for the various non-standardized values in column A.
When I run the macro however, it appears as if it is not running at all. It takes about 5 minutes to run, and when it's done, none of the changes have occurred. Here are some of the things I have tried to make sure that none of the obvious things are at work with the macro:
I have tried to deliberately insert the exact error text I have in Column A of Sheets(4) of Sheets4, so that it will automatically pick up on the text, as they are the exact image and mirror of eachother.
I have gone into the "Views", "Local Window" and followed the variable step by step after running through the code step by step to make sure that I am actually following the proper procedure and that in each case it is picking up and detecting the the different errors in each case.
tried turning on and off the computer.
Does anyone have any thoughts on what I should do in order to get this Macro running?
Sub Translate_Country_Name()
'Variable Names
Dim Ary As Variant
Dim i As Long
With Sheets(4)
Ary = .Range("A2", .Range("B" & Rows.Count).End(xlUp))
End With
With Sheets(1).Range("H:H")
For i = 1 To UBound(Ary)
.Replace Chr(160), " ", xlPart, , , , False, False
.Replace Ary(i, 1), Ary(i, 2), xlPart, , True, , False, False
Next i
End With
End Sub

Replace periods with commas ends up with period deletion

This is my first month with VBA and I've overcome so many obstacles and reduced walls of code with loops, made code pretty much uncrashable, even when user using macro doesn't know what he/she is doing, but I am stuck with this:
If i = 1 Or i = 2 Then
Columns("F:F").Select
Selection.Replace ".", ","
Selection.NumberFormat = "dd\/mm\/yyyy hh:mm:ss"
End If
For some reason the result of replacement of:
438595.73402778 is this 43859573402778
I tried different variations from recording the macro to gradually simplifying the code and ended up with above. Always same result. What am I missing here?
The code is kind of complex, because I have to take data from 6 temporary workbooks into 4 sheets, secure it, depending on user login etc. It works great, but I thought, let's make it even better, because 3 out of those 6 qlikview workbooks have incorrect format in 1 of 4 time tracking columns.
It's kind of sad that I had to write my first post for such thing
I assume your current data is actually string data looking like numeric values. If column F is formatted to General and these "string" numbers appear, then you could change that around using Range.TextToColumns. For example:
Sub Test()
Dim lr As Long, rng As Range
With Sheet1
'Get last used row of column F and set rng
lr = .Cells(.Rows.Count, 6).End(xlUp).Row
Set rng = .Range("F2:F" & lr)
'Replace dot with comma and change to numeric
rng.TextToColumns Destination:=Range("F2"), DataType:=xlFixedWidth, DecimalSeparator:=".", ThousandsSeparator:=","
rng.NumberFormat = "dd\/mm\/yyyy hh:mm:ss"
End With
End Sub
Seems like you have different decimal separator settings in Excel files.
Go to Options-> extended-> use systems decimal separator.
This option may be off on some workbooks and ,is set as decimal separator.
to fix:
If Application.International(xlDecimalSeparator) = "," Then
MsgBox "Wrong decimal separator(,)!!"
Application.UseSystemSeparators = True
End If
If you want to output dot but leave comma the separator use
With ThisWorkBook.WorkSheet("Sheet1")
MsgBox Str( .Range("A1"))
End With
See Using VBA to detect which decimal sign the computer is using

Excel Changes number value automatically

I´m trying to remove the dollar sign in a column which should only include numbers. Therefore I tried to to use simply change the cell format to number but nothing changed.
Now I copied the values inside a text editor and removed the dollar signs. After inserting excel automaticallly changes some values to different numbers.
For Exaxmple it changed 8.59 to 21763,00. When I change the cell format to standard then it displays me something like 28 Jan except 8.59.
In this picture I tried to illustrate my problem with the different columns. Sold Price in Thousands is the original column which I liked to change.
Select the cells you wish to fix and run this short macro:
Sub FixData()
Dim r As Range, s As String
For Each r In Intersect(Selection, ActiveSheet.UsedRange)
s = r.Text
If Left(s, 1) = "$" Then
r.Clear
r.Value = Mid(s, 2)
r.NumberFormat = "0.00"
End If
Next r
End Sub
this is a known issue and the only work around that you can use is the following:
Copy the correct values in notepad.
From notepad make a Find and Replace in order to remove the $ sign.
Select a blank column in excel and set its format to TEXT.
Only now you can copy back the values from notepad to the new TEXT column.
This should fix your issue.

VBA remove " from cell content in a range

I am new to vba coding (and coding in general) but I have started doing a small macro that transfers values of a csv file into an excel file.
My next step is to remove the quotation marks in each cell. I have tried these lines of codes in my sub:
Dim Table As Range
Dim Cell As Variant
Set Table = Range("A1:currentregion")
For Each Cell In Table
cell.value2 = Replace(cell.value2,""","") *I get a syntax error here*
Next Cell
I know this is very basic but I can't find a solution on the net or using the macro recorder. If anybody could tell me what I am doing wrong and also what code I could use to change the value in a cell that contains a string of numbers into a numeric value?
Thanks!
You don't need to loop through each cell. The Range("A1").CurrentRegion may be operated on as a whole.
With Range("A1").CurrentRegion
.Replace What:="""", Replacement:=vbNullString, LookAt:=xlPart
End With
Note that to look for a single quote (e.g. ") you need 4 quotes in a row. An alternative is Chr(34) as a quote symbol is the 34th ASCII character.
Addendum:
With regard to the second portion of your question, changing text that looks like a number to actual numbers is best done with a quick Text to Columns ► Fixed Width command. Each column would have to be run through individually but this can be accomplished within the .CurrentRegion.
Dim c As Long
With Range("A1").CurrentRegion
.Replace What:="""", Replacement:=vbNullString, LookAt:=xlPart
For c = 1 To .Columns.Count
.Columns(c).NumberFormat = "General"
.Columns(c).TextToColumns Destination:=.Columns(c), _
DataType:=xlFixedWidth, FieldInfo:=Array(0, 1)
Next c
End With
There is the question of what number format the columns were in to begin with. If they were Text (e.g. '.NumberFormat = "#"` then removing the quotes is not going to convert them to true numbers. I've added a reversion to the General number format to accommodate this. If you have existing number formats that you wish to keep, there are more precise ways of reverting the number formats of some of the cells.
Cell.Value2 = Replace(Cell.Value2, Chr(34), "")
There always is a workaround, this one is referencing via character code.
You should dim Cell as Range. Also it's not a very good idea to name a variable using a VBA syntax element. Use MyTable and MyCell instead.
And to set the range better use
Set MyTable = [A1]
For Each MyCell In MyTable.CurrentRegion
...

Resources