Insert rows by AutoFill using VBA - excel

I want to create a macro which can insert a new row below the last row, containing the same formulas and formatting (not the values) as the rows above. If I do it by hand I would select an entire row and use the AutoFill feature, but this didn't work out when I try to implement it in my macro.
What I basically did is this:
Sub CommandButton1_Click()
Dim lRow As Long
Dim lRsp As Long
On Error Resume Next
Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select
lRow = Selection.Row() - 1
lRsp = MsgBox("Insert New row above " & lRow & "?", _
vbQuestion + vbYesNo)
If lRsp <> vbYes Then Exit Sub
Rows(lRow).Select
Selection.AutoFill Destination:=Range(lRow, lRow + 1)
End Sub
Thanks in advance!
Insert rows by AutoFill using VBA

why not try to copy the last cell with formula and paste in the range of the new rows.
'Callback for btnRellenarFormulas onAction
Sub btnRellenarFormulas_OnClick()
Sheets("YourSheet").Select ' the sheet you will add rows
'Here add your rows, you current code just to add below will solve the column D problem
Dim nRows As Double, nRowLastFormula As Double
'chose one and remove or comment the other one
nRows = Range("CONFIG_NROWS_DATOS") 'This is a named range with formula counta, which counts the number of rows after add the new rows, in your case the column A
'or you can use the formula in code:
nRows = Application.WorksheetFunction.CountA(Sheets(1).Range("A:A"))
'Remove one or comment
nRowLastFormula = Range("CONFIG_NROWS_FORMULA")'this is a named range with formula counta, which will count the number of rows wiht fomula
'or you can use the formula in code:
'The counta in column D will be less than the countA column A, maybe you will need plus 1 to the nRowLastFormula value: nRowLastFormula=nRowLastFormula +1
nRowLastFormula = Application.WorksheetFunction.CountA(Sheets(1).Range("D:D"))
'Column A
Range("A" & nRowLastFormula).Select
Selection.Copy
Range("A" & nRowLastFormula + 1 & ":A" & nRows).Select
Application.CutCopyMode = False
End Sub
Good Luck

Related

Formula Auto Fill VBA

