Bold a specific text within a range (broken up into multiple cells) - excel

I am building a template in Excel and I would like the phrase "6. Description Summary:" to be bold using VBA. The cell the phrase is located is not static so the code should be able to pick up the phrase anywhere within the range.
Currently the code makes the whole range A1:G100 bold
Here is what I have tried:
Set BoldRange = Range("A1:G100").Find("6. Description Summary:")
If Not (BoldRange Is Nothing) Then
BoldRange.Font.Bold = True
End If
Would appreciate it if you could let me know if there is a way to edit this code to make it bold only the specified text.
Update: The text is broken up into multiple cells so I am actually looking to only bold the specified string.

The code does what you want, I checked it myself. Set BoldRange = Range("A1:G100").Find("6. Description Summary:") returns the range where the string is found, and that is the only cell that is turned to bold. Check in your code if you are not manipulting the range somewhre else where you might be changing the whole range to bold.
Below the code I used, just in case it helps (just yours into a Sub()):
Sub FindAndBold()
Set BoldRange = Range("A1:G100").Find("6. Description Summary:")
If Not (BoldRange Is Nothing) Then
BoldRange.Font.Bold = True
End If
End Sub

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")

How do I call a function to add/remove dots and dashes on a given cell

Here in Brazil we use a 20 number string to identify judicial cases, in a standardized manner, separated by a dots and dashes.
The problem is in most systems we use, when you export to excel it takes away the dots and dashes, thus creating a problem when exporting that data to a system that actually needs the dots and dashes to work (some poorly coded excuse for a legal system).
What I'm trying to do is use VBA to call a function that fixes the number so I can export it.
The way the standardized number works is like this:
0010159-24.2015.8.10.0001
(CaseNumber-VerifyingDigit.Year.Court.State.City)
When I export my current data do Excel, it shows like this:
00101592420158100001
And I need it to go back to the format above!
I'm 100% stuck though, would love some input.
Edit:
To clarify some stuff.
The string is always 20 numbers long, its a standardized number set by our National Council of Justice, it never changes. All the cases follow that 20 number string format.
The cell with the number is always in text, so it doesn't show as scientific notation.
If I got you correctly, you want to change the values in a range so that they are in the needed format (with dots and dashes) so then you can export it somewhere else?
Maybe something like that can help? I assume you have your 00101592420158100001 in a cell A1.
Sub x()
Range("A1").Value = Format(Range("A1"), "#######-##.####.#.##.####")
End Sub
EDIT 1: As the number in cell A1 starts with 00 I assumed that you have cell A1 formatted as text. So that the macro proposed by me will only add a certain dashes or dots.
EDIT 2: Why the code above was not working is the fact that in VBA the "#" character represents a displayed character, and "#" works for numbers.
So, as suggested in a comment below, the subroutine like this:
Sub x()
Range("A1").Value = Format(Range("A1"), "#######-##.####.#.##.####")
End Sub
will do the trick.
But as you want to choose a range to be formatted I would suggest using something more like that:
Sub forhenriquef()
Dim cell As Range
Dim rng As Range
On Error Resume Next
Set rng = Application.InputBox("Choose the range, OK?", "Macro for henriquef", Selection.Address, , , , , 8)
If rng Is Nothing Then Exit Sub
For Each cell In rng
cell.Value = Format(cell, "#######-##.####.#.##.####")
Next cell
End Sub
This solution isn't VBA but we can make one, however if you're just looking to reformat the text and it is as you show with no variation (I sense a date is in there and the length of this string may vary), this should work for you.
Assuming you data starts in cell A1, you can put this formula in row 1 somewhere and get the desired format.
=LEFT(A1,7)&"-"&RIGHT(LEFT(A1,9),2)&"."&RIGHT(LEFT(A1,13),4)&"."&LEFT(RIGHT(A1,7),1)&"."&LEFT(RIGHT(A1,6),2)&"."&RIGHT(A1,4)
Or as Scott had mentioned you can use the shorter:
=TEXT(LEFT(A1,9),"0000000\-00\.")&TEXT(MID(A1,10,20),"0000\.0\.00\.0000")

VBA Formula and Text in a specific cell

