有時候有這樣一種場景,excel的公式/函數結果都是沒有樣式的,一般情況下只能整體的改變單元格的樣式,不能只修改單元格內部分文本的樣式。由於excel本身的限制,改需求並不能通過公式或VBA函數直接實現。
如下提供一個替代方案:
1. 將公式寫在自定義的單元格內,計算期望的結果
2. 將該列隱藏起來
3. 在VBA中寫入如下代碼,將其值格式化后寫在后一列內
Private Sub Worksheet_Change(ByVal Target As Range) Dim i&, m& Application.EnableEvents = False Set targetcolumn = Me.UsedRange For Each t In targetcolumn If t.Column = 7 Then If t.Value <> "" Then m = Len(t.Value) For i = 1 To m If Mid(t.Value, i, 4) = "Lion" Then Set nextcol = Cells(t.Row, t.Column + 1) nextcol.Value = t.Value With nextcol.Characters(1, i - 1).Font .ColorIndex = 0 End With With nextcol.Characters(i, 4).Font .ColorIndex = 3 End With With nextcol.Characters(i + 4, m - i).Font .ColorIndex = 0 End With Exit For End If Next End If End If Next t Application.EnableEvents = True End Sub
該代碼寫在worksheet里。
4. 最終效果: