A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
Try this macro:
Sub TestMacro()
Dim rngC As Range
Dim rngG As Range
Dim rngH As Range
Dim rngHs As Range
Dim Sht1 As Worksheet
Dim sht2 As Worksheet
Dim v As Variant
Dim m As Variant
Dim strA As String
Set Sht1 = Worksheets("Sheet1")
Set sht2 = Worksheets("Sheet2")
'First, remove unneeded values
sht2.Rows(1).Copy
sht2.Rows(2).Insert
With Intersect(sht2.Rows(2), sht2.Range("A1").CurrentRegion)
.Cells.UnMerge
Intersect(.Cells, sht2.UsedRange).SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=RC[-1]"
.Value = .Value
End With
sht2.Rows(4).Insert
With Intersect(sht2.Rows(4), sht2.Range("A1").CurrentRegion.EntireColumn)
.FormulaR1C1 = "=MATCH(R[-1]C,INDEX(Sheet1!C1:C702,,MATCH(R[-2]C,Sheet1!R[-3],FALSE)),FALSE)"
.Value = .Value
If Application.CountIf(.Cells, "#N/A") > 1 Then
.Cells.SpecialCells(xlCellTypeConstants, 16).EntireColumn.Delete
End If
End With
sht2.Rows(4).Delete
sht2.Rows(2).Delete
For Each rngG In Intersect(Sht1.Range("1:1"), Sht1.UsedRange)
If rngG.Value <> "" Then
v = Application.Match(rngG.Value, sht2.Range("1:1"), False)
If Not IsError(v) Then
For Each rngH In rngG.Offset(1, 0).Resize(Sht1.UsedRange.Rows.Count, 1)
If rngH.Value <> "" Then
strA = sht2.Cells(1, v).MergeArea.Address
Set rngHs = sht2.Range(Replace(strA, 1, 2))
m = Application.Match(rngH.Value, rngHs, False)
If IsError(m) Then
'If it needs to be first
If rngH.Row - 1 = 1 Then
rngHs.Cells(1, 2).EntireColumn.Insert
With rngHs.Cells(1, 1).Resize(sht2.UsedRange.Rows.Count)
.Offset(0, 1).Value = .Value
.ClearContents
.Cells(1, 1).Value = rngH.Value
End With
End If
'If it needs to be in the middle
If rngH.Row - 1 <= rngHs.Cells.Count Then
rngHs.Cells(1, rngH.Row - 1).EntireColumn.Insert
rngHs.Cells(1, rngH.Row - 1).Value = rngH.Value
End If
'If it needs to be as the end
If rngH.Row - 1 > rngHs.Cells.Count Then
rngHs.Cells(1, rngHs.Cells.Count).EntireColumn.Insert
With rngHs.Cells(1, rngHs.Cells.Count).Resize(sht2.UsedRange.Rows.Count)
.Offset(0, -1).Value = .Value
.ClearContents
.Cells(1, 1).Value = rngH.Value
End With
End If
End If
End If
Next rngH
End If
End If
Next rngG
End Sub