用于文本格式化的Excelmacros

数据:

我有下面的表格:

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 

问题:

我想将数据合并到一个列中。 单行的macros代码就像这样。我通过一个button来运行代码。

码:

 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 

再问一遍:

数字被格式化。 他们有不同的颜色。 我怎样才能合并在一个单元格,并保持颜色格式?

此代码将存储颜色值,连接单元格,然后根据存储的颜色值为string着色。 应该更改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 

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

一个例子是:

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