Excel:如何将文本从多个单元格移到第一个单元格?

时间:2018-08-09 14:57:36

标签: excel excel-formula excel-2010

我有一个excel表格:

我需要一个公式将数据移动到第一个单元格,如下所示。

请帮助我做到这一点。

1 个答案:

答案 0 :(得分:0)

这有效。只要确保将source_rng设置为所需的范围即可。也应该很好地扩展。编辑:现在意识到这不会保留颜色,可以在此工作

Sub main()
Dim ws                              As Worksheet
Dim source_rng                      As Range
Dim target_rng                      As Range
Dim source_data()                   As Variant
Dim clean_data()                    As Variant
Dim column_count                    As Long
Dim row_count                       As Long
Dim i                               As Long
Dim j                               As Long
Dim k                               As Long

    Set ws = ActiveSheet

    Set source_rng = ws.Range("A1:F19200")

    column_count = source_rng.Columns.Count
    row_count = source_rng.Rows.Count

    ReDim source_data(1 To row_count, 1 To column_count)
    ReDim clean_data(1 To row_count * column_count, 1)
    source_data = source_rng

    k = 1
    For j = 1 To row_count
        For i = 1 To column_count
            If source_data(j, i) <> "" Then
                k = k + 1
            End If
        Next i
    Next j

    ReDim clean_data(1 To k, 1)

    k = 1
    For j = 1 To row_count
        For i = 1 To column_count
            If source_data(j, i) <> "" Then
                clean_data(k, 0) = source_data(j, i)
                k = k + 1
            End If
        Next i
    Next j

    source_rng.Clear
    Set target_range = ThisWorkbook.ActiveSheet.Range("A1:A" & UBound(clean_data))
    target_range.value = clean_data
End Sub

enter image description here

enter image description here