I'm trying to sum a column that's located in another worksheet. I'm trying to sum everything from C2 downwards in sheet 2 and putting it into the cell in E4 in sheet 1.
I've had this code that has worked perfectly until now and it still works fine by itself
ActiveCell.FormulaR1C1 = "=SUM('Sheet2'!C[-1]:C[-1])"
However, when I now use it I get a 1004 error message that says that its wasn't able to select the cell.
So I tried doing this instead:
ActiveCell.FormulaR1C1 = "=SUM('Sheet2'!C[-1]:C[-1])"
So I tried using this code that I found online but it doesn't work either
Range("E4") = Application.WorksheetFunction.sum(Sheets("Sheet2").Range("C2:C"))
Any advice on the best way to do this?
Thanks,
CodePudding user response:
Instead of taking the whole column C
, I think it's more efficient to find the last row.
An example of how you could do it:
Sub Calculate()
Dim ws As Worksheet, ws2 As Worksheet
Set ws = ThisWorkbook.Sheets("Test") 'Change the name of WS accordingly
Set ws2 = ThisWorkbook.Sheets("Data") 'Change the name of WS accordingly
lastrow = ws2.Cells(Rows.Count, "C").End(xlUp).Row 'Find last row used in column C in sheet 'Data'
ws.Range("E4").Value = Application.Sum(ws2.Range("C2:C" & lastrow))
End Sub
CodePudding user response:
So you need to sum all of column C in Sheet2, except cell C1 In VBA:
Workbook("name of workbook").Sheets(1).Range("E4").Formula = "=SUM(Sheet2!C:C)"
If C1 is a number that you need to keep out of the sum, this will check if C1 is a number and then subtract it from the sum total, if it's not a number it will subtract zero
Workbook("name of workbook").Sheets(1).Range("E4").Formula = "=SUM(Sheet2!C:C)-IF(ISNUMBER(C1),C1,0)"