Learn when you want, where you want with convenient online training courses. Sign up now!
Experts Exchange Solution brought to you by
"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.
Dim rg As Range, rgHeaders As Range, targ As Range
Dim v As Variant, vHeaders As Variant, vv As Variant
Dim i As Long, j As Long, jj As Long, k As Long, nCols As Long, nFixedCols As Long, nRows As Long
nFixedCols = 2 'Each row of reformatted data will have this many fixed columns. Another two columns will include the variable data & type.
On Error Resume Next
Set rg = Application.InputBox("Please select your data", Default:=Range("A1").CurrentRegion.Address, Type:=8)
If rg Is Nothing Then Exit Sub
Set rgHeaders = Application.InputBox("Please select your header labels", Default:=rg.Rows(1).Address, Type:=8)
Set targ = Application.InputBox("Where do you want results to go?", Default:=rg.Cells(1).Address, Type:=8)
If targ Is Nothing Then Exit Sub
On Error GoTo 0
Set rg = Intersect(rg.Worksheet.UsedRange, rg)
If Not rgHeaders Is Nothing Then
Set rgHeaders = Intersect(rgHeaders, rg.EntireColumn)
If rg.Row = rgHeaders.Row Then Set rg = rg.Offset(1, 0).Resize(rg.Rows.Count - 1)
nCols = rg.Columns.Count
nRows = rg.Rows.Count
ReDim vHeaders(1 To nCols)
For j = 1 To nCols
If rgHeaders Is Nothing Then
vHeaders(j) = "Column " & j
vHeaders(j) = rgHeaders.Cells(1, j).Value
v = rg.Value
ReDim vv(1 To nRows * (nCols - nFixedCols), 1 To nFixedCols + 2)
For i = 1 To nRows
For j = nFixedCols + 1 To nCols
If v(i, j) <> "" Then
k = k + 1
For jj = 1 To nFixedCols
vv(k, jj) = v(i, jj)
vv(k, nFixedCols + 1) = v(i, j)
vv(k, nFixedCols + 2) = vHeaders(j)
ReDim Preserve vv(1 To k, 1 To nFixedCols + 2)
If Not Intersect(rg, targ.Resize(2)) Is Nothing Then
If Not rgHeaders Is Nothing Then rgHeaders.ClearContents
For jj = 1 To nFixedCols
targ.Cells(1, jj).Value = vHeaders(jj)
targ.Cells(1, nFixedCols + 1).Value = "Value" 'Change label to suit
targ.Cells(1, nFixedCols + 2).Value = "Type" 'Change label to suit
targ.Cells(2, 1).Resize(k, nFixedCols + 2).Value = vv
Open in new window
Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.
From novice to tech pro — start learning today.
Premium members can enroll in this course at no extra cost.