【问题标题】:Splitting multiple values in multiple column into rows in Excel.将多列中的多个值拆分为 Excel 中的行。
【发布时间】:2020-04-29 09:33:23
【问题描述】:

我拥有的 excel 列,我需要将 Col B 中的第一个元素映射到 Col C 中的第一个元素等等。

Column A     Column B             Column C
Electrical   Lighting,Thunder     Bad,Good
Mechanical   Nut, Bolt            Bad,Good

我想要的结果:

Column A     Column B     Column C
Electrical   Lighting     Bad
Electrical   Thunder      Good
Mechanical   Nut          Bad
Mechanical   Bolt         Good

【问题讨论】:

    标签: excel excel-formula vba


    【解决方案1】:

    如果所有这些值都在 Sheet1 中,只需确保您的结果中有一个 Sheet2,那么此代码将按照您的预期进行:

    编辑:

    它现在也适用于单个值:

    Sub foo()
    Dim LPosition As Integer 'declare variables
    Dim LPosition2 As Integer
    Dim LastRow As Long
    Dim NextEmptyRow As Long
    Dim strName As String
    Dim TempArray1() As String
    Dim TempArray2() As String
    
    LastRow = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row 'find the last row on column A on Sheet1
    For i = 2 To LastRow 'loop from row 2 to the last row
        strName = Sheet1.Cells(i, 1).Value 'get the value of column A into a variable
        LPosition = InStr(Sheet1.Cells(i, 2).Value, ",") ' check if column B has a comma in it
        If LPosition > 0 Then
            TempArray1 = Split(Sheet1.Cells(i, 2).Value, ",") 'if comma found put values into an array
        Else
            TempArray1(0) = Sheet1.Cells(i, 2).Value
        End If
    
        LPosition2 = InStr(Sheet1.Cells(i, 3).Value, ",") 'check for a comma on Column C
        If LPosition2 > 0 Then
            TempArray2 = Split(Sheet1.Cells(i, 3).Value, ",") 'place values into a separate Array
        Else
            TempArray2(0) = Sheet1.Cells(i, 3).Value
        End If
        For x = 0 To UBound(TempArray1) 'loop through the array
            NextEmptyRow = Sheet2.Cells(Sheet2.Rows.Count, "A").End(xlUp).Row + 1 'check the next free row on Sheet2
            Sheet2.Cells(NextEmptyRow, 1).Value = Trim(strName) 'place appropriate values
            Sheet2.Cells(NextEmptyRow, 2).Value = Trim(TempArray1(x))
            Sheet2.Cells(NextEmptyRow, 3).Value = Trim(TempArray2(x))
        Next x
        ReDim TempArray1(0)
        ReDim TempArray2(0)
    Next i
    End Sub
    

    【讨论】:

    • 感谢您在 @Xabier 上帮助我,当 Col B 和 Col C 在每行中有多个值时,这工作正常。有些行只有 Col B 和 Col C 的单个值,它们应该按原样存在。有没有办法解决这个问题?
    • @M.Rafi 我已经更新了我的答案,它现在也应该适用于单个值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多