在Excel中转​​换数据

时间:2016-07-11 13:23:51

标签: excel vba transformation

我的数据格式为:

Content-Type: text/html; charset="iso-8859-1"

<html>
    <head>
      <title>Test HTML message</title>
    </head>
    <body>
      <p>This is a <b>HTML</b> <i>version</i> of the test message.</p>
      <p><img src="http://oracle-base.com/images/site_logo.gif" alt="Site Logo" />
    </body>
  </html>

我想将其转换为包含基于NAME_1 : "NAME" FIELD_1 : BOOL FIELD_3 FIELD_3 ... FIELD_40 NAME_2 FIELD_1 ... FIELD_40 ... NAME_276 FIELD_1 ... FIELD_40 数据的行的表格,其中列数基于NAME_j值。我尝试过使用以下宏,但它并没有像我想要的那样完成。 (原始数据位于FIELD_i

Sheet1

我该如何处理?我愿意使用python或其他语言来解决这个问题,欢迎任何想法。

1 个答案:

答案 0 :(得分:1)

这有点暴力,但我认为它应该适用于VBA。

Sub foo()
    Dim dataRange As Range
    Dim r As Range
    Dim i As Long
    Dim myNames As Object
    Dim nm As Variant

    Set myNames = CreateObject("Scripting.Dictionary")

    Set dataRange = Range("A1:B1", Range("A1").End(xlDown))

    ' Collect the key/value pairs, organized by the "Name" field, in to a dict.
    For Each r In dataRange.Rows
        If r.Cells(1).Value Like "Name_*" Then
            ' Add a new entry to our myNames dict
            Set myNames(r.Cells(1).Value) = CreateObject("Scripting.Dictionary")
            nm = r.Cells(1).Offset(0, 1).Value
            myNames(r.Cells(1).Value)("Name") = nm
            ' Put the Field1-Field40 values in the dict as well:
            myNames(r.Cells(1).Value)("FieldValues") = Application.Transpose(r.Cells(1).Offset(1, 1).Resize(40, 1).Value)
        End If
    Next

    ' Write the table header to the sheet
    dataRange.Clear
    Range("A1").Value = "Name"
    For i = 1 To 40
        Range("A1").Offset(0, i).Value = "Field_" & CStr(i)
    Next

    ' Write the original data in to the new table:
    For i = 0 To UBound(myNames.Keys())
        nm = myNames.Keys()(i)

        Range("A2").Offset(i).Value = myNames(nm)("Name")
        Range("A2").Offset(i, 1).Resize(1, 40).Value = myNames(nm)("FieldValues")
    Next
End Sub