Hello sos0123,
Here is the updated macro. This will automatically add the SUM formulas to the last column on the "bud" sheet.
'Thread: http://www.excelforum.com/excel-programming/780898-copy-cell-value-from-sheet-to-sheet-with-conditions.html
'Poster: soso123
'Written: June 20, 2011
'Updated: June 25, 2011 - Added SUM formulas to the last column.
'Author: Leith Ross
Option Explicit
Sub Macro1()
Dim budHeaders As Range
Dim budRng As Range
Dim budWks As Worksheet
Dim C As Long
Dim Cell As Range
Dim Dict As Object
Dim EndCell As String
Dim expHeaders As Range
Dim expRng As Range
Dim expWks As Worksheet
Dim Key As Variant
Dim R As Long
Dim StartCell As String
Set expWks = Worksheets("exp")
Set budWks = Worksheets("bud")
Set expRng = expWks.Cells(1, 1).CurrentRegion
Set expHeaders = expRng.Offset(0, 2).Resize(1, expRng.Columns.Count - 2)
Set budRng = budWks.Cells(1, 1).CurrentRegion
Set budHeaders = budRng.Offset(0, 2).Resize(1, budRng.Columns.Count - 2)
Set Dict = CreateObject("Scripting.Dictionary")
Dict.CompareMode = vbTextCompare
'Save the "bud" headers in the lookup array
For Each Cell In budHeaders
Key = Trim(Cell)
If Key <> "" Then
If Not Dict.Exists(Key) Then
Dict.Add Key, 1
End If
End If
Next Cell
'Check for any "exp" headers that are missing in the "bud" headers
For Each Cell In expHeaders
Key = Trim(Cell)
If Key <> "" Then
'Add a new column for the missing header
If Not Dict.Exists(Key) Then
C = budRng.Columns.Count
budRng.Columns(C).EntireColumn.Insert
budWks.Cells(1, C) = Key
End If
End If
Next Cell
'Clear the lookup array
Dict.RemoveAll
'Save the "exp" data and codes in the lookup array
For R = 2 To expRng.Columns(1).Cells.Count
For C = 3 To expRng.Columns.Count
Key = Trim(expRng.Cells(R, 1) & expRng.Cells(1, C))
If Key <> "" Then
If Not Dict.Exists(Key) Then
Dict.Add Key, expRng.Cells(R, C)
End If
End If
Next C
Next R
'Fill in the "bud" sheet
For R = 3 To budRng.Columns(2).Cells.Count Step 3
For C = 3 To budRng.Columns.Count
Key = Trim(budRng.Cells(R - 1, 1) & budRng.Cells(1, C))
If Key <> "" Then
If Dict.Exists(Key) Then
budRng.Cells(R, C) = Dict(Key).Value
End If
End If
Next C
Next R
'Add the sum formulas
With budRng.Columns(budRng.Columns.Count - 1)
StartCell = budRng.Cells(2, 4).Address(False, False)
EndCell = .Cells(2, 1).Address(False, False)
.Cells(2, 1).Offset(0, 1).Formula = "=SUM(" & StartCell & ":" & EndCell & ")"
.Offset(1, 1).Resize(budRng.Rows.Count - 1, 1).FillDown
End With
End Sub
Bookmarks