extend sum to dynamic range with excel vba macro - excel

I am trying to extend a sum formula to a dynamic range. The sum includes all values from row 5 till the second last used row in the column, the sum is then in the last used row. However, the number of rows and columns vary, the only thing that stays the same is that the sum should always start in row 5. The sum starts also always in column C. I already managed to write a macro that puts the sum in the last row of column C. I am now working on a macro that extends this sum to all other used columns in the sheet, except for the last column (that contains another value and not a sum).
I am working with selection.autofill. However, I am having issues with declaring the range that i want to fill. VBA gives me an "expected: end of statement" error and I can't figure out why. Can somebody explain to me what I am doing wrong? Is there a better method than selection.autofill - i fear that it might not take over the columns, e.g. actually summing up column D when extended to the cell in column D ?
Here is what i already have:
'
' sumtest Macro
'
'
Dim Cell As Range, sRange As Range
Dim wsDestination As Worksheet
With ThisWorkbook
Set wsDestination = .Worksheets("Overview")
End With
FirstRow = Rows(5).EntireRow
lastRow = wsDestination.Cells(Rows.Count, "A").End(xlUp).Row
LastRow1 = wsDestination.Cells(Rows.Count, "A").End(xlUp).Row
LastColumn1 = wsDestination.Cells(4, wsDestination.Columns.Count).End(xlToLeft).Column
Worksheets("Overview").Select
wsDestination.Cells(lastRow, "C").Select
ActiveCell.Formula = "=SUM(C5:C" & lastRow - 1 & ")"
Range(wsDestination.Cells(LastRow1, 3)).Select
Selection.AutoFill Destination:=Range(wsDestination.Cells(LastRow1,3),wsDestination.Cells(LastRow1,LastColumn -1)) Type:=xlFillDefault
End Sub

This code would write the value of the sum in each column for the last row:
Option Explicit
Sub Sumtest()
With ThisWorkbook.Sheets("Overview")
Dim LastCol As Long: LastCol = .Cells(4, .Columns.Count).End(xlToLeft).Column
Dim Cell As Range
Dim LastRow As Long
For Each Cell In .Range("C4", .Cells(4, LastCol))
LastRow = .Cells(.Rows.Count, Cell.Column).End(xlUp).Row
.Cells(LastRow, Cell.Column) = Application.Sum(.Range(Cell.Offset(1), .Cells(LastRow - 1, Cell.Column)))
Next Cell
End With
End Sub
Note that the code will check the LastRow for every column, so if the columns have different amount of rows the total will be on the first row without data for each column.

Related

Simultaneously copying down the contents of 2 selected, adjacent cells to the last row of a table

I have seen several articles showing how to do this with a specified cell range, but I need to be able to do this with a variable range (whatever range is selected). I am at the point in my macro where there are two cells right next to each other with a formula that needs to be copied down to the end of the table based on how far column A goes (the active cells are in columns B and C). The code I am trying is as follows:
ActiveCell.Resize(1, 2).Select <--Selects the two cells containing a formula in columns B and C.
Set rng = Selection
Selection.AutoFill Destination:=Range("rng" & Range("A" & Rows.Count).End(xlUp).Row)
Range(Selection, Selection.End(xlDown)).Select
This gives an error. I think the problem is with the "rng" but I can't specify something like "3B:50C" because the starting point cells in column B and C could be different row each time this runs. Any help would be appreciated. Thank you so much!
Like this:
Dim lr As Long, ws As Worksheet, c As Range
If TypeName(Selection) <> "Range" Then Exit Sub 'make sure a range is selected
Set c = Selection.Cells(1) 'get the top-left cell
Set ws = c.Worksheet 'parent worksheet
lr = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row 'last occupied row in ColA
c.Resize(1, 2).AutoFill Destination:=ws.Range(ActiveCell, ws.Cells(lr, c.Column + 1))

Copy Formula to last cell in active row range then copy all the way to last column - VBA

I am trying to copy a formula from C2 down to the last cell in the active row range (columns A and B count) then copy that same formula to every column in the active column range (row 1 count)
IE copy formula all the way down then all the way across....
Can you dim both last row and last column in the same Subroutine?
If so, how do I do this? I tried with two subroutines and failed miserably.
Sub ImportSub2()
Dim LastRowColumnA As Long
LastRowColumnA = Cells(Rows.Count, 1).End(xlUp).Row
Range("C2:C" & LastRowColumnA).Formula = "=$A2&C$1"
Call ImportSub3
End Sub
Sub ImportSub3()
Dim lastcolumn As Long
lastcolumn = Cells(Columns.Count, 1).End(xlUp).Column
Range("C2:C" & lastcolumn).Formula = "=$A2&C$1"
End Sub
Yes, this can be done; your first problem above is that you are not finding the last column correctly.
VBA formulas, especially with a mix of relative and absolute references, work better with R1C1 format. This code directly writes the required formula into the cells of interest:
Sub InjectFormula()
Dim LastRow As Long, LastCol As Long
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column
Range(Range("C2"), Cells(LastRow, LastCol)).FormulaR1C1 = "=RC1&R1C"
End Sub
If you want to copy a pre-existing formula from C2, you can instead use
Range(Range("C2"), Cells(LastRow, LastCol)).FormulaR1C1 = Range("C2").FormulaR1C1

