Public Sub Rebuild_Tables(ByVal vWorkbook As Variant, _
ByVal vSheet As Variant, _
Optional ByVal fDeleteFirst As Boolean = True)
Dim sRegion As String
Dim nRows As Long
Dim nCols As Long
Dim nOffsetY As Long
Dim nOffsetX As Long
Dim loop1 As Long
Dim loop2 As Long
Dim vCell As Variant
Dim aPhasing() As Variant
' Rebuild_Tables "RebuildTable.xls", "sheet1"
' Rebuild_Tables 1, 1, false
On Error GoTo err_handler
' quick sanity check
If Workbooks(vWorkbook).Name = ThisWorkbook.Name Then
MsgBox "Cannot process " & ThisWorkbook.Name & vbCrLf & vbCrLf _
& "Process will now quit...", vbCritical
Exit Sub
End If
Application.ScreenUpdating = False ' turn screenupdating off for speed
With Workbooks(vWorkbook).Sheets(vSheet)
' get the region of the table from A1
sRegion = .Cells(1, 1).CurrentRegion.Address
nRows = .Range(sRegion).Rows.Count
nCols = .Range(sRegion).Columns.Count
' set dimension of array
ReDim aPhasing(nRows, nCols)
nOffsetY = 1: nOffsetX = 1
' put table in an array
While nOffsetY <= nRows
While nOffsetX <= nCols
vCell = .Cells(nOffsetY, nOffsetX)
aPhasing(nOffsetY, nOffsetX) = vCell
nOffsetX = nOffsetX + 1
Wend
nOffsetY = nOffsetY + 1
nOffsetX = 1
Wend
End With 'sheets(1)
' update normalised table sheet with array
With ThisWorkbook.Sheets(1)
sRegion = .Cells(1, 1).CurrentRegion.Address
If fDeleteFirst Then
.Range(sRegion).EntireColumn.Delete ' clear contents before continue
nOffsetY = 2 ' set rows offset
' set column headings
.Cells(1, 1) = "EMPLOYEE_NAME"
.Cells(1, 2) = "PROJECT_NAME"
.Cells(1, 3) = "HOURS_WORKED"
Else
nOffsetY = .Range(sRegion).Rows.Count + 1
End If
' loop through comms in aPhasing (ignore headings, column1)
For loop1 = 2 To nRows
' loop through weeks in aPhasing (start loop at first week ending, column8)
For loop2 = 8 To nCols
.Cells(nOffsetY, 1).Value = aPhasing(loop1, 1) ' employee
.Cells(nOffsetY, 2).Value = aPhasing(1, loop2) ' project
.Cells(nOffsetY, 3) = aPhasing(loop1, loop2) ' hours worked
nOffsetY = nOffsetY + 1 'next row
Next loop2 ' next project
Next loop1 ' next employee
End With 'Sheets(1)
Application.ScreenUpdating = True ' turn screenupdating back on
'save? nah...
Exit Sub
err_handler:
' msgbox and exit
MsgBox Err.Number & " : " & Err.Description, vbCritical, Err.Source, Err.HelpFile, Err.HelpContext
Debug.Print Err.Number, Err.Description
End Sub