I have a string of text in cell A10, which begins with data from Sheet “Input,” cell C2. I want the referenced data to be underlined. For example, if “John Smith” was in Input!C2, it should look like “John Smith is having trouble with this formula” with John Smith underlined. Below is the code I have, but it’s not working — it’s underlining the entire string of text. Also, while I’m here, how can I get this to run automatically, rather than having to manually run the macro? Thanks in advance.
Sub Macro() With Range("A10") .Value = Range("Input!C2") & " is having trouble with this formula" .Characters(1, Len(Range("Input!C2"))).Font.Underline = True End With End Sub
Try this in normal module (assuming the “Contract” is where your
Option Explicit Sub Macro() Dim sTxt As String Application.EnableEvents = False ' Added this With Worksheets("Contract").Range("A10") .Font.Underline = xlUnderlineStyleNone sTxt = Range("Input!C2").Text If Len(sTxt) = 0 Then .ClearContents Else .Value = sTxt & " is having trouble with this formula" .Characters(1, Len(sTxt)).Font.Underline = xlUnderlineStyleSingle End If End With Application.EnableEvents = True ' Added this End Sub
Then in Input worksheet module (updated):
Option Explicit Private Sub Worksheet_Change(ByVal Target As Range) Dim oRng As Range Set oRng = Union(Range("B2"), Range("B4"), Range("C2")) If Not Intersect(Target, oRng) Is Nothing Then Macro End Sub
Input!C2 contains formula, you need to Union other ranges involved in the
Intersect() or it won’t auto update on their changes.
Alternatively, you can force auto update on the Worksheet calculation, add below to the Input worksheet module:
Private Sub Worksheet_Calculate() Macro ' Will not work if Worksheet calculation is Manual End Sub