2017-09-25 135 views
0

我想請教一下VBA,因爲我在VBA編寫新,你可以建議我下面的問題:VBA /宏置簡單的表

我有表像

enter image description here

Source

我要轉的所有數據變成:

enter image description here

感謝您的建議。一帆風順

+1

請提供你....嘗試過的代碼,以便我們可以幫助您更多.... –

+1

查找到技術,「逆透視」。這可以在沒有VBA的情況下完成。 Power Query是一種選擇。支點表反轉樞軸是另一回事。使用你的谷歌技能。 – teylyn

回答

0

請試試這個...

'************************************************************************ 
'The code will work like this 
'1) UnPivot the data on Sheet1 
'2) Insert a New Sheet called Tranposed if not available in the workbook 
'3) Place the output i.e. UnPivoted data on the Transposed Sheet. 
'************************************************************************ 

Sub UnPivotData() 
    Dim wsSource As Worksheet, wsDest As Worksheet 
    Dim x, y, i As Long, j As Long, n As Long 

    'Assuming your raw data is on a sheet called "Sheet1", change it if required 
    Set wsSource = Sheets("Sheet1") 

    x = wsSource.Cells(1).CurrentRegion.Value 
    ReDim y(1 To UBound(x, 1) * UBound(x, 2), 1 To 2) 

    For i = 2 To UBound(x, 1) 
     For j = 2 To UBound(x, 2) 
      If x(i, j) <> "" Then 
       n = n + 1 
       y(n, 1) = x(i, 1) 
       y(n, 2) = x(i, j) 
      End If 
     Next 
    Next 

    On Error Resume Next 
    Set wsDest = Sheets("Transposed") 
    wsDest.Cells.Clear 
    On Error GoTo 0 

    If wsDest Is Nothing Then 
     Sheets.Add(after:=wsSource).Name = "Transposed" 
     Set wsDest = ActiveSheet 
    End If 
    wsDest.Range("A1:B1").Value = Array("Number", "Deatils") 
    wsDest.Range("A2").Resize(UBound(y), 2).Value = y 
    wsDest.Range("A1").CurrentRegion.Borders.Color = vbBlack 
    MsgBox "Data Transposed Successfully.", vbInformation, "Done!" 
End Sub