Excel VBA为引用的单元格数据加下划线

时间:2018-03-20 23:49:41

标签: excel vba excel-vba

我在单元格A10中有一串文本,它以Sheet“Input”中的数据开头,单元格C2。我希望引用的数据加下划线。例如,如果“John Smith”在Input!C2中,它应该看起来像“John Smith在使用这个公式时遇到了麻烦”,John Smith强调了这一点。下面是我的代码,但它不起作用 - 它强调整个文本字符串。此外,虽然我在这里,我怎么能让它自动运行,而不是必须手动运行宏?提前谢谢。

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

1 个答案:

答案 0 :(得分:1)

在正常模块中尝试此操作(假设“合同”是您的A10所在的位置...)

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

然后在输入工作表模块(已更新)中:

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包含公式,您需要联盟 Intersect()中涉及的其他范围,否则它们不会自动更新其更改。

或者,您可以在工作表计算上强制自动更新,在下面添加到输入工作表模块:

Private Sub Worksheet_Calculate()
    Macro ' Will not work if Worksheet calculation is Manual
End Sub

代码所在位置的屏幕截图:
Location of Code for Module1 Location of Code for Input