Insert string into cell with only integers while keeping fonts- VBA - excel

I am trying to append text into an excel cell with VBA. Currently I am using :
Range("A1").Characters(Len(Range("A1")) + 1).Insert ("text")
This works fine for cells with text, but if the cell contains only numbers (integers) it throws an error:
Run-time error '1004' Insert method of Characters class failed
Parts of the text in the cell are in different fonts or bolded and I need to keep them that way.
I have also tried to change the NumberFormat the cell to general, but it does not help:
Range("A1").NumberFormat = "#"
If someone knows a way to append text to a cell containing only integers with different fonts please answer.

Unlike Strings, Cells that contain actual Numbers (but not strings that look like numbers) cannot have format applied individual characters.
Therefore split your processing based on data type1
Dim cell as Range
Dim AppendText as String
AppendText = "text"
Set cell = Range("A1")
If TypeName(cell.Value2) <> "String" Then
cell.Value2 = cell.Value2 & AppendText
Else
cell.Characters(Len(cell.Value2) + 1).Insert AppendText
End If
After this has run, cells thar were numeric will now be strings, and can have individual characters formmated.
Notes:
You might want to consider other data types too: boolean, date, ...

Related

Code to find cells that contain a constant preceded by = sign

Any suggestions for Excel vba code that will identify cells that contain values but no function. The catch being that the values I'm searching for are preceded by an "=" sign.
I often have to review other people's financial spreadsheets and knowing which cells contain the actual inputs (assumptions) is key. I can easily find cells with just a constant input with a simple:
Selection.SpecialCells(xlCellTypeConstants, 1).Select
The problem is some users have a habit of inputing numbers preceded by an = sign and these cells are treated by excel as containing a function. I know I can search for cells with functions too, but I only want to find the ones that don't actually have a function, but are input starting with an = sign.
In other words, instead of inputing 1000 in a cell the user inputs =1000. It is only these types of cells I am trying to highlight.
Any suggestions on how I can identify these cells?
Exactly this "The problem is some users have a habit of inputing numbers preceded by an = sign" is your problem. Stop people having this habit!
First it is a stupid habit because it slows everything down because Excel has to evaluate those cells that contain something like =1000 to find out the value and
second those cells actually contain a formula and not a value. So there is no built in way to distinguish them.
Those people are just using Excel wrong.
There is only one workaround I can imagine and that is looping through all cells that contain a formula, remove the = sign and check if the rest of the "formula" is numeric IsNumeric(). If so replace the formula by its value.
So for example if the cell is =1000 then 1000 is numeric and it will replace it by the value 1000. If the cell is =1000*2 then 1000*2 is not numeric because it contains a * sign and it will keep the formula.
Note that this workaround is just fighting symptoms but not fixing the root cause. The root cause is those people using Excel wrong! And you should always fix the causes not fight the symptoms.
Option Explicit
Public Sub ReplaceFormluasWithValueIfNoCalculation()
Dim AllCellsWithFormulas As Range
On Error Resume Next ' next line errors if no formulas are found, so hide errors
Set AllCellsWithFormulas = ActiveSheet.Cells.SpecialCells(xlCellTypeFormulas)
On Error GoTo 0 ' re-enable error reporting
If Not AllCellsWithFormulas Is Nothing Then
Dim Cell As Variant
For Each Cell In AllCellsWithFormulas.Cells ' loop through all formulas
Dim ExtractedValue As String ' extract formula right of the `=` sign
ExtractedValue = Right$(Cell.Formula, Len(Cell.Formula) - 1)
' check if extracted formula is only a value, if so replace formula with value
If IsNumeric(ExtractedValue) Then
Cell.Value = ExtractedValue
End If
Next Cell
End If
End Sub
Even the above can be done, I recommend fixing the root cause.
Assuming those inputs only contain number you could use a regex for that and ensure the value only contain "=" and numbers you'll have a code like this :
Dim RegEx As Object, MyString As String
Set RegEx = CreateObject("VBScript.RegExp")
MyString = cell.formulas
With RegEx
.Pattern = "=*[0-9., ]+"
End With
RegEx.test(MyString) 'True if MyString is a number false if it's a function
You'll need to activate "Microsoft VBScript Regular Expression" though.

How Function works in Excel when it uses Reference as Cell? [duplicate]

