VBA Issue with Number formatted as text when numbers include comma - excel

I use a vba script to open another workbook. This workbook is in format .XLS and the content from a DB was stored like:
"Name1" "0" "7,98"
"Name2" "5" "1"
"Name3" "2" "7,1"
When opening the workbook with a VBA script, every cell that includes a comma, is interpreted as text and shows this warning:
The number in this cell is formatted as text or is preceded by an apostrophe
Strangely, if I open the file by double clicking, the numbers are just formatted as text and don't show any error. I guess, Excel is doing some interpretting, which doesn't work.
My code is:
Dim WorkBookImport As Workbook
Name = Application.GetOpenFilename()
If Name <> False Then
Set WorkBookImport = Workbooks.Open(Filename:=Name)
End If
I tried everything from:
Range(mycolumn).Value = Range(mycolumn).Value
For loop with CDbl(.Value)
Range(mycolumn).TextToColumns ...
Nothing works ;( Please help!

Option Explicit
Sub edksg()
Dim c As Range
Set c = Sheet1.Range("D3")
c.Value2 = CDbl(c.Value2)
End Sub
Works fine for me when cell D3 of the worksheet is formatted as text.
Of course, my location uses the comma as decimal separator, so if your location uses a different standard, the issue might be there. In that case, doing something like CDbl(Replace(c.Value2, ",", Application.DecimalSeparator, 1, -1, vbBinaryCompare)) might solve that part of the issue.
If you want to loop through the entirety of some column, the end result might look something like this, assuming the values you want to convert to numbers are in column C.
Option Explicit
Sub edksg()
Dim c As Range
Dim r As Range
Set r = Sheet1.Range("C1:C" & Sheet1.Range("C" & Sheet1.Rows.Count).End(xlUp).Row)
For Each c In r
If Len(c) > 0 Then
c.Value2 = CDbl(Replace(c.Value2, ",", Application.DecimalSeparator, 1, -1, vbBinaryCompare))
End If
Next c
End Sub

It´s a problem with the formating of the cells. You should use NumberFormat to change it.
Sub FormatNumber()
ThisWorkbook.Worksheets("YourWorkbook").Range("YourRange") = CDbl(ThisWorkbook.Worksheets("YourWorkbook").Range("YourRange"))
ThisWorkbook.Worksheets("YourWorkbook").Range("YourRange").NumberFormat = "General"
End Sub
With NumberFormat you can also change it to text if you have the opposite problem, in this case you would use NumberFormat = "#"

Related

When recording macro, why is Excel using R1C1 format instead of A1 format for cell reference? [duplicate]

In recorded VBA macros, it seems that their formulas use R1C1 reference style. For instance, to fill in B4 with B2+1:
Range("B4").Select
ActiveCell.FormulaR1C1 = "=R[-2]C+1"
Does anyone know if it is possible to switch off this mode? For instance, let recorded macro look like:
Range("B4").Select
ActiveCell.Formula = "=B2+1"
I believe you cannot do that. The macro will always record in R1C1 style.
You can always switch the style but it will only be applied to the worksheet and if you record a macro it will still show R1C1 reference style.
It is very easy to understand the R1C1 style
In R1C1 reference style, the range is referred by how far the cells are located from the cell you are calling. For example, if you have 5 values from R1C1 to R5C1 and the range is called from R7C2, then the range would be R[-6]C[-1]:R[-2]C[-1]. Here the first cell in the range is 6 rows before the cell R7C2 and 1 column before the cell R7C2 and similarly for the last cell in the range.
If I take your example then "=R[-2]C+1" means that the formula is referring to a row which is two rows up (-2) and in the same column (0). Your formula is same as "=R[-2]C[0]+1"
EDIT
Here is a small function that I wrote which can help you convert R1C1 to A1 string
Sub Sample()
'~~> This will give you $B$2
Debug.Print R1C12A1("B4", "R[-2]C")
'~~> This will give you E227
Debug.Print R1C12A1("O9", "R[218]C[-10]", True)
'~~> This will give you $Y$217
Debug.Print R1C12A1("O9", "R[208]C[10]")
End Sub
Function R1C12A1(baseCell As String, sRC As String, Optional RemDollar As Boolean = False) As String
Dim MyArray() As String
Dim r As Long, c As Long
sRC = Replace(sRC, "R", "")
If Left(sRC, 1) = "C" Then
r = 0
Else
r = Replace(Replace(Split(sRC, "C")(0), "[", ""), "]", "")
End If
If Right(sRC, 1) = "C" Then
c = 0
Else
c = Replace(Replace(Split(sRC, "C")(1), "[", ""), "]", "")
End If
If RemDollar = False Then
R1C12A1 = Range(baseCell).Offset(r, c).Address
Else
R1C12A1 = Replace(Range(baseCell).Offset(r, c).Address, "$", "")
End If
End Function
Note: I have not done any error handling here. I am sure you can incorporate that if needed.
There used to be a facility to toggle relative reference when recording a macro.
When you have started recording, in the macro toolbar - near the stop button - there was a button to toggle relative reference; is this not the same as toggling R1C1 ? or isn't this available anymore?
I never bothered toggling it myself as like Siddharth says the R1C1 isn't too tricky to understand plus, irrespective of whatever you do, the VBA will need some editing so at the same time if you wish to use other syntax it's easy enough to change.
I've just played around with the following but it doesn't seem to help so maybe I'm mixing up the use of this button with R1C1...

Stripping Hyphens from Numbers in Excel VBA

I am new to Excel VBA and I need help removing hyphens from an Excel document. I usually use python, and could just use .strip, I was wondering if there is an equivalent in Excel. The cell I will be stripping the hyphens from is static, so the cell it self could be hardcoded I think.
I am trying to go from
233-79-01 to 2337901.
I tried these following lines of code
Sub striphyphen()
A5 = replace(A4,'-','')
End Sub
I am getting a compiling error, and am not sure why.
Any help would be appreciated
You can use replace as said #BigBen and #JvdV
Sub Test()
Dim myString as String
Dim newString as String
myString = "233-79-01"
newString = replace(myString, "-", "")
MsgBox newString
End Sub
Note That you can also set mystring = Cells(4,1).Value or mystring = Range("A4").Value
The problem is that you are wrongly referencing cells. The way you do it is the way to reference variables (just like in any other language).
To reference cell you can use one of the following (A4 cell for example):
Cells(4, 1) ' Cells(row, column)
Range("A4")
[A4]

Paste a value in Excel exactly as is visible

I have a simple request, to paste the data exactly as visible in Excel.
I have a list of dates in mm/yyyy format, but Excel keeps adding mm/dd/yyyy which is throwing off my analysis. It's formatted to show simply mm/yyyy but the actual cell value keeps getting set to mm/01/yyyy.
How can I simply copy/paste the value to be mm/yyyy.
I've tried Range("A1").Value = Range("A1").Value, but of course that just keeps the same info.
Yes, in my case since it's dates, I can do a kludgy function that takes the left three characters, and combines with the rightmost four. However, that really just gets the date number returned. I tried on G4 and get 4171730. Plus, I'd like to know how to do this with other types of cell values too (strings, numbers, etc.).
save the value and the format then set the cell as text and assign the formatted value:
Sub test()
Dim t As Variant
t = Range("A1").Value2
Dim x As String
x = Range("A1").NumberFormat
Range("A1").NumberFormat = "#"
Range("A1").Value = Format(t, x)
End Sub
This also works
Sub test()
Dim t As String
t = Range("A1").Text
Range("A1").NumberFormat = "#"
Range("A1").Value = t
End Sub
Range("A1").Value = Format(yourdate, "mm/yyyy")

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

How can I obtain the displayed value instead of actual value in Excel?

I have a cell containing a date ex. "05/11/09"
It is currently displayed as "11-MAY-09". How do I copy-paste or use VBA to get the string "11-MAY-09" into the cell next to it ( NOT "05/11/09")?
I can't figure it out other than piecing out the date pieces by itself.
Range("B1").Value = Range("A1").Text
Using the cell's .text instead of .value modifier will copy the text formatting instead of the raw date.
Chuck
I believe you can use the TEXT function to format a date value to your liking.
The format string of "dd-mmm-yy" would format "05/11/09" as "11-MAY-09".
Use the Format function.
Format("5/11/2009", "DD-MMM-YY")
This will return:
11-May-09
If case matters:
UCase(Format("5/11/2009", "DD-MMM-YY"))
returns:
11-MAY-09
"The same answer but with a different function (that has worked for me):
Public Function DisplayText(ByVal pRange As Range) As String
DisplayText = pRange.Text
End Function
Just use =DisplayText(A1). If you change the cell format this function will return the displayed text"
cc: alvaroc
How can I get the displayed value of a cell in MS Excel ( for text that was converted to dates)?
Try this:
Sub FormattedText()
Dim r As Range
On Error Resume Next
Set r = Application.InputBox(prompt:="Select cell", Type:=8)
If r.Count <> 1 Or r Is Nothing Then
Exit Sub
End If
On Error GoTo 0
ActiveCell = "'" & r.Text
End Sub
It will put text of a selected cell (prompted) in the active cell.
You should be able to right click on the cell and set the format as General. This will allow you to put something in without it being automatically formatted to something else.
To save yourself from copying and pasting you will also want to start by putting in the date you want and not formatting and then copying.
In VBA you can do this:
Range("B2") = Range("A2")
Range("B2").NumberFormat = "dd-mmm-yyyy hh:mm:ss" 'Date as 10-Jun-2005
If you need to loop it then:
Range("B" & i) = Range("A"& i)
Range("B" & i).NumberFormat = "dd-mmm-yyyy hh:mm:ss" 'Date as 10-Jun-2005
Another way to do it.
Low-tech but very easy way - paste it into Word, then copy back into Excel! Can take a while with a big file, however... buts works great for one-off uses!

Resources