【问题标题】:split a single row of data into multiple unique rows into a new sheet to include headers as values and cell contents as values将单行数据拆分为多个唯一行到一个新工作表中,以包括标题作为值和单元格内容作为值
【发布时间】:2017-08-09 11:07:40
【问题描述】:

我发现很多数据拆分 VBA 代码帖子,但没有一个按内容拆分并拉入标题并将结果放入新工作表(我需要将原始数据保留在其原始状态)。

我有一个电子表格,其中包含以国家为标题的列中的值,我需要将每一行拆分为新工作表中的新行,国家在新列中列出,而同一国家列中的值在新行。

我想忽略单元格内容为空白的任何国家/地区标题,如第 3 行示例中所示。

这是原始数据的一个小例子:

这就是我需要将 3 行变成的内容:

虽然我问的是 VBA 代码,但我还不知道如何编写 VBA,只能调整我在互联网上找到的代码以适应我的场景。

【问题讨论】:

    标签: excel split excel-2010 vba


    【解决方案1】:

    由于您是 VBA 编码的新手,我用 For 和 If 编写了一个简单的代码,尝试学习这些函数。 我没有声明每个变量,尝试声明它们并了解数据类型。 last_row 和 last_column 是对 Excel VBA 有很大帮助的变量,主要用于制作动态电子表格

    Sub test()
    'Declare variables here
    Dim sht1, sht2 As Worksheet
    
    'sht1 has the data and sht2 is the output Worksheet, you can change the names
    Set sht1 = ThisWorkbook.Worksheets("Sheet1")
    Set sht2 = ThisWorkbook.Worksheets("Sheet2")
    
    last_row1 = sht1.Range("A65536").End(xlUp).Row
    last_column = sht1.Cells(1, sht1.Columns.Count).End(xlToLeft).Column
    x = 1
    
    'Add header
    sht2.Cells(1, 1) = "Company"
    sht2.Cells(1, 2) = "Country"
    sht2.Cells(1, 3) = "Status"
    'Data add
    For i = 2 To last_row1
    'Assuming Company is in Column 1 or A
        For k = 2 To last_column
            'If cell is different from blank then write data
            If sht1.Cells(i, k) <> "" Then
            sht2.Cells(x + 1, 1) = sht1.Cells(i, 1)
            sht2.Cells(x + 1, 2) = sht1.Cells(1, k)
            sht2.Cells(x + 1, 3) = sht1.Cells(i, k)
            x = x + 1
            End If
        Next k
    Next i
    
    MsgBox "Data Updated"
    End Sub
    

    下一次,尝试学习一些编码并发布您的代码。

    【讨论】:

    • 我通常会尝试自己完成一些工作,但在这种情况下,我真的很难找到任何接近我想要实现的目标。下次我会更加努力。这很好用,非常感谢你。我已标记为正确答案。
    猜你喜欢
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多