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
Related
In recorded VBA macros, it seems that their formulas use R1C1 reference style. For instance, to fill in B4 with B2+1:
Range("B4").Select
ActiveCell.FormulaR1C1 = "=R[-2]C+1"
Does anyone know if it is possible to switch off this mode? For instance, let recorded macro look like:
Range("B4").Select
ActiveCell.Formula = "=B2+1"
I believe you cannot do that. The macro will always record in R1C1 style.
You can always switch the style but it will only be applied to the worksheet and if you record a macro it will still show R1C1 reference style.
It is very easy to understand the R1C1 style
In R1C1 reference style, the range is referred by how far the cells are located from the cell you are calling. For example, if you have 5 values from R1C1 to R5C1 and the range is called from R7C2, then the range would be R[-6]C[-1]:R[-2]C[-1]. Here the first cell in the range is 6 rows before the cell R7C2 and 1 column before the cell R7C2 and similarly for the last cell in the range.
If I take your example then "=R[-2]C+1" means that the formula is referring to a row which is two rows up (-2) and in the same column (0). Your formula is same as "=R[-2]C[0]+1"
EDIT
Here is a small function that I wrote which can help you convert R1C1 to A1 string
Sub Sample()
'~~> This will give you $B$2
Debug.Print R1C12A1("B4", "R[-2]C")
'~~> This will give you E227
Debug.Print R1C12A1("O9", "R[218]C[-10]", True)
'~~> This will give you $Y$217
Debug.Print R1C12A1("O9", "R[208]C[10]")
End Sub
Function R1C12A1(baseCell As String, sRC As String, Optional RemDollar As Boolean = False) As String
Dim MyArray() As String
Dim r As Long, c As Long
sRC = Replace(sRC, "R", "")
If Left(sRC, 1) = "C" Then
r = 0
Else
r = Replace(Replace(Split(sRC, "C")(0), "[", ""), "]", "")
End If
If Right(sRC, 1) = "C" Then
c = 0
Else
c = Replace(Replace(Split(sRC, "C")(1), "[", ""), "]", "")
End If
If RemDollar = False Then
R1C12A1 = Range(baseCell).Offset(r, c).Address
Else
R1C12A1 = Replace(Range(baseCell).Offset(r, c).Address, "$", "")
End If
End Function
Note: I have not done any error handling here. I am sure you can incorporate that if needed.
There used to be a facility to toggle relative reference when recording a macro.
When you have started recording, in the macro toolbar - near the stop button - there was a button to toggle relative reference; is this not the same as toggling R1C1 ? or isn't this available anymore?
I never bothered toggling it myself as like Siddharth says the R1C1 isn't too tricky to understand plus, irrespective of whatever you do, the VBA will need some editing so at the same time if you wish to use other syntax it's easy enough to change.
I've just played around with the following but it doesn't seem to help so maybe I'm mixing up the use of this button with R1C1...
Original Problem:
Within Azure Data Studio, I have saved the results of a SQL query into Excel spreadsheet. When I bring up the spreadsheet, a cell containing a formula (a URL hyperlink) is showing as text to display as opposed to results of executing the formula (a named visibly clickable hyperlink).
Here's the first three rows of raw data from the spreadsheet:
sourceTableNameA
sourceTableComposedKeyA
sourceTableComposedKeyA2
sourceTableNameB
sourceTableComposedKeyB
FCC_ASR_LI_20210202
=Hyperlink("https://maps.google.com/maps?q=28.537266254426,-97.794735431672","C.2655506")
https://maps.google.com/maps?q=28.537266254426,-97.794735431672
F3GIS_20210209
=Hyperlink("https://maps.google.com/maps?q=28.537266254426,-97.794735431672","{F4C8C17C-0702-4B08-ABC5-7ABF0BD76BAA}")
FCC_ASR_LI_20210202
=Hyperlink("https://maps.google.com/maps?q=29.709928035737,-96.912009716035","C.616145")
https://maps.google.com/maps?q=29.709928035737,-96.912009716035
F3GIS_20210209
=Hyperlink("https://maps.google.com/maps?q=29.709928035737,-96.912009716035","{7F77EAB2-3588-4023-921F-4C009FC91BDC}")
Solution A:
By clicking into the cell (ex: B2 above) and then pressing Return, the cell then turns into the results of the formula.
New Problem:
I have +20K of cells which I need to execute "Solution A". And manually executing "Solution A" +20K times is not an option.
Solution B (barely adequate):
After investing considerable time trying to fix this, I discovered a marginal solution. It is to select the contents of the column containing the formula-as-text, then search/replace the "=" character. While this does in fact convert the text into an actual formula for each cell, it leaves each cell looking like regular text instead of making it have the default appearance of a clickable link. This is causing me to have to then manually underline and select a different color for all of these cells.
Solution C (possible?):
My first thought was this is a job for an Excel Macro in VBA. And this is as close as I was able to get:
Public Sub Convert_To_Hyperlinks()
Dim Cell As Range
For Each Cell In Intersect(Selection, ActiveSheet.UsedRange)
If Cell <> "" Then
If Left(Cell, 1) = "=" Then
Evaluate (Cell)
Else
ActiveSheet.Hyperlinks.Add Cell, Cell.Value
End If
End If
Next
End Sub
This function works exactly as I need for cells (ex: C2 above) that contain a raw URL (i.e. the cell does not start with "=" character) which calls the ActiveSheet.Hyperlinks.Add Cell, Cell.Value for each cell giving the desired result. However, the code that detects if the cell (ex: B2 above) starts with "=" which calls Evaluate (Cell) doesn't work on the selected cells.
What VBA code can I use to replace Evaluate (Cell), if any, which would produce the same effect as Solution A?
In projects I have worked on I have found the following is often sufficient:
Cell.Value = Cell.Value
The beauty is that you can apply to ranges in one line.
Applying to your code with the loop:
Public Sub Convert_To_Hyperlinks()
Dim Cell As Range
For Each Cell In Intersect(Selection, ActiveSheet.UsedRange)
If Cell <> vbNullString Then
If Left$(Cell, 1) = "=" Then
Cell.Value = Cell.Value
Else
ActiveSheet.Hyperlinks.Add Cell, Cell.Value
End If
End If
Next
End Sub
I would like to define a function or formatting such that the "COUNTBLANK()" excel function does not consider as blank a "grey-cell", where the user is not allowed to type anything.
For example, let's suppose there is a balance sheet statement, where in cell C3 there is a "grey colored cell", in order to indicate to the user that she is not allowed to text or digit anything inside cell C3, including "0$" nor "-$".
Let's suppose in cell C100 there is a COUNTBLANK(C2:C99) function, in order to check if there are any missing values in the C-column. The function will return COUNTBLANK(C2:C99)=1, as in cell C3 the user did not text or digit anything. However, the C3 cell is "grey colored" and must be empty, and therefore not considered as missing (by definition).
Is there any function/formatting?
Try the next function, please:
Function CountBlkGray(rng As Range) As Long
Dim lngGray As Long, c As Range
For Each c In rng
If c.Value = "" And (c.Interior.ColorIndex = 15 Or _
c.Interior.ColorIndex = 2 Or c.Interior.ColorIndex = 48 Or _
c.Interior.ColorIndex = 16) Then lngGray = lngGray + 1
Next
CountBlkGray = WorksheetFunction.CountBlank(rng) - lngGray
End Function
You can simple use it like formula:
=CountBlkGray(A1:A16)
It will consider gray cells as not blank ones...
But you must use the standard Gray colors (from Excel available Pallete)
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
Each cell contains some text and a background color. So I have some cells that are blue and some that are red. What function do I use to count the number of red cells?
I have tried =COUNTIF(D3:D9,CELL("color",D3)) with no success (Where D3 is red).
Excel has no way of gathering that attribute with it's built-in functions. If you're willing to use some VB, all your color-related questions are answered here:
http://www.cpearson.com/excel/colors.aspx
Example form the site:
The SumColor function is a color-based
analog of both the SUM and SUMIF
function. It allows you to specify
separate ranges for the range whose
color indexes are to be examined and
the range of cells whose values are to
be summed. If these two ranges are the
same, the function sums the cells
whose color matches the specified
value. For example, the following
formula sums the values in B11:B17
whose fill color is red.
=SUMCOLOR(B11:B17,B11:B17,3,FALSE)
The worksheet formula, =CELL("color",D3) returns 1 if the cell is formatted with color for negative values (else returns 0).
You can solve this with a bit of VBA. Insert this into a VBA code module:
Function CellColor(xlRange As Excel.Range)
CellColor = xlRange.Cells(1, 1).Interior.ColorIndex
End Function
Then use the function =CellColor(D3) to display the .ColorIndex of D3
I just created this and it looks easier. You get these 2 functions:
=GetColorIndex(E5) <- returns color number for the cell
from (cell)
=CountColorIndexInRange(C7:C24,14) <- returns count of cells C7:C24 with color 14
from (range of cells, color number you want to count)
example shows percent of cells with color 14
=ROUND(CountColorIndexInRange(C7:C24,14)/18, 4 )
Create these 2 VBA functions in a Module (hit Alt-F11)
open + folders. double-click on Module1
Just paste this text below in, then close the module window (it must save it then):
Function GetColorIndex(Cell As Range)
GetColorIndex = Cell.Interior.ColorIndex
End Function
Function CountColorIndexInRange(Rng As Range, TestColor As Long)
Dim cnt
Dim cl As Range
cnt = 0
For Each cl In Rng
If GetColorIndex(cl) = TestColor Then
Rem Debug.Print ">" & TestColor & "<"
cnt = cnt + 1
End If
Next
CountColorIndexInRange = cnt
End Function
I was needed to solve absolutely the same task. I have divided visually the table using different background colors for different parts. Googling the Internet I've found this page https://support.microsoft.com/kb/2815384. Unfortunately it doesn't solve the issue because ColorIndex refers to some unpredictable value, so if some cells have nuances of one color (for example different values of brightness of the color), the suggested function counts them. The solution below is my fix:
Function CountBgColor(range As range, criteria As range) As Long
Dim cell As range
Dim color As Long
color = criteria.Interior.color
For Each cell In range
If cell.Interior.color = color Then
CountBgColor = CountBgColor + 1
End If
Next cell
End Function
Yes VBA is the way to go.
But, if you don't need to have a cell with formula that auto-counts/updates the number of cells with a particular colour, an alternative is simply to use the 'Find and Replace' function and format the cell to have the appropriate colour fill.
Hitting 'Find All' will give you the total number of cells found at the bottom left of the dialogue box.
This becomes especially useful if your search range is massive. The VBA script will be very slow but the 'Find and Replace' function will still be very quick.