I have a problem in VBA. I created a script to sum up every monthly sum (lastrow of the table; every third column should be added) to a yearly sum. For that I create a string with the sum function in it. Then I want to paste the string into a cell under the monthly table.
Whenever I press the button
error 1004
pops up. I tried my best to solve it myself, but I couldn't fix it. If I pass the string to a msgbox it works fine and I get the =sum(...) displayed on my screen.
'Defintions
Dim lastCol As Long
Dim lastRow As Long
Dim i As Integer
Dim k As Integer
Dim x As Integer
Dim l As String
Dim Squantitys As String
Dim year As String
Dim startYear As Integer
Dim str As String
startYear = 8
'Get Dimensions of results
lastRow = Sheets("results").Cells(Rows.Count, 1).End(xlUp).Row
lastCol = Sheets("results").Cells(1, Columns.Count).End(xlToLeft).Column
'Get the new table ready
Sheets("results").Cells(lastRow + 7, 1).Value = "year"
Sheets("results").Cells(lastRow + 7, 2).Value = "total Quantitys"
'add total Quantitys
Squantitys = "=sum("
For i = 2 To lastCol Step 36
If (lastCol - i) >= 36 Then
For k = i To i + 33 Step 3
l = Split(Sheets("results").Cells(lastRow, k).Address, "$")(1)
Squantitys = Squantitys & l & lastRow & ";"
x = k + 3
Next
l = Split(Sheets("results").Cells(lastRow, x).Address, "$")(1)
Squantitys = Squantitys & l & lastRow & ")"
Else
For k = i To lastCol - 3 Step 3
l = Split(Sheets("results").Cells(lastRow, k).Address, "$")(1)
Squantitys = Squantitys & l & lastRow & ";"
x = k + 3
Next
l = Split(Sheets("results").Cells(lastRow, x).Address, "$")(1)
Squantitys = Squantitys & l & lastRow & ")"
End If
'output
year = Sheets("results").Cells(1, i).Value
Sheets("results").Cells(lastRow + startYear, 1).Value = year
'MsgBox Squantitys --- this works fine
Sheets("results").Cells(lastRow + startYear, 2).Value = Squantitys
'reset for next loop
startYear = startYear + 1
Squantitys = "=sum("
Next