I'm using OfficeOpenXml to create an MS/Excel spreadsheet file. Some of the columns contain arbitrary text values. However, when cells in those columns are filled with numeric values (i.e., text values containing only digits), Excel displays those cells with a small green triangle in the corner, along with the warning that "The number in this cell is formatted as text or preceded by an apostrophe".
Which is technically correct, but I do not want Excel to display the warning.
So how do I format those columns, or the cells in those columns, to be strictly text values, so that they will not be flagged as numeric text values? How do I disable the warning, and force Excel to accept those cell values as text (only)?
Note: I've seen solutions for other OpenXML packages, but none specifically for OfficeOpenXml. I've also seen solutions for interpreting text cell values as numbers, but this is the exact opposite of what I want to do.
Using DocumentFormat.OpenXml code in C# will look like this.
// Append sheetData to worksheet
worksheet.Append(sheetData);
// Ignoring errors for parsing
IgnoredErrors errors = new IgnoredErrors();
errors.AddChild(new IgnoredError() { NumberStoredAsText = true, SequenceOfReferences = new ListValue<StringValue>() { InnerText = "A:Z" } });
// of type Worksheet
worksheet.Append(errors);
I was looking for the same answer and I think this will get you close.
After the SheetData section, you need to create an IgnoredErrors section with IgnoredError elements. You can do a range such as:
<ignoredErrors>
<ignoredError numberStoredAsText="1" sqref="G2:G10"/>
</ignoredErrors>
You can create more than one element and you can span other types of fields.
In my case, I used the range "A1:{LastCell}" and it worked.
I figured it out by creating my "bad" xlsx document, going into excel and marking the range to ignore and saving as a copy. Then I used the Open XML 2.5 productivity tool compare files to see the difference. It didn't take long to find ignorederrors section and go from there.
Another solution is to us LoadFromText, which fills the cell text and seems to suppress the 'numeric text' warnings for the cell. So I use code like this for filling the cells that have this problem:
DataRow dr = ...; // Query result row
...
cell[r, c].LoadFromText(Convert.ToString(dr["item"]));
Related
I am trying to store all the values of an excel column in an array.
set rangeDate to {value of range "A14:A100"}
repeat with date in rangeDate
if (date as string is equal to "01/01/2001") then
log "It works"
end if
end repeat
In my Excel I do have an exact date of 01/01/2001 formatted in the specified columns. When I remove the range and it is just cell A14 (where the date is) it works. But when I include the range A14:A100 it doesn't work.
I am new to applescript, I guess that it doesn't store the values as array values and instead a string object? Any help would be appreciated
You have 4 issues :
1) value of range should not be between {}, but between ()
2) 'Date' is a reserved word in Applescript, so you should not use it as the variable in the loop. I replaced it with 'myDate'.
3) instead of converting your date to string to compare with "01/01/2001", it is quicker to keep comparing 2 dates, and then, compare with the date "01/01/2001"
4) I think it is a bug (at least with my Excel version), but the rangeDate variable is not a list of dates as expected, but for me a list of list : {{01/02/01},{02/02/01},………} Therefore, each member of 'rangeDate' is not a date, but a list made on one item which is a date ! I am not sure, but it could also be that range definition could be a list of ranges... So I am using item 1 of sub list.
Anyway, script bellow is working :
tell application "Microsoft Excel"
activate
tell active sheet of document 1
set rangeDate to (value of range "A14:A100")
repeat with mydate in rangeDate
set TheDate to item 1 of mydate
if TheDate = (date "lundi 1 janvier 2001 00:00:00") then
log "It works"
end if
end repeat
end tell
end tell
Quickly getting the values of a range of cells is great news! But even better is that you can fill in the values of a range by defining the value of that range. This is SO MUCH FASTER than doing it one cell at a time.
When I tried getting the value of a column (a range of cells), I received a list of lists. Each item in the list had only one value - that is the value of the cell.
To speed up complex operations, once you've got the list of values, take the process out of the "tell Excel" block and let AppleScript do the calculations. Then turn the result back into a list of lists and define the value of the range in Excel.
I had a problem reading ranges with some cells containing #VALUE! (failed formulas). I didn't find a solution on the Internet, so I thought it would be a good idea to share my solution here. Comments & improvement are surely welcome. I'm inclined to think there is a more straightforward solution to the problem than this. :)
Getting all values with value of range can lead to a problem messing up the output of the script. AppleScript doesn't consider a cell's content "#VALUE!" (= missing values) a value since it is, well, missing. Therefore the script doesn't include the cell's content in the list of values. This obviously messes up the cell order in the values list, since it has less items than the actual range has cells. In this situation it is quite impossible to return each value to its original cell in the workbook. Adding ”of ranges” to the code includes all cells with missing values solving the problem.
N.B. The values will be displayed as a one-dimensional array. Handling multi-column ranges requires more work. Nonetheless the missing values are included.
set celVals to (value of ranges of range "A1:A4")
E.g. {2.2.2022, 1.1.2011, missing value, 3.3.2033}
In order to return the values back to the workbook it is required to build back the list of lists. A missing value will be written to its cell as an empty string. Of course the original (failed) formula can be written instead, if needed.
N.B. again. This code applies to one column situation only. A little more is needed to put back a multi-column range. I'm sure you'll manage. :D
set returningCelVals to {}
repeat with i from 1 to count of celVals
set end of returningCelVals to {item i of celVals}
end repeat
set value of range ("A1:A4") to returningCelVals
EDIT: I knew there is a better solution. Here it is:
set celVals to string value of range "A1:A4"
String value gives a two-dimensional array of values and error messages of the range. String value gives also e.g. cell's currency symbols, so it is perhaps not suitable to all situations.
I a newbee in field of excel formula and need your help in a complex formula, where i need to extract phone numbers from a string of random text. This does not have a fix format for the string
Example set off strings:
Dring to data add9724516002
add 08107936777 to me pler
8000069633 plz add. Me
9000088106 mujhe bhi add karo dosto
I have already tried many formulas but nothing seem to work. Only thing fixed is the length of number, it should be either 10 digits or 11 (including initial 0)
You could use a RegExp via VBA
(which seems to be coming to Excel as a formula option sometime down the track, see uservoice
code
Function GetCode(strIn As String) As String
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = "\d{10,11}\b"
If .test(strIn) Then
GetCode = .Execute(strIn)(0)
Else
GetCode = "no match"
End If
End With
End Function
If they all look like the strings you have provided above, you could use Text to Columns. Let's say all of those strings were in A1:A4.
Select all four cells
Data - "Text to Columns"
Delimited
Use "space" to separate values
Finish
You will now have a large majority of your phone numbers pulled out, and it will look something like this:
(I've added a row above the data that makes every column its own set of data.. Column 1,2,3,4,5,and 6. I've also added another column in place of column A, Sort. This will be useful at a later stage)
Next, select A1:G5.
Click "Insert - Table"
"My table has headers"
OK
Your range is now a table, meaning you can sort the data via ascending order. I'm assuming you have hundreds of strings that you're sorting through. When you sort via ascending order, all numbers will show up first.
In the pic below I've sorted the first column of actual data, and there are two phone numbers at the top I can pull out:
If you ever want to revert back to your original lineup of data, click the Sort column to "Ascending"
I hope this is a good workaround to avoid VBA. You may not get all of the phone numbers, but probably a good chunk. You can also copy and paste columns C:G to the bottom of column A and sort everything at once if you only need all of the phone numbers.
If the strings that have numbers and letters attached are similar, you can also look into the RIGHT and LEFT formulas to pull out the numbers from the alphanumeric strings
I am looking for help on filtering multiple values in one cell delimited by a comma.
For example I have a spreadsheet with the following data:
Column A (Risk) Column B (Risk Mitigation)
Risk A Requirement1, Requirement2
Risk B Requirement2, Requirement6, Requirement7
Risk C Requirement1, Requirement3, Requirement9
When I filter on the 'Requirement Mitigation' Column I would like to see check boxes for the following:
Requirement1
Requirement2
Requirement3
Requirement4
Requirement5
...
Requirement9
So for my example when I only check the Requirement 1 filter box, only 'Risk A' and 'Risk C' rows would be displayed
Currently when I filter it does by the unique cell value, which gives me
Requirement1, Requirement2
Requirement2, Requirement6, Requirement7
Requirement1, Requirement3, Requirement9
Please note that above is just an example and I have thousand of individual requirements, so it would not be as simple as having one column per requirement.
I open to any suggestions including creating vbscripts.
Any help would be greatly appreciated.
This will be tricky.
First you'll need to create a form that will contain a list box and populate that list box with the Requirements you have in their correct syntax.
Then you'll need to create a loop that will go through every cell in a column and save each of them to a string, you could make a one dimensional string array to save them all in that as well.
Then you'll need a loop that will go through each string and use the split function to seperate the strings with a delimeter, you'll need to set your delimiter to ", " to ensure it seperates the strings at the commas.
Then you'll need a loop that will run after you've made your selection from the listbox in your form. this loop will go through every string in your 2D array and check if it contains any of the requirements in your listbox. If it is not, run the code: Range("B" & x).EntireRow.Hidden = True where x is the row, you can use one of the variables in your loop for this.
If you need more specific information that this I may need to see what you've already done, it is possible as well to use this method to automatically populate the list box in your form.
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).
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.