I am trying to have some vba code to place the value of a formula and text into a specific cell. I want the code to say Leads:(value of formula). Currently my code runs the formula and places the value in the correct box. I just do not know how to add the text with it. The code I have is written below.
ws.Range("$B$1").Formula = "=COUNTIF(E:E,""Lead"")"
A custom Range.NumberFormat property will give you the displayed result while leaving the actual raw value in a numerical form for possible further computation or comparison.
with ws
with .range("B1") '<~~ no need for absolute $ anchors here
.formula = "=COUNTIF(E:E,""Lead"")"
.numberformat = "[=1]L\e\a\d\: 0;L\e\a\d\s\: 0"
end with
end with
Try this:
ws.Range("$B$1").Formula = "=""Leads:("" & COUNTIF(E:E,""Lead"")&"")"""
so that it ends up like the following when applied:
="Leads:(" & COUNTIF(E:E,"Lead")&")"

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:

Set the color of one cell based on the color of another cell

What I would like to have is:
IF A1 in Sheet 2 is blue
Then A1 in Sheet 1 changes to blue
I know I can get the color of A1 in Sheet 2 by using:
=GET.CELL(63,Sheet2!A1)
(Excel: Can I create a Conditional Formula based on the Color of a Cell?)
But I can't figure out what I should do in the next step.
Update on 12.01.2015
At the beginning I thought a function would work, but as I considered my file, VBA may be needed.
It is about the output of a correlation analyse from SPSS, there are three columns: correlation coefficient, p-value and sample size.
I need to check the coefficient and p-value at the same time, and present the coefficient in a readable way. Say I run a correlation between 50 variables with 100 variables, I would not paste coefficient and p-value in one sheet, rather:
sheet one : coefficient
sheet two: p-value
What I would to have is:
If value of p-value is bigger than 0.05, then coefficient (cell) changes to blue/dark blue or black.
So that when I watch the first sheet, I know blue ones should be ignored because of non-significance.
What you need is a way to detect changes in cell format.
There appears to be no event that triggers upon change in format. See
How to detect changes in cell format?
I will describe a workaround, almost step-by-step. It is not keystroke-by-keystroke, so you may have to google a bit, depending on you background knowledge.
The description is not short, so please read it through.
You have to:
Detect change in Selection (there is an event for this).
Inquire about the color of your source cell.
Act if needed.
Go to the Visual Basic Editor (VBE) and add code in three modules:
A standard module (say, Module1). You have to first insert the module.
ThisWorkbook.
Sheet2.
In Module1:
Public prev_sel As Range
Public wssrc As Worksheet, wstrg As Worksheet
Public ssrc As String, strg As String
Public rngsrc As Range, rngtrg As Range
Sub copy_color(rngs As Range, rngt As Range)
Dim csrc As Long
csrc = rngs.Interior.Color
If (csrc = vbBlue) Then
rngt.Interior.Color = vbBlue
End If
End Sub
Sub copy_color2(rngs As Range, rngt As Range)
If (TypeName(prev_sel) = "Range") Then
Dim pss As String
pss = prev_sel.Parent.Name
If (pss = ssrc) Then
Dim ints As Range
Set ints = Application.Intersect(rngs, prev_sel)
If (Not (ints Is Nothing)) Then
Call copy_color(rngs, rngt)
End If
End If
End If
End Sub
In ThisWorkbook:
Private Sub Workbook_Open()
ssrc = "Sheet2"
strg = "Sheet1"
Set wssrc = Worksheets(ssrc)
Set wstrg = Worksheets(strg)
Set rngsrc = wssrc.Range("A1")
Set rngtrg = wstrg.Range("A1")
Call copy_color(rngsrc, rngtrg)
If (TypeName(Selection) = "Range") Then
Set prev_sel = Selection
Else
Set prev_sel = Nothing
End If
End Sub
In Sheet2:
Private Sub Worksheet_Deactivate()
Call copy_color(rngsrc, rngtrg)
If (TypeName(Selection) = "Range") Then
Set prev_sel = Selection
Else
Set prev_sel = Nothing
End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Call copy_color2(rngsrc, rngtrg)
If (TypeName(Target) = "Range") Then
Set prev_sel = Target
End If
End Sub
I will soon edit with explanations. Reading carefully, it can be readily understood, though.
Notes:
This code does not act if the source cell color changes from vbBlue to something else. You did not specify anything for this action. Actually, your specification was not detailed enough to cover all possible cases.
There might be cases (extremely unlikely, I guess) where this code fails. For instance, if color is changed via other VBA code, without selecting/deselecting cells.
The idea is to check for the need of acting after as many relevant events as possible. Here I am detecting Workbook_Open, Worksheet_Deactivate, Worksheet_SelectionChange. You may add other events with suitable Subs, e.g., Workbook_BeforeClose, Workbook_BeforeSave. All this is a way of substituting for the non-existing event of changing cell format.
I like the answer by pnuts (although I did not have time to test it). But the present one gives a flexibility that is not available with the other. There might be some cases (depending on what you need to do) that would not be covered by it.
There are other possible combinations of places to locate variables declaration and other code, essentially performing the same actions.
Not recommended because of reliance on the XLM (not XML) Macro function GET.CELL. This from a technology introduced 30 years ago that was effectively superseded eight years later. With almost all its elements now defunct, the few that remain can be expected to have a low life expectancy. Microsoft encourages migration to VBA.
Nevertheless, you have asked ‘how’ rather than ‘why not’, so I suggest you proceed from where you have reached and select Sheet1 A1 and HOME > Styles - Conditional Formatting - New Rule..., Use a formula to determine which cells to format, Format values where this formula is true:
=CellColor=23
and select blue formatting of your choice, OK, OK, Apply.
23 is a fairly standard number for Blue (not Light, not Dark) but your configuration may expect a different number.
Note that another disadvantage is that, unlike CF in general, the response is not automatic – you may need to enter something in Sheet1 A1, or Shift+F9 to force an update.
If your data is spread across two sheets (Sheet1 and Sheet2, both ColumnA) and there is a 1:1 relationship (the p-value in A1 of Sheet2 is that for the correlation coefficient in A1 of Sheet1) then a simple Conditional Formatting rule may suffice:
Select Sheet1 ColumnA and HOME > Styles - Conditional Formatting, New Rule...
Use a formula to determine which cells to format
Format values where this formula is true:
=Sheet2!A1>0.05
Format..., select dark blue or to suit, OK, OK.
The same rule might be applied in Sheet2 (ColumnA) in the same way so the cells (by row) conditionally formatted in one sheet are those conditionally formatted in the other.
The GET.CELL function, whilst useful, comes from the old XLM macro language which was used before VBA. You may encounter restrictions using this e.g. at that time Excel used a limited number of colours (I have read somewhere around 60?).
Alternatively, with a bit of VBA, you could experiment with the Interior Object and also the Font Object :
Sheets("Sheet1").Range("A1").Interior.Color = vbBlue
Sheets("Sheet1").Range("A1").Font.Color = vbYellow
If Sheets("Sheet1").Range("A1").Interior.Color = vbBlue Then _
Sheets("Sheet2").Range("A1").Interior.Color = vbBlue
If Sheets("Sheet1").Range("A1").Font.Color = vbYellow Then _
Sheets("Sheet2").Range("A1").Font.Color = vbYellow
You will likely need to explore the various ways of specifying the colors to use to give you maximum control/flexibility.
Just to be clear and to keep the functionality you deliver simple, you could use conditional formatting and choose to set the format with a colour. This is incredibly easy once you know how. The main trick is what formula to enter and specifically which cell you need a conditional formats formula to reference when the conditional format applies to a multi cell range.
As an example. If your conditional formatting rule is created such that it applies to the range $C$5:$C$10 the formula you use will often need to be entered as =(A5="A"). Note this is a relative addressing formula ie no dollar signs. this has the effect of the cell c6 inspecting the value of a6 etc.
Your only complication now is to inspect the formatting of the cell rather than the value it stores. In 2013, you can still use =GET.CELL(63,A5) to do this, however this can't be entered in the formula of the CF rule ... Other posts discuss the whys and wherefores of using this. See this link which described how to get cell info.
So you'll end up with a formula in a cell next to the cell that has the colouring. The formula will use a named range that returns true or false depending on whether the colour of the cell matches the colour you specify in the named range. You conditional formatting on another sheet will reference this formula cell and set the colour of the new cell.
You would use the following formula in the named range called "Get .
=GET.CELL(65,OFFSET(INDIRECT("RC",FALSE),0,1))
I've got this to work, and the key information can be found one the referenced web site page.
Ok?

Resources