使用VBA在Excel中展平表

时间:2018-03-08 20:45:46

标签: database excel vba excel-vba transformation

我希望使用VBA将原始数据提取转换为用于查询的展平表。目前,我在Excel中有一个原始数据表,它总结了给定参与的阶段A,B和C的状态(注意:一些参与可能没有所有3个阶段的数据)。

let modifiedBarGraphValues = [
{
    'name': 'sun',
    'value': 100,
  },
{
    'name': 'sun',
    'value': 200,
}, ];     

我需要将桌子展平,看起来像这样:

Row| EngagementID | A_date | A_status | B_date | B_status | C_date | C_status
1  |      201     |   2/2  | Approved |        |          |        |          
2  |      201     |        |          |  3/5   | Approved |        |          
3  |      201     |        |          |        |          |  4/1   |  Pending  
4  |      203     |   2/12 | Submitted|        |          |        |          
5  |      203     |        |          |  2/20  | Approved |        |          
6  |      207     |   2/5  | Approved |        |          |        |          

此外,我想为相添加一列,以便我可以标记"每行与其相关的阶段(A,B或C)。

我尝试过以下VBA代码,但它会垂直展平表格,而不是水平展平(将3行合并为1,而不是将3行合并为1):

Row| EngagementID | Date | Status 
1  |      201     |  2/2 | Approved 
2  |      201     |  3/5 | Approved          
3  |      201     |  4/1 | Pending  
4  |      203     |  2/12| Submitted         
5  |      203     |  2/20| Approved          
6  |      207     |  2/5 | Approved 

请帮助!!

1 个答案:

答案 0 :(得分:0)

试试此代码

Sub Test()
Dim a           As Variant
Dim b           As Variant
Dim i           As Long
Dim j           As Long
Dim k           As Long

a = Range("A1").CurrentRegion.Value
ReDim b(1 To UBound(a, 1) * 3, 1 To 3)

For i = 2 To UBound(a, 1)
    For j = 2 To UBound(a, 2) Step 2
        If a(i, j) <> "" And a(i, j + 1) <> "" Then
            k = k + 1
            b(k, 1) = a(i, 1)
            b(k, 2) = a(i, j)
            b(k, 3) = a(i, j + 1)
        End If
    Next j
Next i

Range("J1").Resize(k, UBound(b, 2)).Value = b
End Sub