I Have built a string using a formula in excel. as an example
Cell C3 contains text "Languages"
Cell C4 = "English, Spanish,German, French"
My Forumla = C3 & ":" & CHAR(10) & C4
The Desired text would be:
Languages:
English, Spanish, German, French
(where the bold text would actually be some color like red)
Is there a way to do this in Excel (change partial text formatting) .
I Have tried a formula... (Not working)
Function formatText(InText As Range)
'Set font color
InText.Characters(1.5).Font.Color = Red
'InText.Characters((InStr(1, ":", InText) + 1), (Len(InText) - InStr(1, ":", InText))).Font.ColorIndex = 3
End Function
Your posted function with work if and only if
It is called from a Sub (ie, as other have mentioned, not as a UDF)
And
the value(s) contained in range InText are string constants. (This is the main point of my answer)
It will not work for any cells in range InText containing a formula. AFAIK you cannot format part of a string returned by a formula.
BTW I would love to be proved wrong on this!
Regarding Hightower's question, "how would you cast a formula output to a string so that you can apply the text formatting?"
To "cast" the output of a formula so that you can apply text formatting, you must write the value returned by the formula into the spreadsheet, then apply the formatting to the value you wrote. You could either write the value into the cell containing the formula (which will erase the formula), or you could write the value into a different place in the spreadsheet (which will preserve the formula but then you'll be seeing double).
Sub Cell_Format(InText as Range)
InText.formula = cstr(InText.value) ' converts result of formula into a string literal
'or: InText.offset(0,1).formula = cstr(InText.value) -- writes the value in the cell next to InText
InText.characters(1, 5).font.color = vbRed
End Sub
Then Cell_Format range("$A$1") will replace the formula in cell $A$1 with a string constant and change the color of the first five characters to red.
If you want to do this for a range larger than one cell, add this code to the above:
Sub Range_Format(InText as Range)
For each c in InText
Cell_Format(c)
Next
End Sub
You need to use this code:
InText.Characters(1,5).Font.Color = RGB(255, 0, 0)
If you want to make it flexible, so that only the (fully) second line is red, use this code:
InText.Characters(Instr(InText, vbCr)+1, Len(InText)-Instr(InText, vbCr)).Font.Color = RGB(255, 0, 0)
Note that your function needs to be called from VBA, i.e. you cannot use it as a User-Defined-Function! UDFs can only return a result but never modify a cell!
You cannot directly call the below UDF in Excel interface. For that you will have use an event as UDF cannot change the physical characteristic of a cell. For more details you may read this link. http://support.microsoft.com/kb/170787
Function formatText(InText As Range)
'Set font color
InText.Interior.Color = vbRed
'InText.Characters((InStr(1, ":", InText) + 1), (Len(InText) - InStr(1, ":", InText))).Font.ColorIndex = 3
End Function

formatting excel cell

I am in trouble. I have thousands of customer data having name, address, zip. I have data in excel and the problem is in zip code. The Zip should be 5 character long and if it is not, we have to add zero at front to make equal to five character. Since there are thousands of data and it is not feasible to change it one by one, can somebody suggest me to format the column of zip so that it could be 5 character long.
You can use the custom format and use the type : 00000
Write the following formula in front of that zip column:
=IF(LEN(A1)>5,"Invalid",RIGHT("00000" & A1,5))
Just replace the cell reference name A1 to the first cell of zip code column and then drag the cell down. Now all those zip codes that are less than five characters will be filled with leading zeros. Also It will show Invalid in cells which have a zip code of more than 5 characters length.
Apply this formula to the cell values, i.e. for A1 in this example:
=TEXT(A1,"0000#")
Copy/paste the formatted values (as text) into the desired column if you need them in a specific column.
Simply mark the whole column.
Than right click to get into the "format cells" settings.
There you go to "special format" and there you should mark "ZipCode".
Here is a picture of the options. It is in german, so I hope you will find it anyway ;)
Quick macro to convert the range to Text format, and append leading zeros if the cell is less than 5 characters.
Sub AddLeadingZeros()
Dim rng As Range: Set rng = Range("A1:A10") '<modify as needed, the cells containing ZIP'
Dim cl As Range
rng.NumberFormat = "#"
For Each cl In rng
If Len(cl.Value) < 5 Then
Do
cl.Value = "0" & cl.Value
Loop While Len(cl.Value) < 5
End If
Next
End Sub
select your column
Format-> cell
Special format-> zip code
make sure you save the changes... it shouldn't remove zero...
or try a "user defined" format... but I never tried it.

How do I get the format of a cell in VBA

