Hiya, another quandary for me. I've been able to prompt up a script that does the following:
1. Define a destination table (table 1).
2. Define a source table (table 2).
3. Move columns from table 2 to table 1 based on column header.
The script works wonderfully with one caveat: there cannot be any empty cells in table 1's header row. However, the situation I'm in requires those blank cells to be present. What would need to be modified in order to do so? Hope someone can help out!
Please see below for the script I currently have:
1. Define a destination table (table 1).
2. Define a source table (table 2).
3. Move columns from table 2 to table 1 based on column header.
The script works wonderfully with one caveat: there cannot be any empty cells in table 1's header row. However, the situation I'm in requires those blank cells to be present. What would need to be modified in order to do so? Hope someone can help out!
Please see below for the script I currently have:
VBA Code:
Sub CopyAndRearrangeData()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("ALS Import") ' Change "ALSImport" to your sheet's name
' Find the last column in row 1 of the sheet
Dim lastColumn As Long
lastColumn = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
Dim table1Range As Range
Set table1Range = ws.Range("A2").Resize(53, lastColumn) ' ws.Range (Destination Table Starting Row), Resize (# of Rows, # of Columns)
Dim table2HeaderRow As Range
Set table2HeaderRow = ws.Range("A61").Resize(1, ws.Cells(61, ws.Columns.Count).End(xlToLeft).Column) ' ws.Range (Source Table Starting Row)
Dim i As Integer
For i = 1 To table1Range.Columns.Count
Dim header As String
header = table1Range.Cells(1, i).Value
Dim headerIndex As Long
headerIndex = 0
For Each cell In table2HeaderRow
If cell.Value = header Then
headerIndex = cell.Column
Exit For
End If
Next cell
If headerIndex > 0 Then
Dim destColumn As Range
Set destColumn = table1Range.Columns(i)
Dim sourceColumn As Range
Set sourceColumn = ws.Cells(61, headerIndex).Resize(ws.Cells(ws.Rows.Count, headerIndex).End(xlUp).Row - 60)
' Copy the data
sourceColumn.Copy Destination:=destColumn.Resize(sourceColumn.Rows.Count, 1)
destColumn.NumberFormat = "General"
' Clear the source data (Table 2)
sourceColumn.Clear
End If
Next i
Application.CutCopyMode = False
End Sub