Home » excel » Excel VBA to underline referenced cell data

Excel VBA to underline referenced cell data

Posted by: admin May 14, 2020 Leave a comment

Questions:

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
How to&Answers:

Try this in normal module (assuming the “Contract” is where your A10 is)…

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

NOTE
If the 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

Screenshots for where the code goes:
Location of Code for Module1
Location of Code for Input