Private Sub CommandButton1_Click()
Dim Var_Row As Long
Dim Var_Col As Long
Dim objDate1 As Date, _
objDate2 As Date
Dim Table1 As Range, _
Table2 As Range, _
Table3 As Range, _
Table4 As Range, _
FoundCell As Variant
'find the column with header "Name" and use its row and column
'values to specify the tables dynamically
With Sheet1
Set FoundCell = .Cells.Find("Name").Offset(1, 0)
Var_Row = .Cells(.Rows.Count, FoundCell.Column).End(xlUp).Row - FoundCell.Row + 1
Set Table1 = FoundCell.Resize(Var_Row)
End With 'sheet1
With Sheet2
Set FoundCell = .Cells.Find("Name").Offset(1, 0)
Var_Row = .Cells(.Rows.Count, FoundCell.Column).End(xlUp).Row - FoundCell.Row + 1
Set Table2 = FoundCell.Resize(Var_Row, 2)
Set Table3 = FoundCell.Offset(0, -1).Resize(Var_Row)
Set Table4 = FoundCell.Resize(Var_Row)
End With 'sheet2
'First cell in the range
Var_Row = Sheet1.Range("F4").Row
Var_Col = Sheet1.Range("F4").Column
'Copy balance from sheet2 to sheet1 for calculation
For Each C1 In Table1
Sheet1.Cells(Var_Row, Var_Col) = Application.WorksheetFunction.VLookup(C1, Table2, 2, False)
objDate1 = CDate(Application.WorksheetFunction.Index(Table3, Application.WorksheetFunction.Match(C1, Table4, 0), 1))
objDate2 = CDate(Sheet1.Cells(Var_Row, Var_Col - 2).Value)
'Comparing date before update the sheet2 Date and Balance after calculation
'MsgBox ("value2 is " & objDate2)
If objDate2 > objDate1 Then
With Sheet1
.Cells(Var_Row, Var_Col + 2).Value = .Cells(Var_Row, Var_Col).Value _
- .Cells(Var_Row, Var_Col + 1).Value _
+ Sheet1.Cells(Var_Row, Var_Col + 3).Value
End With 'sheet1
With Sheet2
.Cells(Application.WorksheetFunction.Match(C1, Table4, 0) + 1, 3).Value = Sheet1.Cells(Var_Row, 8).Value
.Cells(Application.WorksheetFunction.Match(C1, Table4, 0) + 1, 1).Value = Sheet1.Cells(Var_Row, 4).Value
End With 'sheet2
End If
Var_Row = Var_Row + 1
Next C1
MsgBox "Done"
End Sub
Bookmarks