When iterating through cells in a worksheet, how can I get what the format setting on the cell is? Because based on this, I would like to build a SQL statement to either add the single ticks or not to the value retreived
Sounds like you need the VarType() function. Vartype(Range("A1"))
OK, so you don't want to know the format setting for the cell, but whether the value is numeric.
Can you just call IsNumeric(Range("A1")) and quote it if False?
Based on your comment that some numbers are stored as text in the DB, you are not going to solve this by a simple formula. Can't you just quote the values as you build your SQL statement?
Try using the following in VBA:
Range("A1").NumberFormat = "0.00" 'Sets cell formatting to numeric with 2 decimals.
Range("A1").Formula = "=Text(6, " & """0.00""" & ")" 'Looks like a number _
' but is really text.
Debug.Print WorksheetFunction.IsNumber(Range("A1")) 'Prints False
Range("A1").Value = 6 'Puts number into the cell, which also looks like 6.00
Debug.Print WorksheetFunction.IsNumber(Range("A1")) 'Prints True
This should tell you if the value is really text or really a number, regardless of the cell's formatting properties.
The key is that the intrinsic Excel IsNumber() function works better for this purpose than the VBA function IsNumeric. IsNumber() tells you whether the cell's value is a number, whereas IsNumeric only tells you if the cell is formatted for numeric values.
I don't think there's any property of a cell that indicates whether the cell actually contains a numeric value, although VarType() might help, it gets tricky because Excel will allow a number-formatted cell to contain string, and a text formatted cell to contain numeric values, without overriding the NumberFormat property.
In any case you likely need some independent test to figure out whether a cell IsNumeric (or other criteria) AND whether its NumberFormat is among an enumerated list which you can define.
Sub numFormat()
Dim cl As Range
Dim numFormat As String
Dim isNumber As Boolean
For Each cl In Range("A1")
numFormat = cl.NumberFormat
isNumber = IsNumeric(Trim(cl.Value))
Select Case numFormat
Case "General", "0", "0.0", "0.00" ' <--- modify as needed to account for other formats, etc.
If isNumber Then
Debug.Print cl.Address & " formatted as " & numFormat
End If
Case Else
'ignore all other cases
End Select
Next
End Sub
I don't think the format of the cell is the important thing. Rather, it's the data type of the field in your database. If you have the string 'foobar' in a cell and you create an INSERT INTO sql statement that attempts to put that into a Long Integer field, it's going to fail regardless of tickmarks.
Conversely, if a cell contains a numeric value (like 100) that needs to go into a VARCHAR field, it will need tickmarks (like '100').
If you're using ADO, check the Type property of the Field object to determine the data type. Use this list http://support.microsoft.com/kb/193947 to see what the types are. Then set up the SQL statement according to the field type.

Format a subset of text in Excel Cell Using Formula

I Have built a string using a formula in excel. as an example
Cell C3 contains text "Languages"
Cell C4 = "English, Spanish,German, French"
My Forumla = C3 & ":" & CHAR(10) & C4
The Desired text would be:
Languages:
English, Spanish, German, French
(where the bold text would actually be some color like red)
Is there a way to do this in Excel (change partial text formatting) .
I Have tried a formula... (Not working)
Function formatText(InText As Range)
'Set font color
InText.Characters(1.5).Font.Color = Red
'InText.Characters((InStr(1, ":", InText) + 1), (Len(InText) - InStr(1, ":", InText))).Font.ColorIndex = 3
End Function
Your posted function with work if and only if
It is called from a Sub (ie, as other have mentioned, not as a UDF)
And
the value(s) contained in range InText are string constants. (This is the main point of my answer)
It will not work for any cells in range InText containing a formula. AFAIK you cannot format part of a string returned by a formula.
BTW I would love to be proved wrong on this!
Regarding Hightower's question, "how would you cast a formula output to a string so that you can apply the text formatting?"
To "cast" the output of a formula so that you can apply text formatting, you must write the value returned by the formula into the spreadsheet, then apply the formatting to the value you wrote. You could either write the value into the cell containing the formula (which will erase the formula), or you could write the value into a different place in the spreadsheet (which will preserve the formula but then you'll be seeing double).
Sub Cell_Format(InText as Range)
InText.formula = cstr(InText.value) ' converts result of formula into a string literal
'or: InText.offset(0,1).formula = cstr(InText.value) -- writes the value in the cell next to InText
InText.characters(1, 5).font.color = vbRed
End Sub
Then Cell_Format range("$A$1") will replace the formula in cell $A$1 with a string constant and change the color of the first five characters to red.
If you want to do this for a range larger than one cell, add this code to the above:
Sub Range_Format(InText as Range)
For each c in InText
Cell_Format(c)
Next
End Sub
You need to use this code:
InText.Characters(1,5).Font.Color = RGB(255, 0, 0)
If you want to make it flexible, so that only the (fully) second line is red, use this code:
InText.Characters(Instr(InText, vbCr)+1, Len(InText)-Instr(InText, vbCr)).Font.Color = RGB(255, 0, 0)
Note that your function needs to be called from VBA, i.e. you cannot use it as a User-Defined-Function! UDFs can only return a result but never modify a cell!
You cannot directly call the below UDF in Excel interface. For that you will have use an event as UDF cannot change the physical characteristic of a cell. For more details you may read this link. http://support.microsoft.com/kb/170787
Function formatText(InText As Range)
'Set font color
InText.Interior.Color = vbRed
'InText.Characters((InStr(1, ":", InText) + 1), (Len(InText) - InStr(1, ":", InText))).Font.ColorIndex = 3
End Function

Resources