I managed to get this to work, but the problem is I have to specify the range (in this case I just hard coded C2:c25 and the file will have different row counts every time.
Is there a way to make this run only for the rows that have data?
Sub addFormulas()
ThisWorkbook.Worksheets("Sheet2").Range("C2").Formula = "=(B2/12)*100"
Range("C2").Select
Selection.AutoFill Destination:=Range("C2:C25")
End Sub
You could use xlDown to find your last row number based on column B, so you won't have to change your code next time.
Sub addFormulas()
ThisWorkbook.Worksheets("Sheet2").Range("C2").Formula = "=(B2/12)*100"
Range("C2").Select
'find last row with value
last_row = Range("B2").End(xlDown).Row
Selection.AutoFill Destination:=Range("C2:C" & last_row)
End Sub
But I'm assuming that column B doesn't have blank cells between values. In case column B may have blank cells, you could run a FOR loop to find the last row. It's a lot less efficient, but it works well as long as you don't have a very large number of rows:
Sub addFormulas2()
ThisWorkbook.Worksheets("Sheet2").Range("C2").Formula = "=(B2/12)*100"
Range("C2").Select
For i = 1 To 20
If Range("B" & i) & "" > "" Then last_row = i
Next i
Selection.AutoFill Destination:=Range("C2:C" & last_row)
End Sub
EDIT: Just learned here that using xlUp ir more efficient than FOR and more reliable than xlDown, since it won't have any problems if there's some blank cell in column B:
Sub addFormulas_()
ThisWorkbook.Worksheets("Sheet2").Range("C2").Formula = "=(B2/12)*100"
Range("C2").Select
With Sheets("Sheet2")
last_row = .Range("B" & .Rows.Count).End(xlUp).Row
End With
Selection.AutoFill Destination:=Range("C2:C" & last_row)
End Sub
You can accomplish your task without using AutoFill or Select. It is better to use a With … End With statement. Comments are provide in the code below.
Sub addFormulas()
With ThisWorkbook.Worksheets("Sheet2") 'used to set the focus on the worksheet object
.Cells(2, 3).Resize(.Cells(.Rows.Count, 2).End(xlUp).Row - 1).Formula = "=(B2/12)*100"
'writes the formula in the variable range in column C
'Breakdown...
'the "." (dot) e.g. (.Cells and .Rows) is used to refer to the worksheet object in the With statement
'".Cells(2, 3)" is the start of the range you want to write the formula
'".Resize(.Cells(.Rows.Count, 2).End(xlUp).Row")expands the range to the last use row in column B
'the "- 1" adjusts your range because you started on row 2
End With
End Sub

VBA - How to Autofill all the way to the bottom until the last B cell with data

I recorded a macro and I tried to autofill column C with the COUNTIF function all the way down until B column has their last cell value. It doesn't work with new data so I tried to edit the macro and replace it with Range("D2:D") but that doesn't work.
Sub COUNTIF()
'
' COUNTIF Macro
'
'
Range("D2").Select
ActiveCell.FormulaR1C1 = "=COUNTIF(C[-3],RC[-3])>1"
Range("D2").Select
Selection.AutoFill Destination:=Range("D2:D")
End Sub
Better to find the last cell. Also avoid using select as it slows down your code.
Sub COUNTIF()
Dim LastRowB As Long
LastRowB = Range("B" & Rows.Count).End(xlUp).Row
Range("D2").FormulaR1C1 = "=COUNTIF(C[-3],RC[-3])>1"
Range("D2: " & "D" & LastRowB).FillDown
End Sub
Now change your "=COUNTIF(C[-3],RC[-3])>1" formula to whatever it is you really want to fill down.

Dynamically fill the next empty row with data from another sheet

In advance, I would like to thank anyone who reads this for taking the time to make any suggestions! I have tried other examples I've found on here and none of them seem to work so thanks for any advice!
So essentially I have 3 sheets. In sheet 1, I will be manually entering data into the next empty row (The data spans from Column A to Column U). Sheet 2 is linked to Sheet 1 in a manner to where if I select a row and autofill down to the next one, it will display the data from Sheet 1 (and also increases the values in each cell to account for inflation).
So essentially after I enter data into a new row on Sheet 1, I want to run a macro that will then dynamically autofill the last row on Sheet 2 to the next empty row. I also want this to be repeated going from Sheet 2 to Sheet 3.
An example would be, if Sheet 1 and 2 both have data down to row 35, I want to be able to manually enter data in row 36 and then my macro will autofill row 35 to 36 on Sheet 2.
The code I have written so far is below. To explain, base/basee and home/homee are cells I have named to compare values from specific columns for my if/then statement. I keep getting Error 1004 on the last line where I try and autofill down to the next cell wit Offset(1,0)
Sub PracticeTool()
Dim current1 As Integer
Dim current2 As Integer
Worksheets("City1").Select
Application.Goto Reference:="base"
Selection.End(xlDown).Select
Selection.End(xlDown).Select
current1 = Selection
Worksheets("Inflation").Select
Application.Goto Reference:="basee"
Selection.End(xlDown).Select
Selection.End(xlDown).Select
current2 = Selection
If (current1 <> current2) Then
Application.Goto Reference:="homee"
Selection.End(xlDown).Select
Selection.End(xlDown).Select
Selection.End(xlDown).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.AutoFill Destination:=Selection.Offset(1, 0), Type:=xlFillDefault
End If
End Sub
Sheet 1 Sample Data: https://i.stack.imgur.com/pTFo5.png
Sheet 2 Sample Data: https://i.stack.imgur.com/kufrV.png
I didnt't get exactly what you wanted to compare, but I think you're close.
This code should solve the requirement.
Read the comments and adjust it to fit your needs.
Public Sub AutoFillSheets()
AutoFillRange "Sheet2", "A", "U"
AutoFillRange "Sheet3", "A", "U"
End Sub
Private Sub AutoFillRange(ByVal targetSheetName As String, ByVal fromColumnLetter As String, toColumnLetter As String)
Dim targetSheet As Worksheet
Dim targetRange As Range
Dim targetLastRow As Long
Set targetSheet = ThisWorkbook.Worksheets(targetSheetName)
' Get the last row in source sheet
targetLastRow = targetSheet.Cells(targetSheet.Rows.Count, 1).End(xlUp).Row
' Set the range to copy
Set targetRange = targetSheet.Range(fromColumnLetter & targetLastRow & ":" & toColumnLetter & targetLastRow)
' You had the error in this line (below). Problem is that to use autofill you need to include the rows from which Excel would calculate the source range (see that I took the last row in the first column, and added one to the second column)
targetRange.AutoFill Destination:=targetSheet.Range(fromColumnLetter & targetLastRow & ":" & toColumnLetter & targetLastRow + 1)
End Sub

Append Data to the Last Row of another Worksheet

I simply need to grab a column (range) from one sheet, and append to another sheet. For some reason I keep getting an error 1004 - object/application defined error when trying to run the paste values function.
Any help would be appreciated.
Sub copycontactsiratotpsd()
Dim LastRowIRA2 As Long
Dim LastRowIRA As Long
Dim LastRowPOV As Long
Dim lastrow As Long
'activate source sheet
ActiveWorkbook.Worksheets("IRA").Activate
'copy from rev to ira AG to match # of rows for TPRM Contacts before appending
ActiveWorkbook.Sheets("Rev").Range("B2:B15000").SpecialCells(xlCellTypeVisible).Copy
ActiveWorkbook.Sheets("IRA").Range("AG2:AG15000").PasteSpecial xlPasteValues
'define last rows for all three instances
LastRowIRA = ActiveSheet.Range("A1").CurrentRegion.Rows.count
LastRowIRA2 = ActiveSheet.Range("AG1").CurrentRegion.Rows.count
lastrow = WorksheetFunction.Max(Sheets("TPD").Cells(Rows.count, "A").End(xlUp).Row)
LastRowPOV = ActiveWorkbook.Sheets("TPD").Range("A1").CurrentRegion.Rows.count
'if the number of lastrow in source sheet is equal to total VISIBLE last row within reference sheet then
If LastRowIRA = LastRowIRA2 Then
ActiveWorkbook.Worksheets("IRA").Activate
'copy the data needed, values are generally less than 10000 rows
ActiveWorkbook.ActiveSheet.Range("B2:B10000").Copy
ActiveWorkbook.Sheets("TPD").Range("A", lastrow).PasteSpecial xlPasteValues
'LINE WITH ERROR ABOVE
'else display msg for error handling
Else: MsgBox "Row Count is off! *CHECK*"
End If
ActiveWorkbook.Worksheets("IRA").Activate
Columns(33).EntireColumn.Delete
End Sub
To allow an answer to close this out:
ActiveWorkbook.ActiveSheet.Range("B2:B10000").Copy
ActiveWorkbook.Sheets("TPD").Cells(lastrow, "A").PasteSpecial xlPasteValues
Or:
ActiveWorkbook.ActiveSheet.Range("B2:B10000").Copy
ActiveWorkbook.Sheets("TPD").Range("A" & lastrow).PasteSpecial xlPasteValues

Column selection to lastrow then resize

I have a code that finds the last row of data in column E and selects the column to that last row. I want to be able to select associated data in columns B through D that goes with column E and then sort based on column B. So I thought I would just find the last row in column E then resize by 3 columns and sort from that selection but I keep getting a run-time error 1004 application-defined or object-defined error. I have provided the code I'm using below. Columns B through D contain data past the end of column E. Thanks!
ws.Range("E1:E" & finalrow).Resize(0, 3).Select
You may not always be starting in the first row (e.g. E1) so lastRow may not be applicable without some maths. In that case, use With ... End With statements to shorten the code while explicitly referencing the correct cell and cell ranges.
dim lastRow as long
with ws
lastRow = .cells(.rows.count, "E").end(xlup).row
'option 1
.range("B5:D" & lastRow).select
'option 2
with .range("E5:E" & lastRow)
.offset(0, -3).resize(.rows.count, 3).select
end with
'option 3
.range("E5", .cells(lastRow, "G")).offset(0, -3).select
end with
See How to avoid using Select in Excel VBA macros for more methods on getting away from relying on Range.Select and Range.Activate to accomplish your goals.
Something like:
Sub SelectLast3Cols()
Dim ws As Worksheet, lrow As Long
Set ws = Sheets("Sheet3")
lrow = ws.Range("E" & ws.Rows.Count).End(xlUp).Row
ws.Range("B1", ws.Range("D" & lrow)).Select
End Sub

Resources