如何使用 Excel VBA 宏将多行转置粘贴到两列 - 一列中重复标题,第二列中包含值?

问题描述 投票:0回答:1

我的数据如下所示:

标题A 数据1 数据2 数据3 数据
标题B 数据1 数据2 数据3 数据
标题C 数据1 数据2 数据3 数据

预期输出是:

标题A 数据1
标题A 数据2
标题A 数据3
标题B 数据1
标题B 数据2
标题B 数据3
标题C 数据1
标题C 数据2
标题C 数据3

我目前正在使用以下内容,但它给了我一个纯粹的转置,而不是所需的输出:

Sub CopyPaste_ValuesTranspose()

Application.ScreenUpdating = False

Dim ws1 As Worksheet, ws2 As Worksheet

Set ws1 = Sheets("Sheet1") '<< source sheet name

Set ws2 = Sheets.Add(after:=Sheets(Sheets.Count)) '<< new Sheet

ws1.Range("A1").CurrentRegion.Copy

ws2.Range("A1").PasteSpecial xlValues, Transpose:=True

Application.CutCopyMode = False

ws2.Cells.EntireColumn.AutoFit

Application.ScreenUpdating = True

End Sub

有什么建议吗?

excel vba
1个回答
0
投票
  • 使用PQ转换表格,无需编码
let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type text}, {"Column2", type text}, {"Column3", type text}, {"Column4", type text}, {"Column5", type text}}),
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"Column1"}, "Attribute", "Value"),
    #"Removed Columns" = Table.RemoveColumns(#"Unpivoted Other Columns",{"Attribute"})
in
    #"Removed Columns"

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.