Sub CopyDataAndSubtractFromExistingValues()
Dim sourceSheet As Worksheet
Dim targetSheet As Worksheet
Dim lastRow As Long
Dim i As Long
Dim accountName As String
Dim accountRow As Range
Dim monthName As String
Dim monthColumn As Integer
Dim valueToSubtract As Double
Dim currentCell As Range
Set sourceSheet = ThisWorkbook.ActiveSheet
monthName = sourceSheet.Range("D1").Value
Set targetSheet = ThisWorkbook.Sheets("3125333")
monthColumn = 0
For i = 18 To 32
If targetSheet.Cells(6, i).Value = monthName Then
monthColumn = i
Exit For
End If
Next i
If monthColumn = 0 Then
MsgBox "Nie znaleziono kolumny dla miesiąca: " & monthName, vbExclamation, "Błąd"
Exit Sub
End If
lastRow = sourceSheet.Cells(sourceSheet.Rows.Count, "F").End(xlUp).Row
For i = 4 To lastRow
accountName = sourceSheet.Cells(i, "E").Value
If InStr(1, accountName, "Total", vbTextCompare) = 0 Then
valueToSubtract = sourceSheet.Cells(i, "F").Value
Set accountRow = targetSheet.Columns("A:A").Find(What:=accountName, LookIn:=xlValues, LookAt:=xlWhole)
If Not accountRow Is Nothing Then
Set currentCell = targetSheet.Cells(accountRow.Row, monthColumn)
currentCell.Value = currentCell.Value - valueToSubtract
Else
MsgBox "Nie znaleziono konta: " & accountName, vbExclamation, "Błąd"
End If
End If
Next i
End Sub