How to get Excel to ignore apostrophe in beginning of cell - excel

I'm writing a tool that syncs a simple database with Excel sheets. Each item in a table in the database corresponds to one row in the worksheet. I read the Excel sheet into the tool using C# and the Excel interop com interface, then compared the items' values (i.e. one of the columns in the excel sheet) after the sync just to make sure that they are equal.
Yesterday I found a case where the comparison wasn't true:
"'<MedalTitle>' Medal - <MedalDescription>"
"<MedalTitle>' Medal - <MedalDescription>"
The second is the one I've read in from Excel, and as you can see it's skipped the first apostrophe. Is there a way to tell Excel to treat the cell as just text (no, just setting the cell's formatting doesn't help)?
I even tried to copy the value ( 'hello' ) of a cell in VBA like this:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Target.Offset(1, 0).Value = Target.Worksheet.Range("b2").Value
Target.Offset(2, 0).Value = Target.Worksheet.Range("b2").Formula
Target.Offset(3, 0).Formula = Target.Worksheet.Range("b2").Formula
Target.Offset(4, 0).Formula = Target.Worksheet.Range("b2").Value
End Sub
The result was that the value of target cell is always hello'
If there is no way, I'll have to do something ugly like
if (dbitem.value[0] == ''' )
{
// stuff
}
else
{
// regular comparison
}

I'm afraid the apostrophe ' is a special character for Excel when it appears as the first character in a cell as you've found. It tells Excel to treat the rest of the string as text, so that you can enter something like '34.2 in the cell, and it'll treat it as the string instead of the number (for formatting and so on).
I suggest doing something similar to what you've suggested, except that where you're putting it into Excel, check the first character, and add an extra ' if there's one there already.
Alternatively, you could prepend an apostrophe to all values - if you want them all as text that is. That way you don't need the extra first character check.

Look at the PrefixCharacter property of the Range object which corresponds to that cell
From the help:
If the TransitionNavigKeys property is
False, this prefix character will be '
for a text label, or blank. If the
TransitionNavigKeys property is True,
this character will be ' for a
left-justified label, " for a
right-justified label, ^ for a
centered label, \ for a repeated
label, or blank.
The TransitionNavigKeys part relates to Lotus 1-2-3 compatibility so it's more than likely going to be False
Answer based on article at:
http://excel.tips.net/Pages/T003332_Searching_for_Leading_Apostrophes.html
(warning: slightly annoying pop-up may appear)
edit: actually this probably isn't going to be any use because PrefixCharacter is read-only :(
edit2: I was right the first time. PrefixCharacter only gets populated if the value added to the cell started with ' so just read back PrefixCharacter plus Value and concatenate. As long as TransitionNavigKeys is False, that is

try targetcell.Value instead. .Formula is the formula seen in the formula bar while .Value is the evaluated value of the cell.
So, I am guessing that you would have used .Formula in your original code as well. Changing that should work.
EDIT: Ok, it did not work (embarrassed).
Excel treats the starting single quote specially.. so specially that even obscure cell / range properties do not have access. The only workaround I could find is essentially the same as what you thought initially. Here goes:
If VarType(cell) = 8 And Not cell.HasFormula Then
GetFormulaI = "'" & cell.Formula
Else
GetFormulaI = cell.Formula
End If

You might try pre-pending a single quote to your text fields ( '''' + dbField ) in your query so that for fields with embedded single quotes your query would return:
"''stuff in single quotes'"
which when placed in an Excel cell would convert to:
"'stuff in single quotes'"
for characters that weren't in quotes you would get:
"'stuff that wasn't in quotes"
which when placed in an Excel cell would convert to:
"stuff that wasn't in quotes"
Worth a shot. :-)

Related

How to hide part of cell content?

