I am reordering columns in an array and removing one column. The mapping is as follows:
| Item | In index | Out Index |
|--------|----------|-----------|
| Item1 | 1 | 6 |
| Item2 | 2 | 4 |
| Item3 | 3 | 5 |
| Item4 | 4 | 7 |
| Item5 | 5 | 8 |
| Item6 | 6 | 9 |
| Item7 | 7 | 10 |
| Item8 | 8 | #N/A |
| Item9 | 9 | 1 |
| Item10 | 10 | 2 |
| Item11 | 11 | 3 |
So, with the following data in range A1:K2
of the active sheet:
| Category 1 | RX9 | East Midlands | 4588 | 14:47:36 | 00:08:25 | 00:14:52 | | 01/10/17 | 09/02/18 | England |
|------------|-----|---------------|------|----------|----------|----------|---|----------|----------|---------|
| Category 1 | RX9 | East Midlands | 4588 | 14:47:36 | 00:08:25 | 00:14:52 | | 01/10/17 | 09/02/18 | England |
I get, after running the code:
| 01/10/17 | 09/02/18 06:09 | England | RX9 | East Midlands | Category 1 | 4588 | 0.616388889 | 0.005844907 | 0.010324074 |
|----------|----------------|---------|-----|---------------|------------|------|-------------|-------------|-------------|
| 01/10/17 | 09/02/18 06:09 | England | RX9 | East Midlands | Category 1 | 4588 | 0.616388889 | 0.005844907 | 0.010324074 |
Notes:
I don't expect the array number of rows to ever exceed 12,240.
The time columns have become doubles in the output. Sorted with code to format the relevant columns - not pertinent to question.
Is there a more efficient way to do this without making arrays left, right and centre?
Option Explicit
Public Const OutputColumnsTotal As Long = 10
Private Sub test()
Dim tempArr() As Variant
With ActiveSheet
tempArr = .Range("A1:K2").Value
tempArr = ShuffleArrayColumns(tempArr)
.Range("A5").Resize(UBound(tempArr, 1), UBound(tempArr, 2)) = tempArr
End With
End Sub
Private Function ShuffleArrayColumns(ByRef tempArr As Variant) As Variant
If Not UBound(tempArr, 2) - 1 = OutputColumnsTotal Then
Debug.Print "Array tempArr as wrong # columns in " & Application.VBE.Activecodepane.CodeModule
Exit Function
Else
Dim i As Long
Dim tempArr2() As Variant
ReDim tempArr2(1 To UBound(tempArr, 1), 1 To OutputColumnsTotal)
For i = LBound(tempArr, 1) To UBound(tempArr, 1)
tempArr2(i, 1) = Format$(tempArr(i, 9),"yyyy-mm-dd") 'to preserve UK date format. Sheet is formatted to display "mmm-yy".
tempArr2(i, 2) = tempArr(i, 10)
tempArr2(i, 3) = tempArr(i, 11)
tempArr2(i, 4) = tempArr(i, 2)
tempArr2(i, 5) = tempArr(i, 3)
tempArr2(i, 6) = tempArr(i, 1)
tempArr2(i, 7) = tempArr(i, 4)
tempArr2(i, 8) = tempArr(i, 5)
tempArr2(i, 9) = tempArr(i, 6)
tempArr2(i, 10) = tempArr(i, 7)
Next i
End If
ShuffleArrayColumns = tempArr2
End Function
"yyyy-mm-dd"
format to the columns regardless of the Excel versionColumns("A").NumberFormat = "yyyy-mm-dd"
. \$\endgroup\$dd/mm/yyyy
issue. You could try using.Range("A1:K2").Value2
andtempArr2(i, 1) = tempArr(i, 9)
..Value2
ignores formatting and uses the integer value of the Date. Of course, you will still have to change the Columns format. It would probably be easier to do it your way. \$\endgroup\$