如何将多列中的数据缩减为一列

时间:2017-10-12 09:22:38

标签: excel vba excel-vba excel-2010

希望有人能够帮助我。我需要编写一个查询,它会将数据从多列(在我的例子中从A:H列)缩小到一列。 原始文件如下所示: enter image description here

我需要逐行缩小数据。我的意思是,查询必须检查第一行并获取数据(名称),然后将其放入“新列”,然后检查第二列并执行相同的操作,并逐一继续这样做。该表有170行。

我发现了一个查询,它将数据从多列缩减为一列,但顺序不同于我需要的顺序。该查询首先从A列获取所有数据并将其放入“新列”,然后从B列获取所有数据并将其放入上一列(A列)数据下的“新列”中。 这是我尝试申请的查询: enter image description here

请有人帮帮我吗?我不得不承认我没有使用UBound和LBound函数,我在这里迷失了。 :(

我将感谢任何建议如何调整此查询。

非常感谢提前! :)

2 个答案:

答案 0 :(得分:1)

Try this. I'm first setting your range to an array. I then loop through the array and 'slice' each row using Application.Index. It then Joins all the content in that row together before Trimming the whitespace left over from either end. This leaves me with the one value in my results array (tmp). The code then clears your source data before leaving all your data in one column.

Sub CombineColumns()
    Dim rng As Range
    Dim tmp As Variant, vaCells As Variant
    Dim i As Long

    Set rng = Sheets("DATA").Range("A2:H200")
    vaCells = rng.Value2

    ReDim tmp(LBound(vaCells) To UBound(vaCells))

    For i = LBound(tmp) To UBound(tmp)
        tmp(i) = Trim(Join(Application.Index(vaCells, i, 0)))
    Next i

    With rng
        .ClearContents
        .Cells(1).Resize(UBound(tmp)).Value2 = Application.Transpose(tmp)
    End With
End Sub

LBound returns the lowest position in the array (usually 0 or 1) and UBound returns the highest

答案 1 :(得分:0)

我觉得这样的事情

for i = 1 to 170
    for y = 1 to 8
        if worksheets("trainers").cells(i,y).value <> "" then 
            worksheets("output").cells(i,1).value = worksheets("trainers").cells(i,y).value
            exit for
        end if
    next y
next i

或在同一张纸上

For i = 1 To 170
Z = 0
    For y = 1 To 8
        If Cells(i, y).Value = "" Then
            Cells(i, y).Delete Shift:=xlToLeft
            Z = Z + 1
            If Z <= 8 Then y = y - 1
        End If
    Next y
Next i