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")
Related
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
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")
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:
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. :-)
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