Excel VBA: End(xlUp) and End(xlDown) all end up at row 244, which is blank?

I filled B2:GQ244 with formulae, copied the range and pasted by value before sorting the range column by column. The cells in B8:GQ244 were all blanks. Then, I wanted to concatenate the non-blank cells column by column, starting from row 2. To do so, I needed to find the last non-blank cell in each column.
For some reason, both End(xlUp) and End(xlDown) gave row 244, which was empty. I can't figure out why. I thought the file might be corrupted. So, I copied the two sheets and the module to a newly created workbook to no avail. Any explanation why both End(xlUp) and End(xlDown) gave row 244?
.Range("B2:GQ244").Formula = "=IF(ISERROR(FIND( B$1,Sheet9!$H34)),"""",Sheet9!$I34)"
'paste by value to get rid of formulae
.Range("B2:GQ244").Copy
.Range("B2").PasteSpecial Paste:=xlPasteValues
'sort by column
Dim last_row As Long
Dim j As Long
For i = 2 To 200 Step 1
Range(.Cells(2, i), .Cells(245, i)).Sort key1:=.Cells(2, i), order1:=xlAscending
Next i
For i = 2 To 200 Step 1
last_row = .Cells(65536, i).End(xlUp).Row
last_row = .Cells(1, i).End(xlDown).Row
The code below will remove all null strings at the bottom of columns as well as those that contain zeroes.
Sub ClearBlankCells()
' 146
Dim Rng As Range ' working range
Dim R As Long ' intermediate: row
Dim C As Long ' loop counter: columns
Application.ScreenUpdating = False
With ActiveSheet
With .Range("B2:GQ244")
.Formula = "=IF(ISERROR(FIND( B$1,Sheet9!$H34)),"""",Sheet9!$I34)"
' replace formulas with their values
.Copy
.PasteSpecial Paste:=xlPasteValues
End With
Application.CutCopyMode = False
For C = 2 To 200 Step 1
Set Rng = .Columns(C)
R = Application.Evaluate("SUMPRODUCT((" & Rng.Address & "<>"""")*(" & _
Rng.Address & "<>0)*1)")
If R > 0 Then
Set Rng = Range(.Cells(R + 1, C), .Cells(Rows.Count, C))
Rng.ClearContents
End If
' sort by column
' Range(.Cells(2, C), .Cells(245, C)).Sort Key1:=.Cells(2, C), Order1:=xlAscending
Next C
End With
Application.ScreenUpdating = True
End Sub
Note that no blanks or zeroes may be included in the block of data above the bottom of each column, including the caption.
Sorting must be done after such cells have been removed but I left the sort instructions dimmed out because it's wrong either in syntax or by concept. If you need to sort each column the syntax is wrong because the syntax sorts the entire sheet. On the other hand, if you want to sort the entire sheet you don't have to do it in a loop 200 times.
The code runs very slowly which gives rise to two observations.
It spends 99% of its time repairing the damage it has done in its first line.
It looks at a data range which is vastly bigger than what is actually, reasonably, required. Nobody wants to look at a sheet 200 columns and 244 rows.
Therefore there must be much better ways to do achieve what you want.
I can't confirm your findings. Having a blank ActiveSheet and a blank Sheet9 the code below filled the ActiveSheet with zeroes B2:GQ244. It then read the last row xlUp as 244 and xlDown as 2. Both of these values are as expected. Perhaps you have a setting that suppresses the display of zeroes. However, as explained in my comment above, a cell that appears blank isn't necessarily blank and that would also apply to a cell containing a NullString inserted by your formula, even if the formula was subsequently removed leaving the null string in its place.
Sub Examine()
Dim last_row As Long
Dim i As Long
With ActiveSheet
.Range("B2:GQ244").Formula = "=IF(ISERROR(FIND( B$1,Sheet9!$H34)),"""",Sheet9!$I34)"
'paste by value to get rid of formulae
.Range("B2:GQ244").Copy
.Range("B2").PasteSpecial Paste:=xlPasteValues
'sort by column
For i = 2 To 200 Step 1
Range(.Cells(2, i), .Cells(245, i)).Sort Key1:=.Cells(2, i), Order1:=xlAscending
last_row = .Cells(.Rows.Count, i).End(xlUp).Row
Debug.Print last_row ' returns 244
last_row = .Cells(1, i).End(xlDown).Row
Debug.Print last_row ' returns 2
Next i
End With
End Sub
The only mystery remaining, therefore, is why .Cells(1, i).End(xlDown).Row gives you a value of 244. It doesn't. Therefore the solution must be in the conduct of your test, not in its result. Compare your testing method with the one I employed above.

How do I copy a fixed cell into the outermost empty cell

I am trying to copy a fixed column range (D20:D39) into an empty column, say K20:K39. The columns keeps getting updated every time I update (D20:D39), i.e. K, L, M, N... will get updated when I want to copy (D20:D39) over. I am not proficient in coding or computer science and just trying to make my spreadsheet efficient. Any one able to help?
I've looked at some other threads but mostly mentioned copying into a separate worksheet. None mentioned this "rolling" copy n paste mechanism.
The following will calculate the last column used (in row 20, since we'll be copying to there) then will set the column values one column over to the same ones as range D20 to D39:
Sub coppercopy()
Dim lastcol As Integer
lastcol = Sheets("Sheet1").Cells(20, Columns.Count).End(xlToLeft).Column
Range(Cells(20, lastcol + 1), Cells(39, lastcol + 1)).Value = Range("D20:D39").Value
Range(Cells(42, lastcol + 1), Cells(32, lastcol + 1)).Value = Range("D42:D62").Value
End Sub
If you want to copy and paste instead of setting the values to be the same as the range, use this:
Sub coppercopy()
Dim lastcol As Integer
lastcol = Sheets("Sheet1").Cells(20, Columns.Count).End(xlToLeft).Column
Range("D20:D39").copy
Cells(20, lastcol + 1).PasteSpecial xlPasteValues
End Sub
Edit, the first option is edited to include more ranges. This can be done on the same line, but for code readability and ease of use I've put it on a new line. Please note that the Cells( statement always takes an R1C1 notation, unlike the Range( statement. Meaning it references to Cells(Row number, Column number). Keeping this in mind this can be easily updated to include any range to be copied as well by updating to the correct cell reference.
Second edit:
As per the comments, the range needs to be more dynamic while still getting rid of the sum formula when copying. The following sub is adapted to this. It will copy the entire range starting from D20 to the last filled row, and copies it into the next available column as needed. It then loops over the entire copied range +1 (This is to account for a sum formula at the end of the range which needs to be deleted) and if blanks are found (indicating a new "paragraph") it deletes the cell above (always the sum formula for the last paragraph).
Sub coppercopy()
Dim lastcol As Integer, lastr As Integer, cel As Range
lastcol = Sheets("Sheet1").Cells(20, Columns.Count).End(xlToLeft).Column 'determine last column with values
lastr = Sheets("Sheet1").Range("D" & Rows.Count).End(xlUp).Row 'determine last row with values
Range(Cells(20, lastcol + 1), Cells(lastr, lastcol + 1)).Value = Range("D20:D" & lastr).Value 'copy range to column after last used one
For Each cel In Range(Cells(20, lastcol + 1), Cells(lastr + 1, lastcol + 1)) 'If the copied range does not end with a sum formula, omit the `+ 1` after `lastr`.
If cel.Value = "" Then 'loops over all cells and checks for blanks
cel.Offset(-1, 0).Value = "" 'if blank is found, delete cell above
End If
Next cel
End Sub

Excel move row down in conditional statement

I am trying to do the following in Excel:
The easiest way is of course to just drag and drop, but as I have many rows and columns, this is not feasible.
I was thus thinking that the following should work:
=IF(B6="Food", "Food", "insert two blank cells")
However, to my surprise, I was unable to find seomthing which would allow me to actually use "insert shift cells down" in a formula. What do I overlook, do I need to get started with VBA here?
Thanks!
I believe the following code would do what you expect:
Sub foo()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your Sheet above
lastrow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'find the last row with data on Column A
For i = 6 To lastrow 'loop from row 6 to last
If ws.Cells(i, 1).Value = "Food" Then 'if Food is found
ws.Cells(i, 2).Insert Shift:=xlDown 'insert a blank cell on Column B
ws.Cells(i, 2).Insert Shift:=xlDown 'again insert a second blank cell on Column B
End If
Next i
End Sub

Resources