【问题标题】:How can I merge text with different color formatting into one cell and keep the color formatting?如何将具有不同颜色格式的文本合并到一个单元格中并保持颜色格式?
【发布时间】:2020-01-21 21:58:38
【问题描述】:

数据:

我有下表:

160  89  85 116 161
147 117 133 148 191
 93  91  94  92 107
147 148 177 133 205
116 147 117 190 148

问题:

我想将数据合并到一个列中。

单行代码,通过一个按钮运行。

代码:

Sub mergeStuff()
    Range("M3").Value = CStr(Range("H3").Value) + "," + CStr(Range("I3").Value) + "," + CStr(Range("J3").Value) + "," + CStr(Range("K3").Value) + "," + CStr(Range("L3").Value)
End Sub

输出示例:

    160,89,85,116,161
    147,117,133,148,191
     93,91,94,92,107
    147,148,177,133,205
    116,147,117,190,148

问题:

数字已格式化。它们有不同的颜色。如何在一个单元格中合并并保持颜色格式?

【问题讨论】:

  • 创建一个临时变量来存储您将要连接的每个单元格的颜色,然后在连接后对其进行着色
  • 所以你建议我应该保存五个颜色值,然后在我连接字符串值之后以某种方式添加它们?

标签: excel vba


【解决方案1】:

此代码将存储颜色值,连接单元格,然后根据存储的颜色值对字符串进行着色。 1 to 5 应更改以反映您要连接的列数。在您的示例中,有 5 列。 1 to 3 部分可以不用管。

Sub mergeStuff()

    Dim arrColors(1 To 5, 1 To 3) As Long
    Dim rIndex As Long
    Dim cIndex As Long
    Dim StartColor As Long
    Dim strOutput As String
    Dim i As Long

    For rIndex = 3 To Cells(Rows.Count, "H").End(xlUp).Row
        StartColor = 1
        strOutput = vbNullString
        For cIndex = Columns("H").Column To Columns("L").Column
            strOutput = strOutput & "," & Cells(rIndex, cIndex).Value
            arrColors(cIndex - Columns("H").Column + 1, 1) = StartColor
            arrColors(cIndex - Columns("H").Column + 1, 2) = Len(Cells(rIndex, cIndex).Value)
            arrColors(cIndex - Columns("H").Column + 1, 3) = Cells(rIndex, cIndex).Font.Color
            StartColor = StartColor + Len(Cells(rIndex, cIndex).Value) + 1
        Next cIndex

        With Cells(rIndex, "M")
            .Value = Mid(strOutput, 2) 'Remove beginning comma
            For i = 1 To UBound(arrColors, 1)
                .Characters(arrColors(i, 1), arrColors(i, 2)).Font.Color = arrColors(i, 3)
            Next i
        End With
    Next rIndex

End Sub

【讨论】:

  • 我试用了这段代码。它绝对是最好的答案,尽管有时我没有按应有的颜色着色。有时这些值是一种颜色或另一种颜色。你知道为什么会这样吗?
  • 我将不得不查看一些代码无法正常工作的示例数据。
【解决方案2】:

您可以使用 .Characters 方法在单元格内或单元格的字符串值内格式化字符。

一个例子是:

Cells(1, 1).Characters(1, 3).Font.Color = RGB(0, 255, 0)

【讨论】:

  • 这就是我要寻找的答案。
猜你喜欢
  • 2014-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-17
  • 2017-01-19
  • 1970-01-01
相关资源
最近更新 更多