Writing matlab matrix to excel - excel

I am trying to export a matrix from Matlab to export with xlswrite. However, my matrix is a cellarray that has strings such as '001', '00323'. When it is exported into Excel, Excel automatically converts them back to numbers and drops the first 2 zeros into '1', and '323'.
Does anyone know how to force excel to accept them as Text as them are being written from Matlab to xlsx?
Thank you!
L.

Excel probably likes to do this because it is exactly what Excel would do if you typed those values in.
One way to fix this is to put '"=001"' in the cell array rather than '001' like the following code. Note that Excel treats the values properly in the resulting file:
myCell= {1, '0001', '="0001"'};
xlswrite('test.xlsx', myCell)
You could write a little function that surrounds all the strings in a cell array with quotes, if needed:
function aCell = fixForExcel(aCell)
for ind = 1:numel(aCell)
myVal = aCell{ind};
if isstr(myVal)
aCell{ind} = sprintf('="%s"', myVal)
end
end
end

I run into this issue with SSNs. I don't know how much control you have with creating the spreadsheet with xlswrite.
You can set the format to Text, and this preserves the leading zeroes.
The problem will remain that when you open the spreadsheet, all leading zeroes will be eliminated. You can create a custom format that specifies that the format for the cell has two leading zeroes. You can use "\0\0#" as your custom expression. The text format will be saved after the first time.
If you have a variable number of 0s, the only way to get around it is to copy the data into excel.

Related

vb.net 2010 Excel converting text fields to decimal

I am creating an excel object from a vb.net listview table simply by creating an array of F(x,y), creating a range and putting the values from the array in the range as follows.
shXL.Range(Startcell,AEndCell).Value = F
However some of the fields are numeric and I want them to be formatted to two decimal places and EXCEL to recognize them as decimals
What I end up with in the excel worksheet is many green triangles telling me they are text fields.
How do I convert a range withing the sheet say A5,I20 to be formated as decimals.
I tried: (x,y).numberformat = "00.00" which works to format to 2dp but still treats the cells as text.
Furthermore, is it possible to Excel Sum a range? How is the possible?
Your help is appreciated!
shXL.Range(Startcell,AEndCell).Value = F
'// Loop over same range and convert to decimal
For Each cell In shXl.Range(Startcell,AEndCell)
With cell
.Value = CDec(.Value)
End With
Next
Furthermore, is it possible to Excel Sum a range? How is the possible?
I don't think Excel would have got very far as a spreadsheet product if it couldn't sum a range!
Assuming you want to do this in vb.net you need to use the instance of the application. I'll assume in your code it's XL
mySumValue = XL.WorksheetFunction.Sum(shXL.Range(Startcell,AEndCell))

Excel formulas are not working - not recognizing numbers

I've pasted some numbers on Excel spreadsheet and wanted to do some calculations with it. The problem is that Excel isn't recognizing the numbers. I've already tried several methods to convert them into numbers and none of them works: paste/special multiplying by 1; formating each cell to the number/scientific number format. And there isn't also an error message on the top right corner of each cell like I've read on the internet indicating that there is a number written as text. If I retype each number, Excel recognizes it.
To make sure that the problem was really that the numbers were understood by Excel as text, I tried the functions ISNUMBER(), that returned FALSE and ISTEXT() that returned true.
I want to know how I can fix that problem without having to type into each cell.
Ps. the numbers are in scientific number format, i.e., 1,085859E+001 
Since the column is text the cells are formatted as text.
you use Value to convert the text into a number so the formula will work
A2 = 123
A3 = 123 Richard
Formula
=isnumber(A2) result is false
use
=isnumber(value(A2)) result is True
I was having the same problem, until I realized that the decimal separator was set as (,) instead of (.) in the default settings. Once I changed that, everything worked fine.
If your "numbers" are being detected as text, you can use VALUE() to make sure Excel understands that it is actually a number.
A1: `1.23E+10 (this is a string)
B1: =VALUE(A1)
=12300000000
C1: 1.23E+10 (this is a number)
D1: =IF(B1==C1,"It worked", "Uh Oh")
=It Worked (for me anyway)
I'm not sure what the comma in your scientific number will do so might want to have the function replace them if there not required.
See Kenneth Hobs' answer here: http://www.vbaexpress.com/forum/showthread.php?42119-Solved-Convert-exponential-format-to-a-number
Open your Excel File, Press Alt + f11 to open the VBA screen,
Go to Insert > Module, Copy and Paste Kenneth's code:
Sub Expo()
Dim cell As Range, s() As String, lng As Long, n As Integer
For Each cell In Selection
With cell
If Not VarType(.Value2) = vbString Then GoTo NextCell
s() = Split(cell.Value2, "E")
.Value2 = s(0) * 1 * (1 * 10 ^ s(1)) 'ePart(s(1))
.NumberFormat = "General"
.EntireColumn.AutoFit
End With
NextCell:
Next cell
End Sub
You can now run it as a macro to convert selected cells. Or if you want it as a function copy this code instead:
Function Expo(cell As Range)
Dim s() As String
With cell
If VarType(.Value2) = vbString Then
s() = Split(.Value2, "E")
Expo = s(0) * 1 * (1 * 10 ^ s(1)) 'ePart(s(1))
End If
End With
End Function
This way you can use it as a normal function in excel eg =Expo(A1)
As I mentioned in the comments above though, you will have already lost some degree of accuracy when the original number was converted to scientific notation. The best solution is to get the originating program to write the proper numbers into the text file if you can.
Open a new word document and try Pasting the web content in word first, the copy this content from the word document and paste special in excel, as text. This simple solution worked for me
Open a new blank Excel, then go to Data > From Text, this way you can import text and designate which format you want to convert to. On the Text Import Wizard page, select either Delimited or Fixed width (I am not sure how your original text file look like but generally it should be Delimited. On the next page, pick a Delimiter or enter one in Others. On step 3, you should see the data listed below and the data format on the upper left. Pick General for those columns that you believe should not be Text. This should fix your problem.
My case was stubborn, no response to Paste Special or CLEAN(). Finally resolved by copying the offending column of Excel data and pasting into new Notepad++ doc. This revealed a leading "?" in all the bad numbers (apparently some non-printing character). Used Search > Replace to find all "?" and replace with nothing. Edit > Select All, copy to a new Excel column, and voilà!
There may be hidden characters. Trailing/leading spaces may not visible and hence erroneously be neglected. If there is trailing/leading Space characters with numeric values, excel consider it as text.
Copy contents problematic cells to MS-Word [(Select problematic cells and copy them to MS-Word)] and check any hidden characters, Remove hidden characters with "find"/"replace" functionality.
I was having issues with numbers from PPT (e.g. ($3,000))pasted to excel. Tried multiple different ways to get the text to recognize including find replacing parens, commas, $ signs to blank and trying to format so excel could run formulas. The only option that worked was to paste to Word first then paste value to excel which worked without any additional formatting steps. Surprised I could not do it all within excel though. Maybe there's another way
Select all the cells to convert to a number.
|Data| Menu Tab > Data Tools > [Text to columns]
Delimited. [Next]
Deselect all "Delimiters". [Next]
"Column data format" > General
[Finish]
Verify by using =ISNUMBER(C16) in an spare cell, where C16 is a sample cell. Should now return TRUE.
This happened to me lately. I had forgotten that I had set formula recalculation to manual. The weird thing is that it was returing FALSE when initially created (which was correct) but given the test depended on the value of other cells that, when changed, did not trigger the change in the cell with the isnumber() formula.
Pressing F9 "fixed" my problem (and my ignorance).

Writing a char matrix to Excel using xlswrite

Could someone assist in writing a char matrix to Excel? The following is a <17x6 char>
A =
SPK01a
SPK03a
SPK03b
SPK05a
SPK07a
SPK07b
SPK07c
SPK09a
SPK11a
SPK15a
SPK17a
SPK19a
SPK21a
SPK23a
SPK25a
SPK27a
SPK29a
I was trying to do xlswrite(filename, {A}) but receive the error:
Error using xlswrite (line 220)
ActiveX - Element of a cell array cannot be a character matrix.
I need the strings to be in cells, so in this case, in the first column in Excel, in 17 separate cells.
You can use cellstr to make a properly shaped cell array:
xlswrite(fileName,cellstr(A))
cellstr provides a quick way to place each row of a character array into a separate cell, and it will remove trailing spaces at the end of each row.
Use mat2cell to convert your matrix of characters into a cell array and use that to write into an excel file -
xlswrite(xls_filename,mat2cell(A,ones(1,size(A,1))))
This will write everything to the first column of the excel sheet, but in different rows.

Cast "Accounting" formatted numbers as text in Excel

Here's the deal. I'm using a code-based advanced filter to do a database search. The criteria (as generated by the code) treats all data as text and appends a * to the front and back end of anything entered to facilitate partial lookups.
One of my fields (just one, in the middle of the data, and indistinguishable otherwise) is formatted as "Accounting". I want to format it as text so that it is query-able. But when I use the TEXT() function to try and format it (as I do in any other case where I need numbers stored as text), it won't accept "Accounting" as one of the presets. And furthermore, if I attempt to copy-paste the format from Excel's own custom formats form like so: _(* #,##0.00_);_(* (#,##0.00);_(* "-"??);(#_), then I get a #VALUE error in the cell.
By selectively trimming that format string I've gotten to where it no longer presents an error, but cannot get the numbers in the column to align on the decimal (which is the point of Accounting format).
Please help.
You get the #VALUE error because the format string has double quotes in it. If you use
=TEXT(B2,"_($* #,##0.00_);_($* (#,##0.00);_($* ""-""??_);_(#_)")
with the double quotes escaped (by doubling them) you won't get the error. But you won't get the desired result. There are some subtle differences between number formats and what the TEXT function will produce. I don't know what they all are, but this is one.
One option you have is to write your own function. This function will convert the accounting formatted number into a string and preserve the white space between the currency symbol and the first number.
Public Function GetRealText(Cell As Range) As String
Application.Volatile
GetRealText = Cell.Cells(1).Text
End Function
There is a catch, though. If you resize a column, the Range.Text property will change, but this function will not update automatically. Even though it's Volatile, a column width change won't trigger a recalc. You'd have to recalc manually or something else would have to trigger it.
You can put a number, date or any value as text by using the ' prefix:
Cells(1, 1) = "'" & MyNumber
Multiply the formula times 1 and then the format cell containing the formula as Accounting
Cell A1 =5000
=TEXT(A1,"$#,##0.00") gives you currency.
=TEXT(A1,"$#,##0.00")*1 now it's back to a number and displays as your cell format. Format as Accounting

Excel number formatting. Treat my cell as a number but leave its formatting alone! (ie Trailing 0's)

I have (what seems like it should be) a simple problem. I need to be able to tell excel (in vba) that a cell's contents are numeric, but I don't really want to apply any formatting to it. I need my trailing zeros left how they are. Am I missing something incredibly simple?
Update:
I'm getting xml data from a query and am placing it into the spreadsheets. But lets say one of the cells has 589.950000 I need to keep those additional zeros on display for the user (don't ask me why, they just want the precision) but excel converts it to 589.95. I also need for them to be able to do spreadsheet calculations on that cell (so I can't format it as text).
Update 2:
Further Clarification. Lets say I have 4 values that I'm going to place into a column
595.56000
15.00
90.00050
1919.120000000
is there one numeric format that I can apply to that column that will display those exact numbers?
You can't do this with one custom format.
What you can do is make a macro that does the input for you and modifies each cell format as it puts the value into it. You can use the Macro Recorder to get a handle on where to start with this.
I think you can do:
Val(Range("A1").Value)
Which will evalulate the text to a number
You mean you want to use the value of the cell as a numerical one but you don't want to change the real val of the cell ?
In vba, you can use CInt(yourvar) to convert a string to number. Thus, the value you get will sure be an integer.
[edit] Btw, if you want to display or set back the value to a cell with the format you want, you can use the Format ( expression, [ format ] ) function of Excel vba
[edit 2]
As you cannot predict how many zeros you will have, i can't see any number format that would work. You'd probably better use the Text format as Lance Robert suggested. To use formula on text cells, you can use the VALUE formula to convert the cell to use it as a number. If you need it on a range, you may have to use array formulas like this : {=SUM(IF(ISTEXT(A1:A4);VALUE(A1:A4);A1:A4))}.
Please let us know if you want some help on these formulas.
Regards,
Max
If you know the number of decimal places you need, you can use something like the following:
Range("A1").NumberFormat = "0.000000"
I suppose you could even get fancy and check the number of trailing 0s in the code and adjust the formatting as required.
UPDATE:
Here's a VBA function that takes the number as a string and returns the appropriate NumberFormat string.
Private Function trailing(strNum As String) As String
'From number entered as string, returns Excel Number format to preserve trailing zeroes in decimal.
Dim decpt As Integer
Dim aftdec As Integer
Dim strTmp As String
decpt = InStr(strNum, ".")
If decpt = 0 Then
strTmp = "0"
Else
aftdec = Len(strNum) - decpt
strTmp = "0."
If aftdec <> 0 Then
For i = 1 To aftdec
strTmp = strTmp & "0"
Next
End If
End If
trailing = strTmp
End Function
Can't believe I just stumbled on this...
I know it's old but might as well give very simple answer:
Custom format and simply use # symbol. Will be treated as integer and left exactly as typed in to cell.

Resources