When editing a cell's contents, you can "select" (highlight) some of the text within that cell. Is there an object in VBA that lets you reference the selected text within the active cell?
The reason is that I have a spreadsheet where some cells contain names. The names need to be replaced by initials to anomalyse the spreadsheet before the it is sent externally. I've written the macro at the end of this post, which goes through each cell in the selected range, replacing every word by its initial and an underscore. That's fine where the cell only contains names. But for cells that contain other text too, I want to be able to:
- Click into the cell with the mouse,
- Highlight the words within the text that I want to change,
- Run a macro that only converts the selected words into initials and underscores and leaves the other words unchanged?
There will be any number of names in the spreadsheet, so a simple find/replace wouldn't work.
Is this even possible? Or can you only reference cells, rather than selected text within them?
This is my macro for converting the contents of entire cells in a range:
Thanks!
The reason is that I have a spreadsheet where some cells contain names. The names need to be replaced by initials to anomalyse the spreadsheet before the it is sent externally. I've written the macro at the end of this post, which goes through each cell in the selected range, replacing every word by its initial and an underscore. That's fine where the cell only contains names. But for cells that contain other text too, I want to be able to:
- Click into the cell with the mouse,
- Highlight the words within the text that I want to change,
- Run a macro that only converts the selected words into initials and underscores and leaves the other words unchanged?
There will be any number of names in the spreadsheet, so a simple find/replace wouldn't work.
Is this even possible? Or can you only reference cells, rather than selected text within them?
This is my macro for converting the contents of entire cells in a range:
Code:
For Each cell In Selection
Anon = Left(cell.Value, 1) & "_"
SpaceChar = 0
ErrorCheck = 0
Do
On Error GoTo ErrorHandler
SpaceChar = Application.WorksheetFunction.Search(" ", cell.Value, SpaceChar + 1)
On Error GoTo 0
If ErrorCheck = 1 Then Exit Do
Anon = Anon & Mid(cell.Value, SpaceChar, 2) & "_"
Loop
cell.Value = Anon
Next cell
Exit Sub
ErrorHandler:
ErrorCheck = 1
Resume Next
Thanks!