I am new to VBA and have been struggling with finding a solution to copying & pasting some formulas into a range with a variable end row. I managed to cobble together the below code, which works, but it is inefficient because it pastes the formulas one row at a time. I would like to copy the formulas and then paste them into the entire range at once (instead of row by row). I have to do this function in a few different sheets and ranges so ideally I'd like to create a sub routine to find the last row. What I don't know is 1) how to find the last row 2) how to reference it when I'm selecting the range to paste the formulas into.
The sheet is setup with data in the first column, starting in cell C9, and the formulas are in D8:I8. I need to copy the formulas into the range of D9.I? (with the last row being the last row of data in column C).
I've been working on this for about 5 hours and am going out of my mind. Any help would be appreciated!
Sample of the code I have managed to write that works but isn't efficient:
Range("D8").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
ActiveCell.Offset(1, -1).Select
Do Until ActiveCell.Value = Empty
ActiveCell.Offset(0, 1).Select
Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
ActiveCell.Offset(0, -1).Select
ActiveCell.Offset(1, 0).Select
Loop
The classic way to find the last used row is shown below. Call the function like Debug.Print LastRow or, directly in the Immediate Window, with ? LastRow
Function LastRow() As Long
With ActiveSheet
LastRow = .Cells(.Rows.Count, "A").End(XlUp).Row
End with
End Function
Observe that both, the .Rows.Count and the result are taken from the ActiveSheet and that the measure is taken in column "A". (You can replace the name "A" with the number 1 in the above formula). If you want to develop the function, pass both the sheet and the column to it as arguments.
.Cells(.Rows.Count, "A") defines the cell A1400000 (or thereabouts), the last cell in the column. Then the function looks for the first occupied cell above that, meaning that if A1 and A10 are in use and A2:A9 are blank, the function will return 10. It's important to understand that .Cells(.Rows.Count, "A").End(XlUp) is a range object, a cell, of which the .Row property holds the number of the row where that range is located.
Now, if you want to define a range D9:I? you might do it like this, setting the range by defining its first and last cell. Observe the 4 leading periods. Each one stands for the object in the With statement, in this case ActiveSheet.
With ActiveSheet
Set MyRange = .Range(.Cells(9, "D"), .Cells(.Rows.Count, "I").End(xlUp))
End With
But that would take the measure for the last used cell in column I. Often it's the first column on the left that is longer than the last column in the required range. In that case you might use code as shown below.
With ActiveSheet
Set MyRange = .Range(.Cells(9, "D"), .Cells(.Rows.Count, "D").End(xlUp))
End With
With MyRange
Set MyRange = .Resize(.Rows.Count, 9)
End With
The code first sets the range for column D only, presuming that column D is the longest one, and then expands it to include 9 columns. Observe the .RowsCount refers to the ActiveSheet in the first With block and to MyRange in the second.
Of course, you could achieve a similar result with this code which calls the LastRow function (which measures the last row in column A):-
With ActiveSheet
Set MyRange = .Range(.Cells(9, "D"), .Cells(LastRow, "I"))
End With
This solution is a Subroutine to fill a range with values (in this case, formulas) and find the LastRow in a separate Function. There are many ways to do this so feel free to modify it how you please.
First this Subroutine receives the relevant Worksheet, range the formulas are in and the Column letter for the start and end of our destination range.
The Sub uses the Range.AutoFill method to fill the destination range, much the same as if you click the bottom right of a cell with a value and drag up/down/left/right to fill the cells in that direction.
Public Sub AutoFillVariableSizedRangeByRow _
(ByRef TargetWorkSheet As Worksheet, _
ByVal TargetValueCellAddress As String, _
ByVal StartColumn As String, _
ByVal EndColumn As String)
Dim RangeValuesArray As Variant
Dim TargetValueCell As Range
Dim TargetRange As Range
Set TargetValueCell = TargetWorkSheet.Range(TargetValueCellAddress)
Set TargetRange = TargetWorkSheet.Range(StartColumn & Right(Mid(TargetValueCellAddress, 4), 1) & ":" & _
EndColumn & LastRow(TargetWorkSheet, "C"))
TargetValueCell.AutoFill TargetRange
End Sub
The LastRow is found by a separate function, which is well explained already in many places on the net, including another answer to this question.
Public Function LastRow(ByRef TargetSheet As Worksheet, ByVal TargetColumnLetter As String) As Long
LastRow = TargetSheet.Cells(Rows.Count, TargetColumnLetter).End(xlUp).Row
End Function
To write the LastRow function with excel references (not user defined variables), it would look like:
Sheet1.Cells(Rows.Count, "C").End(xlUp).Row
To call the sub it could look something like:
Private Sub myProcedure()
AutoFillVariableSizedRangeByRow ThisWorkbook.Sheets("Sheet1"), "D1:I1", "D", "I"
End Sub
In the above, ThisWorkbook.Sheets("Sheet1") is TargetWorkSheet and "D1:I1" is TargetValueCellAddress, "D" and "I" are the start and end columns of our destination range respectively.
In this example, I've put values 1 to 20 down column C and the formula =$C1*$C1 in row 1 of columns D to I, all on Sheet1.
And here is the output after running AutoFillVariableSizedRangeByRow Sheet1, "D1:I1", "D", "I":
As example, the formula across row 8 is =$C8*$C8 and row 20 is =$C20*$C20.
Related
I am very new to VBA and am trying to create a macro that selects the cell next to a specifically named column, names it "UniqueID", has it apply a concatenate formula to the whole column, and then selects the next column over, names it "VerifyID", and has it apply a VLOOKUP to the whole column. What I'm having issues with is having the specific cell selection work. Here is what I have:
Application.CutCopyMode = False
Sheets("PowerBI Data Dump").Select
Selection.AutoFilter
Dim i As Long
Dim LastSamplePrepColumn As Range
Dim rngHeaders As Range
Set rngHeaders = Range("1:1")
Set LastSamplePrepColumn = rngHeaders.Find("UniqueID")
i = LastSamplePrepColumn.Column
j = LastSamplePrepColumn.Column + 1
ActiveSheet.Cells(2, i).Select
ActiveCell.FormulaR1C1 = "=CONCATENATE(RC[-2],RC[-1])"
Selection.AutoFill Destination:=Range("RC2:RC157")
ActiveSheet.Cells(1, j).Select
ActiveCell.FormulaR1C1 = "VerifyID"
ActiveSheet.Cells(2, j).Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-1],UniqueID!C[-26],1,FALSE)"
When debugging, it errors at the last line. My main issue, however, is with having the Range().Select choosing columns by letter instead of by the name of the column. I get data dumps in a variety of formats, so I need it to be able to select a column by the name of the one next to it.
Thanks in advance for any advice.
Edit: I have changed my code to reflect where I am now. I'm still stuck on how to make the formula apply to the whole column without selecting the column by letter.
So you want to find the 'UniqueID' column and then add formulas in the two columns to the right and copy then down?
This code will do that but I think you might need to rethink the VLOOKUP formula.
For a start you can probably replace it with MATCH and if the column UniqueID is going to be in you might want to consider changing the relative column reference, i.e. -26, to an absolute reference.
Dim wsData As Worksheet
Dim LastSamplePrepColumn As Range
Dim rngHeaders As Range
Dim colID As Long
Application.CutCopyMode = False
Set wsData = Sheets("PowerBI Data Dump")
Set rngHeaders = ws.Range("1:1")
colID = Application.Match("UniqueID", rngHeaders, 0)
If Not IsError(colID) Then
With wsData
.Range(.Cells(2, colID + 1), .Cells(.Rows.Count, colID).End(xlUp).Offset(, 1)) _
.FormulaR1C1 = "=CONCATENATE(RC[-2],RC[-1])"
.Range(.Cells(2, colID + 2), .Cells(.Rows.Count, colID).End(xlUp).Offset(, 2)) _
.FormulaR1C1 = "=VLOOKUP(RC[-1],UniqueID!C[-26],1,FALSE)"
End With
End If
I am creating a monthly report that copies cell values and pastes them onto specific rows depending on some simple criteria.
Pre Filter
I already have a IF function that =1 if my conditions are met. This is located in column C.
My goal is to copy 5 cells and simply paste-values them in the row that the filter = 1.
The following VBA has been myself playing with the option to filter to only show that specific row that =1, and then selection the 'Criteria 1', to paste in the first visible row below
Post Filter
Sub Macro11()
'
' Macro11 Macro
'
Dim PasteCell As Range
Set PasteCell = Range("F2").Offset(1, 0).Value 'F2 is the header for Criteria 1'
'Copy values from plan
ThisWorkbook.Worksheets("MonthlyDump").Range("N1:R1").Select
Selection.Copy
'Filter to only show the IF function = 1, plus blanks so the headings still show
ActiveSheet.Range("$C$1:$J$64").AutoFilter Field:=1, Criteria1:="1", _
Operator:=xlOr, Criteria2:="="
'Click on header, then pastes into first visible cell on the row below (the filtered row)
PasteCell.PasteSpecial xlPasteValues, xlPasteSpecialOperationNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
'Clear filters
ActiveSheet.Range("$C$1:$J$64").AutoFilter Field:=1
Range("A1").Select
End Sub
It currently fails on the first line 'Dim PasteCell As range', 424 object required.
But I am wondering if this is the best way to even go about this, ideally I would just like to look down column C until C65, and if it sees a 1, then pastes-values 3 cells to the right.
Is anyone able to come it with an elegant solution to this? My second option would be preferred as this seems the quickest way to a solution without requiring manually filtering.
Thanks
No. This doesn't look like the most suitable method. Please try the code below instead.
Sub Macro11()
' 204
Dim Arr As Variant ' temorary array
Dim Rng As Range ' temporary range
Dim Rt As Variant ' Row: target
Arr = ThisWorkbook.Worksheets("MonthlyDump").Range("N1:R1").Value
With ActiveSheet 'better to name the sheet (!)
' start lookin in row 3
Set Rng = .Range(.Cells(3, "C"), .Cells(64, "C"))
' same as above but last row is dynamic:-
' Set Rng = .Range(.Cells(3, "C"), .Cells(.Rows.Count, "C").End(xlUp))
Rt = Application.Match(1, Rng, 0)
If IsError(Rt) Then
MsgBox "No row matches the criteria.", _
vbExclamation, "Failed to post"
Else
.Cells(Rt + Rng.Row - 1, "D").Resize(1, UBound(Arr, 2)).Value = Arr
End If
End With
End Sub
This code uses the MATCH function to find the first 1 in column C. Actually, this looks like not being the optimum, either. It should be possible to look for the conditions that you use to set column C to 1 and 0, perhaps a date. If the code would look for the date, or whatever other criterium, instead of the 1 column C wouldn't be needed.
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
I am currently trying to write a macro that essentially takes a column,duplicates it to the right, then changes certain references to refer back to the previous column.
I am using the replace method, but because i am looking for a specific string based on the column letter and "2" I used an object to bring together the column letter and the "2".A better way to explain is say I copied column B and inserted it and made a duplicate in column C.
I now want to find "C2 and "C3" in my formulas and change them to "B2" and "B3".
I figured this would be done by finding the aforementioned strings by using the replace method and offsetting them by -1. This has proved rather difficult. Any ideas?
'duplicates column over 1'
ActiveCell.EntireColumn.Select
Selection.Copy
ActiveCell.Offset(0, 1).EntireColumn.Select
Selection.Insert Shift:=xlToRight
Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone
Application.CutCopyMode = False
'Declarations and Instantiations'
Dim rngo As Range, cell As Range, ranger As Range
Dim lookfor As String
Dim UsedRng As Range, LastRow As Long
Set rngo = Selection.EntireColumn
Set UsedRng = ActiveSheet.UsedRange
LastRow = UsedRng(UsedRng.Cells.Count).Row
rngo.Select
Do Until ActiveCell.Row = LastRow + 1
For Each cell In rngo
Col = SPLIT(ActiveCell(1).Address(1, 0), "$")(0) 'returns just the cell letter'
lookfor = (Col & "2") 'combines the column letter with the number(I BELIEVE THIS IS THE SOURCE OF THE ISSUE BUT IM NOT SURE IN WHAT WAY'
'starts to search the new column for "lookfor" which is just the designated string'
rngo.Replace _What:=lookfor, Replacement:="'offset lookfor by 1 column'",_SearchOrder:=xlByRows, MatchCase:=True
Next cell
ActiveCell.Offset(1, 0).Select
Loop
MsgBox ColumnName(Selection)
MsgBox lookfor
End Sub
Solved: change " rngo.Replace" to "ActiveCell.Replace"
Okay, I'm learning scripting for Excel and I've come across something that I just don't know how to do.
I've been asked to help automate the import of a sheet into a sheet and then add some columns off to the side and do some calculations and autofill them to the last row of the imported info. That is no problem. I recently found out however that the sheet that I would import for my office has X number of columns and other offices have Y and Z number of columns in the sheets that they would import. So I'm trying to do this to where it builds the calculation columns at the end of the imported columns. With that bit of background here's where I need some assistance:
Script as written for my office and works:
Range("O1").Select
ActiveCell.FormulaR1C1 = "Remainder"
Range("O2").Select
ActiveCell.FormulaR1C1 = "=MOD(RC[-14],RC[-5])"
Range("O2").Select
Range("O2").AutoFill Destination:=Range("O2:O" & Cells(Rows.Count, "B").End(xlUp).Row)
So now I need to make this relational not Cell Address Specific So I came up with this.
Range("A1").select
Selection.End(xlToRight).Select
ActiveCell.Offset(0, 1).Select
ActiveCell.FormulaR1C1 = "Threshold"
ActiveCell.Offset(1, 0).Select
ActiveCell.FormulaR1C1 = "=IF(RC[-13]>(RC[-5]/3),""Over"",""Under"")"
Range(ActiveCell.Address).AutoFill Destination:=Range(*****How to return the Current Cell Address** : **How to Return the Current Column Letter***** & Cells(Rows.Count, "B").End(xlUp).Row)
I've Tried "ActiveCell.Address":"CHAR(COLUMN()+64))" but That doesn't work and I Just don't know how to get it to set that value to Be the equivalent ?2:? my office running this should autofill from O2:O. But would return P2:P in another.
I'm assuming you want the formula to go in the 1st unused column, no matter how many columns there are. (This will allow for future column use, as well.)
Dim LastCol as integer
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column + 1
Cells(1, LastCol).FormulaR1C1 = "Remainder"
Cells(2, LastCol).FormulaR1C1 = "=MOD(RC[-14],RC[-5])"
Cells(2, LastCol).AutoFill Destination:=Range(Cells(2, LastCol), _
Cells(Cells(Rows.Count, "B").End(xlUp).Row, LastCol))
How's this:
Sub test()
Dim lastCol As Integer, lastRow As Integer, formulaCol As Integer
Dim ws As Worksheet
Set ws = ActiveSheet
' First, let's find the last column (#) and last row (#)
With ws.UsedRange
lastCol = .Columns.Count
lastRow = .Rows.Count
End With
' Now, create the "header, two columns offset from last column"
formulaCol = lastCol + 2
Cells(1, formulaCol).Value = "Remainder"
'Now, let's create a range, that we will fill with the MOD() formula. You can do this _
through resizing a range, instead of selecting and autofill
With ws
.Range(.Cells(2, formulaCol), .Cells(2, formulaCol)).Resize(lastRow - 1, 1).FormulaR1C1 = _
"=IF(RC[-" & formulaCol - 1 & "]>(RC[-2]/3),""Over"",""Under"")"
End With
End Sub
I am assuming a few things: Your raw sheets come with the data in one block. In other words, you don't have a gap of columns between data you need. This will get the last used column and row, and use those to enter your formula.
Also, I assume that you are checking that the first part of your mod() formula refers to the info in Col. A, and the second part is the right most column's data. I think I'm not understanding something, so any more info. about how the data is laid out would be helpful. But also, this avoids using "Select", which is good VBA practice from what I've gathered.