I want to hide part of the cell content in Excel like in MS Word where we can set the Hidden property of a selected text. The idea is to display a representative part while the underlying data can be retrieved by Range(...).Value2. Unfortunately, I don't see the Hidden property in Excel's Font object.
As an alternative, I thought some custom number format could be used. I found the content placeholder #, so I can hide, replace and pad text. However, I don't see an option to display content partially.
Is it possible to set the displayed part of the text in cells?
update Jun 26, 2022
At the moment I'm using a combination of event handling and number formatting. Something like this:
Private Sub Worksheet_Change(ByVal Target As Range)
Const Data = "A1" ' data area to look for
Dim Common As Range
Dim Cell As Range
Set Common = Intersect(Target, Range(Data))
If Common Is Nothing Then Exit Sub
For Each Cell In Common
Cell.NumberFormat = GetFormat(Cell.Value2)
Next Cell
End Sub
Private Function GetFormat(ByVal Value) As String
' Return the first five characters for demonstration purposes
Const Quote = """"
Dim Output as String
Output = Left(Value, 5) & "..."
GetFormat = ";;;" & Quote & Output & Quote
End Function
with this result:
As before, I hope this process can be simplified.
As you stated in your answer, there is no hidden Font property in Excel as one can find in Word. However, there are a variety of workarounds that would give the same functionality of "sort of hidden" (note that this is not a security feature). The use case for this in Word seems (to me) somewhat minimal except maybe to change the way something is printed and keeping notes? Comments and Notes in a cell would probably be more appropriate.
I was first thinking of using a font color, but that is functionally different than the Hide property because the Hide property removes the text rather than whites it out (so you would have a blank space the length of the hidden text).
Overall, I think that using an if statement within a string of your text with a global true/false driving cell would probably be the closest thing.
For example if cell A1 had either true or false, then any cell with the below formula could toggle between showing and not showing the hidden text:
="I have "&IF(A1,"a hidden text ","")& "to think about."
If you never wanted the text to be visible, then you could just hard code it false.
="I have "&IF(False,"a hidden text ","")& "to think about."
While not directly related to your question, if you were looking to have some notes within a cell formula that was a value (not text), the N function has been something I've used as it converts any text to zero, so it can be included after a calculation. Example:
=SUM(A:A)+N("This is a summation of all values in column A")

Reference combined cell above

I have a sheet with a lots of columns ordered in a hierarchical way with the cells merged:
I'd like to name those columns (in example: row 5) like this:MainGroupA-SubGroupA-SubSubGroupA.
Simply referencing the columns above in the classic way won't work as the field above isn't available anymore. (In the example: the fields B1 to F1) (i.e. I can't enter A1&A2&A3 / R[-4]C&R[-3]C&R[-2]C as this formula tries to read from the "hidden" cells).
Is there a way to do this without manual work or the need to un-merge the parent-cells? I might be able to do this with some external text editor or even VBA but would prefer an "Excel formula solution" as it would stay updated for new groups and columns.
To Clarify: I'd like all columns in Line 5 to have the text like in A5
If you want:
MainGroupA-SubGroupA-SubSubGroupA
in A5 then this should work:
=A1&"-"&A2&"-"&A3
Edit Then try:
=OFFSET(A1,0,1-MOD(COLUMN(),6))&"-"&OFFSET(A2,0,MOD(COLUMN(),2)-1)&"-"&A3
though this won't give the same text as in A5 across the complete row.
The answer from pnuts is great and helped me solve some test cases. It was however a little difficult to adapt and produced empty strings for the last column, so I also wrote a VBA-Function to do exactly what I need.
Open the VBA Editor (ALT + F11) and enter the following code in a new module:
Public Function checkLeftIfEmpty(start As range) As String
If start.Cells.Count > 1 Then
checkLeftIfEmpty = "Only a single cell allowed as parameter"
Exit Function
End If
Dim currentRange As range
Set currentRange = start
Do While currentRange.Column >= 1
If currentRange.Value <> "" Then
checkLeftIfEmpty = currentRange.Value
Exit Function
Else
Set currentRange = currentRange.Offset(0, -1)
End If
Loop
End Function
You can now use the function checkLeftIfEmpty to find the first cell left-side from your parameter which contains text: (This will be the text of the merged cell itself, if applied to a "hidden by merge" cell)
And also in combination to concatenate a string:

Excel: Formula to extract a string of text delimited by markers from cells

I'm messing with a spreadsheet containing postal addresses that have been inserted in the cells' comments
Each comment contain an address composed of a variable number of lines (damn UK addresses, they can have up to 7 lines!) in the following format:
Line1,
Line2,
Line3,
[...],
State
With my poor skills, I've managed to extract the comment with a VBA script, obtaining the following string on a single cell:
Line1,Line2,Line3,[...],State
At this point each string between commas must be extracted to its own cell.
I've managed to extract the 1st 3 lines with the following formulas:
For Line1:
=LEFT(A8;(SEARCH(",";A8))-1)
For Line2:
=MID(A8; SEARCH(",";A8)+1; SEARCH(","; A8; SEARCH(","; A8)+1)-SEARCH(",";A8)-1)
For Line3:
=MID(A8; SEARCH(",";A8;SEARCH(",";A8;SEARCH(",";A8;SEARCH(",";A8)))+1)+1;SEARCH(","; A8; SEARCH(","; A8;SEARCH(",";A8)+1)+1)-SEARCH(",";A8;SEARCH(",";A8)+1)-1)
From this point I start to get overflow errors from my brain... I probably need some days of sleep.
Can anybody help me to get to "line6", and finally suggest me how to pull out the "State line" which ends without comma?
I thought I could pull out the "State" line with =RIGHT(",";SEARCH(",";A8)-1) but I'm obviously doing something wrong because that pulls out a comma instead of a string.
I guess I could do everything with a VBA script, but I'm not that skilled yet :(
With comma separated data in A1, in B1 enter:
=TRIM(MID(SUBSTITUTE($A1,",",REPT(" ",999)),COLUMNS($A:A)*999-998,999))
and copy across. For example:
Note:
Why not use TextToColumns ?
The row of formulas re-calculates automatically if A1 changes.
The row of formulas will work even if A1, itself, contains a formula.
If you are wanting to do this programmatically instead of using a built-in, check out the split function for chopping up your comma separated string. It will split up your input string into an array. Then you can do whatever you like with the array.
Dim Names() As String
Names() = Split(inputValue, ",")
For i = 0 To UBound(Names)
' do what you want with each piece
Next
Gary's Student's answer is great for using the built-in functions.
If you want a VBA solution:
Sub spitString()
Dim sourceRange As Range
Dim stringArr() As String
Dim i As Integer
Set sourceRange = ActiveSheet.Range("A1")
stringArr = Split(sourceRange.Value, ",")
For i = LBound(stringArr) To UBound(stringArr)
sourceRange.Offset(0, i + 1).Value = stringArr(i)
Next i
End Sub
You could avoid adding comments: Are you aware that users can add line breaks inside a cell by pressing ALT+RETURN?
If having high rows d is a problem and you don't like that formatting, an alternative approach might be to write a simple bit of code that changes the height of the current row when a user clicks in a certain range. It would , make other rows less high. Perhaps.
Just a thought. It has benefits keeping it simple.
Harvey.

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 an input integer into a cell

I am writing a quick application myself - first project, however I am trying to find the VBA code for writing the result of an input string to a named cell in Excel.
For example, a input box asks the question "Which job number would you like to add to the list?"... the user would then enter a reference number such as "FX1234356". The macro then needs to write that information into a cell, which I can then use to finish the macro (basically a search in some data).
You can use the Range object in VBA to set the value of a named cell, just like any other cell.
Range("C1").Value = Inputbox("Which job number would you like to add to the list?)
Where "C1" is the name of the cell you want to update.
My Excel VBA is a little bit old and crusty, so there may be a better way to do this in newer versions of Excel.
I recommend always using a named range (as you have suggested you are doing) because if any columns or rows are added or deleted, the name reference will update, whereas if you hard code the cell reference (eg "H1" as suggested in one of the responses) in VBA, then it will not update and will point to the wrong cell.
So
Range("RefNo") = InputBox("....")
is safer than
Range("H1") = InputBox("....")
You can set the value of several cells, too.
Range("Results").Resize(10,3) = arrResults()
where arrResults is an array of at least 10 rows & 3 columns (and can be any type). If you use this, put this
Option Base 1
at the top of the VBA module, otherwise VBA will assume the array starts at 0 and put a blank first row and column in the sheet. This line makes all arrays start at 1 as a default (which may be abnormal in most languages but works well with spreadsheets).
When asking a user for a response to put into a cell using the InputBox method, there are usually three things that can happen¹.
The user types something in and clicks OK. This is what you expect to happen and you will receive input back that can be returned directly to a cell or a declared variable.
The user clicks Cancel, presses Esc or clicks × (Close). The return value is a boolean False. This should be accounted for.
The user does not type anything in but clicks OK regardless. The return value is a zero-length string.
If you are putting the return value into a cell, your own logic stream will dictate what you want to do about the latter two scenarios. You may want to clear the cell or you may want to leave the cell contents alone. Here is how to handle the various outcomes with a variant type variable and a Select Case statement.
Dim returnVal As Variant
returnVal = InputBox(Prompt:="Type a value:", Title:="Test Data")
'if the user clicked Cancel, Close or Esc the False
'is translated to the variant as a vbNullString
Select Case True
Case Len(returnVal) = 0
'no value but user clicked OK - clear the target cell
Range("A2").ClearContents
Case Else
'returned a value with OK, save it
Range("A2") = returnVal
End Select
¹ There is a fourth scenario when a specific type of InputBox method is used. An InputBox can return a formula, cell range error or array. Those are special cases and requires using very specific syntax options. See the supplied link for more.
I've done this kind of thing with a form that contains a TextBox.
So if you wanted to put this in say cell H1, then use:
ActiveSheet.Range("H1").Value = txtBoxName.Text

Resources