I’m having an issue when exporting values (using VBA code, not via an export to CSV) from an Excel spreadsheet to a text file.
Using these numbers:
- (formatted so 0 displays as "-")
0.10000000
0.0166666666666667
If I debug.print the .Text then .Value property of each cell, the results are:
- --> 0
0.10000000 --> 0.1
0.01666667 --> 1.66666666666667E-02
My issue is, I want to avoid the 0.0166666666666667 (in the spreadsheet cell visually) –> 1.66666666666667E-02 (in the cell’s .Value property) conversion to happen.
If I read the .Text property instead, the result comes out as a decimal as desired, but the problem then is that the 0 formatted as “-” is exported as “-“.
Is there a “proper” way to handle this that will work in all scenarios?
I have to use the final solution across multiple spreadsheets, and I have no control over the display format settings in each spreadsheet, or the contents of each cell (ie: not guaranteed to be numeric data)
Example Code
Public Function test()
Dim cell As Range: Set cell = Worksheets("Sheet1").Range("A1")
Dim i As Integer
Dim vSingle As Single
Dim vVariant As Variant
Dim vDouble As Double
For i = 0 To 4
vSingle = cell.Offset(i, 0).Value
vVariant = cell.Offset(i, 0).Value
vDouble = cell.Offset(i, 0).Value
Debug.Print cell.Offset(i, 0).Text & " --> " & cell.Offset(i, 0).Value & " : " & vSingle & " : " & vVariant & " : " & vDouble
Next
End Function
Results in:
- --> 0 : 0 : 0 : 0
0.10000000 --> 0.1 : 0.1 : 0.1 : 0.1
0.01666667 --> 1.66666666666667E-02 : 1.666667E-02 : 1.66666666666667E-02 : 1.66666666666667E-02
--> : 0 : : 0
--> : 0 : : 0
I can’t replicate your issue, but perhaps you can use the following code to help. Basically, you can check if it’s numeric, then store it into a strong-typed variable, and then export that. You can use something like this: