VBA remove " from cell content in a range - excel

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
...

Related

Pasting Values as Displayed

I have a column of cells in excel that have the following formatting: "0000.00"
FYI, the quotes are not part of formatting.
Basically, four digits followed by two decimals. However, when the numbers are like "600", they need to be displayed as "0600.00". However, the list of numbers provided to me are displayed that way through formatting, so if I am trying to VLOOKUP, it can't process it; it sees "600", not "0600.00" that is displayed to me.
I am aware of PasteSpecial Paste:=xlPasteValues, but this pastes "600", not the "0600.00" that is displayed to me. Currently I can achieve such results by copying the values and pasting them into notepad —which suggests to me there is a way to do this— but I'd like to create a macro to do this for me.
Sorry for any redundant explanation, just wanted to avoid getting answers relating to pasting values only, which is not what I am looking for.
As you said, to use VLOOKUP with formatted text as the lookup value, you'll need the value of the cell to match with the value of the lookup value, so you'll have to convert the value in the cell to text with something like this (example for a single cell):
Dim rng As Range
Set rng = Range("A1")
rng.PasteSpecial xlPasteFormulasAndNumberFormats
Dim TextValue As String
TextValue = Format(rng, rng.NumberFormat)
rng.NumberFormat = "#" 'We need this line to turn the cell content into text
rng.Value2 = TextValue
I'm pretty sure no PasteSpecial options will allow you to do what you want in a single operation, so this solution is a workaround that does it in two steps.
Multiple cells case:
I realize that the code above doesn't address the issue of pasting multiple cells, so here's a procedure that can be used to copy the formatted number as text from one range to another:
Sub CopyAsFormattedText(ByRef SourceRange As Range, ByRef DestinationRange As Range)
'Load values into an array
Dim CellValues() As Variant
CellValues = SourceRange.Value2
'Transform values using number format from source range
Dim i As Long, j As Long
For i = 1 To UBound(CellValues, 1)
For j = 1 To UBound(CellValues, 2)
CellValues(i, j) = Format(CellValues(i, j), SourceRange.Cells(i, j).NumberFormat)
Next j
Next i
'Paste to destination by using the top left cell and resizing the range to be the same size as the source range
Dim TopLeftCell As Range
Set TopLeftCell = DestinationRange.Cells(1, 1)
Dim PasteRange As Range
Set PasteRange = TopLeftCell.Resize(UBound(CellValues, 1), UBound(CellValues, 2))
PasteRange.NumberFormat = "#" 'We need this line to turn the cells content into text
PasteRange.Value2 = CellValues
End Sub
It's basically the same idea, but with a loop.
Note that if the formatting is always the same, you could make it a variable and apply it to every values in the array instead of calling .NumberFormat on every cell which inevitably adds a little bit of overhead.
Sidenote
One could ask why I'm not suggesting to use :
SourceRange.Cells(i, j).Text
instead of
Format(CellValues(i, j), SourceRange.Cells(i, j).NumberFormat)
And that would be a very good question! I guess, the fact that .Text can return "###..." when the column isn't sized properly always makes me afraid of using it, but it certainly would look much cleaner in the code. However, I'm not sure what would be better in terms of performance. (Relevant article by Charles Williams)

VBA code changes from text into numeric value of a range, however no tall the columns?

i wrote a code in VBA to change values in a range from text into general (number). it works fine, however there is one issue. when i checked all the column values, only the string with an integer value ("2345") is changed to integer (2345) but the strings with float values ("123.456") didn't change at all, the type changed into General but the value stay the same.
here is the vba code
If (ws.Name = "TB") Then
shTB.Activate
[A:A].Select
With Selection
.NumberFormat = "General"
.Value = .Value
End With
results as the table below, still the float values didn't change at all. as you can see only row 119 changed into Number or integer.Any suggestion or help is appreciated highly!
It is clear from your results that there is a mis-match between the text format of your data and your Locale settings.
You data appears to have come from a source in which the comma is the decimal separator rather than the period. Try:
Sub dural()
With Range("A:A")
.NumberFormat = "General"
.Replace ",", "."
.Value = .Value
End With
End Sub
if that "." stands for thousands separator then just remove it
With shTB.Range("A:A")
.Replace what:=".", replacement:=vbNullString
.NumberFormat = "General"
End With
BTW, as you see you don't need to select anything: just act on its direct reference

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

Trim data where some cells contain space, some contain formula

I have a large amount data in an Excel file. I have over 3000 rows which cross A to CZ columns.
Before I start using the data, I need to trim all of it.
When I use VBA it takes a long time and I get error "Type not match".
Some cells contain space, some contain formula, some contain formula link with another Excel file.
Worksheets("Sheet1").Activate
For Each cell In ActiveSheet.UsedRange.SpecialCells(xlCellTypeConstants)
If cell.HasFormula = False Then
cell.Value = Trim(cell)
End If
Next cell
It want to trim the cells which do not have a formula but it gets the error.
Text-to-Columns, Fixed width, Finish will quickly remove leading/trailing spaces.
dim i as long
with Worksheets("Sheet1")
for i=.cells(1, .columns.count).end(xltoleft).column to 1 step -1
with .columns(i)
.cells.TextToColumns Destination:=.cells(1), DataType:=xlFixedWidth, _
FieldInfo:=Array(0, 1)
end with
next i
end with
BTW, if you want to reduce multiple interim spaces (e.g. data data to data data) to a single space, you need to use Application.Trim(...) not VBA.Trim(...).
Worksheets("Sheet1").Activate
For Each cell In ActiveSheet.UsedRange
If Not IsError(cell) Then
cell = WorksheetFunction.Trim(cell)
End If
Next cell
finally i use this code to ignore the error. i know it is not a good method.

Zero Length String Microsoft Access

In excel, I have a text string, which contains numbers and text, that I strip the numbers out of with a formula. However, sometimes it is possible that the text string will be blank to begin with so if this happens I use "" to return a blank instead of a 0. When I link this excel sheet to an access database it will not let me format this column as currency because it is picking up the "" as text along with the stripped out numbers as numbers. Any solutions on how to fix this? Is there another way besides "" to make a cell completely blank and not a zero length string?
This is along the lines of the problem I am having:
http://support.microsoft.com/kb/162539
Here is a quick routine that reduces formulas to their values and strips zero length strings to truly blank cells.
Sub strip_zero_length_string()
Dim c As Long
With Sheets("Sheet1").Cells(1, 1).CurrentRegion
.Cells = .Cells.Value
For c = 1 To .Columns.Count
.Columns(c).TextToColumns Destination:=.Cells(1, c), _
DataType:=xlFixedWidth, FieldInfo:=Array(0, 1)
Next c
End With
End Sub
I'm using .CurrentRegion so there can be no completely blank rows or columns within your data block but that is usually the case when preparing to export to a database.

Resources