用于文本格式的Excel宏

时间:2013-09-04 15:15:33

标签: excel excel-vba vba

数据:

我有下表:

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

再次提问:

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

2 个答案:

答案 0 :(得分:1)

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

一个例子是:

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

答案 1 :(得分: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