将文本转为列的宏然后将转换后的文本转置为列并插入行

将文本转为列的宏然后将转换后的文本转置为列并插入行

我有一张 Excel 表,其中包含三列 SKU、标题和尺寸,如下所示:

在此处输入图片描述

运行宏后,我需要工作表看起来像这样:

在此处输入图片描述

我坚持添加行以将转换后的文本与列匹配。

答案1

这是如何运作的?

Sub splitBySize()
Dim lastRow As Long, i As Long, k As Long
Dim sizes() As String

lastRow = Cells(Rows.Count, 1).End(xlUp).Row

For i = lastRow To 2 Step -1
    sizes = Split(Cells(i, 3), ", ") 'Add sizes to an array
    If UBound(sizes) <> 0 Then ' If there's more than one size, then...
        Range(Cells(i + 1, 1), Cells(i + UBound(sizes), 1)).EntireRow.Insert
        For k = LBound(sizes) To UBound(sizes) ' This will add the sizes to the new cells inserted
            Cells(i, 3).Offset(k, 0).Value = sizes(k)
        Next k
    End If
Next i

End Sub

基本上,它只是查看每一行,将大小放入数组中,在它们之间添加行,然后用大小填充单元格。

答案2

尝试一下,但将工作表名称(即Sheet1 and Sheet2)更改为工作簿中的工作表。请注意,这Sheet2是一张空白工作表,所需结果将存储在其中。

Option Explicit

Dim wshI As Worksheet
Dim wshO As Worksheet
Dim i As Integer
Dim j As Integer
Dim r As Integer

Sub delimited()

Set wshI = Worksheets("Sheet1") 'change this to the sheet that has your data
Set wshO = Worksheets("Sheet2") 'make a new sheet and change this to its name

'This extract each size to a column (text to columns)
    wshI.Activate
 'Change "100" to the last column of your data
  wshI.Range("C2:C100").TextToColumns Destination:=Range("C2"), DataType:=xlDelimited, _
  TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
  Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
  :=Array(Array(1, 2), Array(2, 2), Array(3, 2), Array(4, 2)), TrailingMinusNumbers:= _
        True

i = 1
j = 3
r = 1
'This put the desired outcome into the sheet2
While wshI.Cells(i, 1) <> ""
    Do While wshI.Cells(i, j) <> ""
        If j = 3 Then
            wshO.Cells(r, 1) = wshI.Cells(i, 1)
            wshO.Cells(r, 2) = wshI.Cells(i, 2)
            wshO.Cells(r, 3) = wshI.Cells(i, 3)
        Else
            wshO.Cells(r, 3) = wshI.Cells(i, j)
        End If
        j = j + 1
        r = r + 1
    Loop
    j = 3
    i = i + 1
Wend

i = 2
j = 4

'This put the data into its original format
While wshI.Cells(i, 1) <> ""
    Do While wshI.Cells(i, j) <> ""
        wshI.Cells(i, 3) = wshI.Cells(i, 3) & ", " & wshI.Cells(i, j)
        wshI.Cells(i, j).Clear
        j = j + 1
    Loop
j = 4
i = i + 1
Wend

End Sub

答案3

您可以使用数据 ► 获取和转换 ► 从表

  • 用逗号或逗号+空格拆分 Size 列
  • 选择 SKU 和标题列
  • 取消透视“其他”列
  • 删除第三列;并将新的第三列重命名为“Size”
  • 保存查询
  • 使用条件格式删除 A 和 B 列中的相应条目
    • CF 公式为 `=AND($A2<>$A1,$B2<>$B1)
    • 自定义数字格式为;;;

相关内容