Autofill error on Range Class - vba

I'm trying to add 2 columns with formulas and autofill down to the last row, but I'm getting an
Autofill method of range class failed
when running the code. It breaks at the line that starts with Activecell.Autofill
Sub addColumnsandChange()
Dim LastRow As Integer
'Finds the value of the last row
LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
Selection.EntireColumn.Insert
Selection.EntireColumn.Insert
ActiveCell.FormulaR1C1 = "YoY% Change"
ActiveCell.Offset(0, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = "3 Year CAGR"
ActiveCell.Offset(1, -1).Range("A1").Select
ActiveCell.FormulaR1C1 = "=IFERROR((RC[-1]-RC[2])/RC[2],"""")"
ActiveCell.Offset(0, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = "=IFERROR((RC[-2]/RC[2])^(1/3)-1,"""")"
ActiveCell.Offset(0, -1).Range("A1:B1").Select
ActiveCell.AutoFill Range("A1:B" & LastRow), Type:=xlFillDefault
Range("A1:B" & LastRow).Select
End Sub
Since incorporating the LastRow variable I have not been able to run the code.
Instead it returns a run-time error
Autofill method of range class failed
when debugging. How should I autofill and end the code?

While it is unclear on where you actually start (e.g. what cell Selection is), I suppose that it could be assumed that you know what you are doing before running the sub procedure. In any event, it is better to .FillDown or simply write the formulas all at once.
Using .FillDown:
Sub addColumnsandChange()
Dim lastRow As Long
'Finds the value of the last row
lastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
With Selection.Cells(1)
.Resize(lastRow, 2).EntireColumn.Insert
.Offset(0, -2).Resize(1, 2) = Array("YoY% Change", "3 Year CAGR")
.Offset(1, -2).FormulaR1C1 = "=IFERROR((RC[-1]-RC[2])/RC[2], TEXT(,))"
.Offset(1, -1).FormulaR1C1 = "=IFERROR((RC[-2]/RC[2])^(1/3)-1, TEXT(,))"
.Offset(1, -2).Resize(lastRow - 1, 2).FillDown
.Offset(0, -2).Resize(lastRow, 2).Select
End With
End Sub
Writing all formulas at once:
Sub addColumnsandChange()
Dim lastRow As Long
'Finds the value of the last row
lastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
With Selection.Cells(1)
.Resize(lastRow, 2).EntireColumn.Insert
.Offset(0, -2).Resize(1, 2) = Array("YoY% Change", "3 Year CAGR")
.Offset(1, -2).Resize(lastRow - 1, 2).FormulaR1C1 = "=IFERROR((RC[-1]-RC[2])/RC[2], TEXT(,))"
.Offset(1, -1).Resize(lastRow - 1, 2).FormulaR1C1 = "=IFERROR((RC[-2]/RC[2])^(1/3)-1, TEXT(,))"
.Offset(0, -2).Resize(lastRow, 2).Select
End With
End Sub

You are trying to autofill starting with the first row.
However, the formulas you are trying to copy are on the second row. Your first row contains header text.
Please note: You don't have to Select a cell before changing it's value. Your code would perform much faster if you would leave our those Selects. (And the code would become much easier to read and understand)

Related

My code generates an infinite loop

My code paste the same formula throughout all of the H2 column. I dont see anywhere in the code where it should do that.
Worksheets("sheet1").Activate
Range("F2").Activate
Do Until IsEmpty(ActiveCell)
If ActiveCell.Value <> "" Then
Pickle = ActiveCell.Address
ActiveCell.Offset(0, 2).Select
ActiveCell.Value = "=IF(" + Pickle + " <TODAY(),""Send Reminder"",""Do not Send Reminder"") "
ActiveCell.Offset(0, -2).Select
End If
ActiveCell.Offset(1, 0).Select
Loop
No loop needed. Use .FormulaR1C1
Do not use Activate and Select, they slow down the code
Dim lastrow As Long
With Worksheets("sheet1")
lastrow = .Cells(.Rows.Count, "F").End(xlUp).Row
.Range("H2:H" & lastrow).FormulaR1C1 = "=IF(RC[-2] <TODAY(),""Send Reminder"",""Do not Send Reminder"") "
End With
This puts the formula in all the cells at once and the RC[-2] properly refers to the same row in Column F

Excel VBA on combining multiple formulas [duplicate]

Hello everyone,
I have a problem to create VBA excel to duplicate data.
How to combine duplicate rows and sum the values 3 column in excel?
Thank you.
this one uses Remove Duplicates:
Sub dupremove()
Dim ws As Worksheet
Dim lastrow As Long
Set ws = Sheets("Sheet1") ' Change to your sheet
With ws
lastrow = .Range("A" & .Rows.Count).End(xlUp).Row
With .Range("B2:C" & lastrow)
.Offset(, 4).FormulaR1C1 = "=SUMIF(C1,RC1,C[-4])"
.Offset(, 4).Value = .Offset(, 4).Value
End With
With .Range("A1:A" & lastrow)
.Offset(, 4).Value.Value = .Value
End with
.Range("E1:G" & lastrow).RemoveDuplicates 1, xlYes
End With
End Sub
edited after OP's clarifications
try this
solution maintaining original data:
Option Explicit
Sub main()
With Worksheets("Sheet01") '<== change "Sheet01" as per your actual sheet name
With .Range("A1:C1").Resize(.Cells(.rows.Count, 1).End(xlUp).Row)
.Copy
With .Offset(, .Columns.Count + 1)
.PasteSpecial xlPasteAll ' copy value and formats
.Columns(2).Offset(1).Resize(.rows.Count - 1, 2).FormulaR1C1 = "=SUMIF(C1,RC1,C[-" & .Columns.Count + 1 & "])"
.Value = .Value
.RemoveDuplicates 1, xlYes
End With
End With
End With
End Sub
solution overwriting original data (kept for reference):
Sub main()
Dim helperRng As Range, dataRng As Range
Dim colToFilter As String
Dim colsToSumUp As Long
With Worksheets("Sheet01") '<== change "Sheet01" as per your actual sheet name
Set dataRng = .Range("A2:C2").Resize(.Cells(.rows.Count, 1).End(xlUp).Row - 1)
colToFilter = "A" ' set here the column header you want to sum up on
colsToSumUp = 3 ' number of adjacent columns to sum up with
Set helperRng = dataRng.Offset(, .UsedRange.Columns.Count + 1).Resize(, 1) 'localize "helper" cells first column out of sheet used range
With helperRng
.FormulaR1C1 = "=RC" & Cells(1, colToFilter).Column 'make a copy of the values you want to sum up on
.Offset(, 1).FormulaR1C1 = "=if(countif(R1C[-1]:RC[-1], RC[-1])=1,1,"""")" 'localize with "1" first occurrence of each unique value
With .Offset(, 2).Resize(, colsToSumUp)
.FormulaR1C1 = "=sumif(C" & helperRng.Column & ", RC" & helperRng.Column & ",C[" & Cells(1, colToFilter).Column - helperRng.Column - 1 & "])" 'sum up in adjacent columns
.Value = .Value 'get rid of formulas
End With
.Offset(, 1).SpecialCells(xlCellTypeFormulas, xlTextValues).EntireRow.Delete 'delete rows with repeted values you want to sum up on
dataRng.Columns(2).Resize(.rows.Count, colsToSumUp).Value = .Offset(, 2).Resize(.rows.Count, colsToSumUp).Value 'copy summed up values from "helper" cells
helperRng.Resize(, 1 + 1 + colsToSumUp).Clear 'clear "helper" cells
End With
End With
End Sub
it's commented so that you can follow the code and adapt to your actual data "structure"

Code works when running via editor but not when clicking hyperlink

The purpose of my macro is to simply take some information from one sheet and transfer it to another to prevent having to re-enter information. The code works perfectly when I run it via the VBA editor but results in in a Run-time error '1004': Applicaiton-defined or object-defined error when I try to run it via the hyperlink. I know the hyperlink is linked to the correct macro. What's going on?
Sub Insert_PCO_Row()
' Insert_PCO_Row Macro
' Inserts PCO information into COR log if COR number is entered in COR number column in "Sub Pricing" Worksheet.
Dim corNum As Range
Dim nextOpen As Range
Sheets("Sub Pricing").Select
Range("C3").Select
Set corNum = Sheet6.Range("A1:A1000")
Do Until Selection.Offset(0, -1) = ""
'Checks if COR # is entered in "Sub Pricing" tab OR if the COR # is already entered in "COR Log" tab.
If Selection.Value = "" Or Application.WorksheetFunction.CountIf(corNum, Selection.Value) > 0 = True Then
Selection.Offset(1, 0).Select
Else
Set nextOpen = Sheet6.Range("A9").End(xlDown).Offset(1, 0)
Selection.Copy
nextOpen.PasteSpecial xlPasteValues
Selection.Offset(0, 1).Copy
nextOpen.Offset(0, 1).PasteSpecial xlPasteValues
Selection.Offset(0, -2).Copy
nextOpen.Offset(0, 2).PasteSpecial xlPasteValues
Selection.Offset(0, -1).Copy
nextOpen.Offset(0, 3).PasteSpecial xlPasteValues
Selection.Offset(0, 7).Copy
nextOpen.Offset(0, 7).PasteSpecial xlPasteValues
Selection.Offset(1, 0).Select
End If
Loop
Sheets("COR Log").Select
End Sub
Try it without using .Select.
Option Explicit
Sub Insert_PCO_Row()
' Insert_PCO_Row Macro
' Inserts PCO information into COR log if COR number is entered in COR number column in "Sub Pricing" Worksheet.
Dim rw As Long, nrw As Long
With Worksheets("Sub Pricing")
For rw = 3 To .Cells(Rows.Count, 2).End(xlUp).Row
With .Cells(rw, 3)
If CBool(Len(.Value2)) And _
Not IsError(Application.Match(.Value2, sheet6.Columns(1), 0)) Then
nrw = sheet6.Cells(Rows.Count, "A").End(xlUp).Row + 1
sheet6.Cells(nrw, 1) = .Value
sheet6.Cells(nrw, 2) = .Offset(0, 1).Value
sheet6.Cells(nrw, 3) = .Offset(0, -2).Value
sheet6.Cells(nrw, 4) = .Offset(0, -1).Value
sheet6.Cells(nrw, 8) = .Offset(0, 7).Value
End If
End With
Next rw
End With
Worksheets("COR Log").Select
End Sub
Using the Range .Select method and relying on the Application.Selection and ActiveCell properties to identify the source and target of your operation is simply not reliable. In a similar vein, direct value transfer is more efficient than a Copy/PasteSpecial, Values operation and does not involve the clipboard.

Change value on specific column when condition is met on another column

I need help regarding the screenshot above. If possible I want a vba code that starts checking in F2 cell in row F(Unit Price) and change the adjacent values of row H and I to "01/01/2010" if the value on unit price is 0 and loop until an empty cell. Thanks in advance.
Range("F1").Select
ActiveSheet.Range("$A$1:$AI$9036").AutoFilter Field:=6, Criteria1:="0"
Range("H3").Select
ActiveCell.FormulaR1C1 = "1/1/2010"
Selection.AutoFill Destination:=Range("H3:I3"), Type:=xlFillCopy
Range("H3:I3").Select
Selection.FillDown
ActiveSheet.Range("$A$1:$AI$9036").AutoFilter Field:=6
Tried this one but the value doesnt change
Sub test()
irow = 2
Do
If (Sheets("Prices").Cells(6, 1).Value = 0) Then Cells(8, 1).Value = "01/01/2010"
irow = irow + 1
Loop Until IsEmpty(Sheets("Prices").Cells(irow, 6))
End Sub
This one works in less than 1 sec with 100,000 rows:
Option Explicit
Public Sub updateDates()
With ThisWorkbook.ActiveSheet.UsedRange
If ActiveSheet.AutoFilter Is Nothing Then .AutoFilter
.AutoFilter Field:=6, Criteria1:="0"
.Columns(8).Offset(1).Resize(.Rows.Count - 1) = "1/1/2010"
.AutoFilter
End With
End Sub
For i = 1 To 100000
With Sheets("Prices")
If .Range("F" & i).Value = "0" Then _
.Range("H" & i).Value = "01/01/2010"
End With
Next i
This one worked

Excel Macro – Change the row based on value

I want to change the macro below to make it changes the color of part of the row, not the cell, based on the cell value.
If the value in cell E2 is "proof", then cells A2-E2 become red.
Sub ChangeColor()
lRow = Range("E" & Rows.Count).End(xlUp).Row
Set MR = Range("E2:E" & lRow)
For Each cell In MR
If cell.Value = "Proof" Then cell.Interior.ColorIndex = 3
Next
End Sub
It's a relatively simple change. Change cell.Interior.ColorIndex = 3 to a specific range as seen in the procedure below.
Sub ChangeColor()
lRow = Range("E" & Rows.Count).End(xlUp).Row
Set MR = Range("E2:E" & lRow)
For Each cell In MR
If cell.Value = "Proof" Then range("a" & cell.row & ":e" & cell.row).Interior.ColorIndex = 3
Next
End Sub
If you have a lot of rows to process, you may wish to abandon the loop process and work with a filter instead.
For A:E highlighting:
Sub highlight_Proof()
With ActiveSheet
With .Cells(1, 1).CurrentRegion
.Cells.Interior.Pattern = xlNone
If .AutoFilter Then .AutoFilter
.AutoFilter Field:=5, Criteria1:="=proof"
With .Offset(1, 0).Resize(.Rows.Count - 1, 5)
If CBool(Application.Subtotal(103, .Cells)) Then _
.SpecialCells(xlCellTypeVisible).Interior.ColorIndex = 3
End With
.AutoFilter
End With
End With
End Sub
For full row highlighting:
Sub highlight_Proof2()
With ActiveSheet
With .Cells(1, 1).CurrentRegion
If .AutoFilter Then .AutoFilter
.AutoFilter Field:=5, Criteria1:="=proof"
With .Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count)
If CBool(Application.Subtotal(103, .Cells)) Then _
.SpecialCells(xlCellTypeVisible).EntireRow.Interior.ColorIndex = 3
End With
.AutoFilter
End With
End With
End Sub
I haven't wildcarded the search for proof but that is a small modification. It seems that your original code was looking for the entire cell value.
With Conditional Formatting, select ColumnsA:E, HOME > Conditional Formatting, New Rule..., Use a formula to determine which cells to format, Format values where this formula is true::
=$E1="proof"
Format..., select red, OK, OK.