【问题标题】:How do I change font for each line in a cell if it starts with a special character?如果单元格中的每一行以特殊字符开头,如何更改其字体?
【发布时间】:2022-02-07 00:42:44
【问题描述】:

如果行以“#”和“-”开头,我需要更改多行单元格中每一行的字体。

我的宏会更改特殊字符的第一个实例及其下方所有内容的字体。
我需要它来检查单元格中的每一行是否以特殊字符(即 # 或 -)开头,如果为真则更改。

Dim i as Range
Dim POS As Long, Before As Long, After As Long

For Each i in Sheet(1).UsedRange.Columns(2).Cells
    POS = 0
    If InStr(1, i.text, "#") > 0 Then POS = InStr(1, i.text, "#")
    If InStr(1, i.text, "-") > 0 Then POS = InStr(1, i.text, "-")

    If POS > 0 Then
        Before = InStrRev(i.text,chr(10), POS)
        After = InStr(POS, i.text, vbNewline)

        With i.Characters(Start:=Before + 1, Length:=After - (Before + 1).font
            .Name = "Consolas"
            .Size = 12
       End With
    End If
Next i

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    这是一种使用 split() 单独检查每一行的方法:

    Sub Tester()
    
        Dim c As Range, arr, ln, n As Long, pos As Long
        
        For Each c In Sheet1.UsedRange.Columns(2).Cells
            If Len(c.Value) > 0 Then
                arr = Split(c.Value, vbLf) 'get an array of lines
                pos = 1                    'start point
                
                For n = 0 To UBound(arr)   'loop over the lines
                    ln = arr(n)
                    Debug.Print ln
                    ' # must be escaped by wrapping in []
                    If Trim(ln) Like "-*" Or Trim(ln) Like "[#]*" Then
                        With c.Characters(Start:=pos, Length:=Len(ln)).Font
                            .Name = "Consolas"
                            .Size = 12
                        End With
                    End If
                    pos = pos + Len(ln) + 1 'move start point
                Next n
            End If 'has any value
        Next c
            
    End Sub
    

    【讨论】:

    • 仅供参考,Trim(ln) Like "-*" Or Trim(ln) Like "[#]*" Then 可以写成Trim(ln) Like "[-#]*" Then(要在字符列表中包含-,它必须是first or last
    • @chrisneilsen - 很好,谢谢
    • @TimWilliams,谢谢你这就像一个魅力。如何以相同的方式搜索单词“Note:”?我尝试以相同的格式使用 Instr(),但它似乎不起作用。
    • @chrisneilsen,谢谢。
    • 如果您希望在行首找到它,则可能是 If Trim(ln) like "Note:*",如果在中间某处,则可能是 If Trim(ln) like "*Note:*"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    相关资源
    最近更新 更多