将具有数据列的行转换为具有多行的列(运行时间错误)

我有一行数据如下:

header1 header2 header3 header4 header5 row key datavalue1 datavalue2 datavalue3 datavalue4 datavalue5.... CC Corporate Leadership Community Funding Delivery da1000 50% 50% 

所以基本上,我有一个非规范化的数据集的数据值可能会或可能不会逐行为空。 我需要正常化他们。

  CC Activity Allocation da1000 Community Development 50% da1000 Community Funding Delivery 50% 

等等

我可以通过使用粘贴特殊转换来做到这一点,但我有成千上万的行,我需要确保我得到每个正确的行键。 此外,每一行都有一些与之相关的描述,我需要复制每个数据值。

我试图使用下面的代码,但我得到一个

运行时错误5无效的过程调用或参数

 Sub NormalizeSheet() Dim wsOriginal As Worksheet Dim wsNormalized As Worksheet Dim strKey As String Dim clnHeader As Collection Dim lngColumnCounter As Long Dim lngRowCounterOriginal As Long Dim lngRowCounterNormalized As Long Dim rngCurrent As Range Dim varColumn As Variant Set wsOriginal = ThisWorkbook.Worksheets("Original") 'This is the name of your original worksheet' Set wsNormalized = ThisWorkbook.Worksheets("Normalized") 'This is the name of the new worksheet' Set clnHeader = New Collection wsNormalized.Cells.ClearContents 'This deletes the contents of the destination worksheet' lngColumnCounter = 2 lngRowCounterOriginal = 1 Set rngCurrent = wsOriginal.Cells(lngRowCounterOriginal, lngColumnCounter) ' We'll loop through just the headers to get a collection of header names' Do Until IsEmpty(rngCurrent.Value) clnHeader.Add rngCurrent.Value, CStr(lngColumnCounter) lngColumnCounter = lngColumnCounter + 1 Set rngCurrent = wsOriginal.Cells(lngRowCounterOriginal, lngColumnCounter) Loop 'Here we'll reset our Row Counter and loop through the entire data set' lngRowCounterOriginal = 2 lngRowCounterNormalized = 1 lngColumnCounter = 1 Do While Not IsEmpty(wsOriginal.Cells(lngRowCounterOriginal, lngColumnCounter)) Set rngCurrent = wsOriginal.Cells(lngRowCounterOriginal, lngColumnCounter) strKey = rngCurrent.Value ' Get the key value from the current cell' lngColumnCounter = 2 'This next loop parses the denormalized values for each row' Do While Not IsEmpty(wsOriginal.Cells(lngRowCounterOriginal, lngColumnCounter)) Set rngCurrent = wsOriginal.Cells(lngRowCounterOriginal, lngColumnCounter) 'We're going to check to see if the current value' 'is equal to NULL. If it is, we won't add it to' 'the Normalized Table.' If rngCurrent.Value = "NULL" Then 'Skip it' Else 'Add this item to the normalized sheet' wsNormalized.Range("A" & lngRowCounterNormalized).Value = strKey wsNormalized.Range("B" & lngRowCounterNormalized).Value = clnHeader(CStr(lngColumnCounter)) wsNormalized.Range("C" & lngRowCounterNormalized).Value = rngCurrent.Value lngRowCounterNormalized = lngRowCounterNormalized + 1 End If lngColumnCounter = lngColumnCounter + 1 Loop lngRowCounterOriginal = lngRowCounterOriginal + 1 lngColumnCounter = 1 'We reset the column counter here because we're on a new row' Loop End Sub (CREDIT GOES TO Ben McCormack)