Copy 'Selected' Columns
Option Explicit
Sub copySelectedColumns()
Dim srg As Range: Set srg = Range("horiz") ' Select Range
Dim cCount As Long: cCount = Application.CountIf(srg, ">0") ' Columns Count
Dim sData As Variant: sData = srg.Value ' Select Data (Array)
Dim Data As Variant: Data = Range("data").Value ' Data
Dim ColData As Variant: ReDim ColData(1 To cCount) ' Column Data (Array)
Dim n As Long, c As Long
For n = 1 To UBound(sData, 2)
If sData(1, n) > 0 Then
c = c + 1
ColData(c) = sData(1, n)
End If
Next n
Dim rCount As Long: rCount = UBound(Data, 1)
Dim Result As Variant: ReDim Result(1 To rCount, 1 To cCount) ' Result
Dim r As Long
For r = 1 To rCount
For c = 1 To cCount
Result(r, c) = Data(r, ColData(c))
Next c
Next r
Worksheets("Sheet1").Range("L1").Resize(rCount, cCount).Value = Result
End Sub
EDIT
- The improvement is about not allowing impossible columns (greater than the number of columns in the
Data Range (0 was previously included)) and clearing the contents of a previous result.
- The small range study is about writing the addresses of the four ranges to the Immediate window (CTRL+G).
An Improvement feat. a Small Range Study
Sub copySelectedColumns()
Debug.Print "***** The Ranges *****"
Dim srg As Range: Set srg = Range("horiz") ' Select Range
Debug.Print "Select Range: " & srg.Address(0, 0)
Dim sData As Variant: sData = srg.Value ' Select Data (Array)
Dim sCount As Long: sCount = UBound(sData, 2) ' Select Columns Count
Dim drg As Range: Set drg = Range("data") ' Data Range
Debug.Print "Data Range: " & drg.Address(0, 0)
Dim Data As Variant: Data = drg.Value ' Data
Dim dCount As Long: dCount = UBound(Data, 2) ' Data Columns Count
Dim ColData As Variant: ReDim ColData(1 To sCount) ' Column Data (Array)
Dim n As Long, c As Long
For n = 1 To sCount
If sData(1, n) > 0 And sData(1, n) <= dCount Then
c = c + 1
ColData(c) = sData(1, n)
End If
Next n
If c > 0 Then
Dim cCount As Long: cCount = c
Dim rCount As Long: rCount = UBound(Data, 1)
Dim Result As Variant: ReDim Result(1 To rCount, 1 To cCount) ' Result
Dim r As Long
For r = 1 To rCount
For c = 1 To cCount
Result(r, c) = Data(r, ColData(c))
Next c
Next r
With Worksheets("Sheet1").Range("L2")
' Clear contents of previous result.
Dim crg As Range ' Clear Range
Set crg = .Resize(.Worksheet.Rows.Count - .Row + 1, sCount)
Debug.Print "Clear Range: " & crg.Address(0, 0)
crg.ClearContents
' Write result.
Dim rrg As Range: Set rrg = .Resize(rCount, cCount) ' Result Range
Debug.Print "Result Range: " & rrg.Address(0, 0)
rrg.Value = Result
End With
Else
' all values in Select Range are invalid
' (0 or greater than Data Columns Count (dCount))
Debug.Print "The Select Range '" & srg.Address(0, 0) & "' contains " _
& "only invalid data."
End If
End Sub