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
Related
I would like the user to be able to click the green button on the right of each named range to insert a new data entry row below the named range header. The code I have hard codes the insert row number for the first named range. I need a way to have the code to be smart enough to know that the first row below the header of the second, third, & forth named range will changed.
Another big part is that the inserted row needs to have the same formatting (dropdowns, formulas, color, etc.) as the rows below.
First named range button code:
Sub BidSheetAddRow_Materials()
' BidSheetAddRow_Materials Macro
Rows("19:19").Select
Selection.Copy
Rows("19:19").Select
Selection.Insert Shift:=xlDown
Range("A19").Select
Application.CutCopyMode = False
Selection.ClearContents
Range("C19").Select
Selection.ClearContents
Range("K19").Select
Selection.ClearContents
End Sub
Based on the screenshot all table headers are in colA, the first input row is 3 cells below the header, and the first input cell on each table row is a merged cell.
So this works for me:
Sub AddMaterial()
AddRow "MATERIALS"
End Sub
Sub AddRate()
AddRow "RATE"
End Sub
Sub AddRow(TableHeader As String)
Dim f As Range, ws As Worksheet, c As Range
Set ws = ThisWorkbook.Worksheets("Input") 'or whatever
Set f = ws.Columns("A").Find(what:=TableHeader, lookat:=xlWhole) 'find the header
If Not f Is Nothing Then
Set c = f.Offset(3) 'step down to first input row below header
Do While c.Offset(1).MergeArea.Cells.Count > 1 'keep looping while `c` is merged
Set c = c.Offset(1)
Loop
c.Offset(1).EntireRow.Insert shift:=xlDown 'insert
c.EntireRow.Copy c.Offset(1) 'copy
c.Offset(1).EntireRow.ClearContents 'clear new row
Else
MsgBox "Table header '" & TableHeader & "' not found!"
End If
End Sub
Before/after:
I am new to VBA, I have to copy cell value from one sheet to another. The existing code was
'go to the team sheet and select col 3-5 on last row and copy
Sheets(strname).Activate
ActiveCell.Offset(0, -10).Select
Range(ActiveCell, Cells(ActiveCell.Row, ActiveCell.Column + 2)).Select
Selection.Copy
DoEvents
'select the col 2 on team line and paste
Sheets("dtl overview").Select
ActiveCell.Offset(0, -6).Select
ActiveSheet.paste Link:=True
DoEvents
The problem is , I have added one more column in the 'team' sheet. So the above copy script has to read one cell backward.
Say for example, the above code is reading the data from D,E & F cells. I dont know how...
I am looking for to change the above code to read the value from C,D&E.
Inputs are Welcome & Highly appreciable!
I don't know how you consistently copy from columns D:F using that code either.
What your code does is:
'Activate sheet indicated in the "strname" variable.
'"strName" must be set elsewhere in the code?
Sheets(strname).Activate
'When the sheet is activated a cell will already be selected on there.
'This will be whatever cell was active when the sheet was previously looked at.
'This could easily change if a user selects another cell.
'The "OFFSET" command looks at the same row and ten columns to the left of the ActiveCell.
'If the ActiveCell is not in at least column J (11th column) then this
'will throw an "Application defined or Object Defined error" as it will try and select
'a column before column A.
'The offset cell is then selected - hopefully it will be column D.
ActiveCell.Offset(0, -10).Select
'This will select a range from the ActiveCell plus 2 columns on the same row.
'Hopefully columns D:F
Range(ActiveCell, Cells(ActiveCell.Row, ActiveCell.Column + 2)).Select
'Copy the selection.
Selection.Copy
'Don't need this line unless other code you haven't included needs it.
DoEvents
'Select the "dtl overview" sheet.
Sheets("dtl overview").Select
'Again, whichever cell was last active on "dtl overview" and select the cell 6 columns to the left.
ActiveCell.Offset(0, -6).Select
'Paste a link to the original cells.
'So if you copied D4:F4 on the original sheet (which I'll call "Sheet1") then this will paste
'=Sheet1!D4 , =Sheet1!E4 and =Sheet1!F4
ActiveSheet.Paste Link:=True
'Definitely shouldn't need this now.
DoEvents
At the moment your code looks 10 columns to the left of whichever cell is currently active - so depends which cell you have selected when you run the code.
You don't say which row you want copying, so this code copies row 1 and pastes to cell D1.
Sub Test()
Dim strName As String
strName = "Sheet1"
'ThisWorkbook means the file containing this code.
Dim wrkSht As Worksheet
Set wrkSht = ThisWorkbook.Worksheets(strName)
'Cells(1,4) is row 1, column 4.
'Range(Cells, Cells) shows a start & end cell for the range.
With wrkSht
.Range(.Cells(1, 4), .Cells(1, 6)).Copy _
Destination:=ThisWorkbook.Worksheets("dtl overview").Cells(1, 4)
End With
End Sub
Further reading: With
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.
this is my first post and I am super excited about it. I apologize in advance if my writing wouldn't make sense since I'm not super familiar with coding/programming terms.
Here is the Micro_Enabled_Excel_File which I'm using.
I have an excel file with multiple columns and rows. The number of rows will increase as time passes. I'm trying to filter two columns and copy the latest/most recent datapoint(row) and paste it in a new sheet to create a status report.
Excel Dataset: image
What the results would look like: image
What I have done so far:
Created a Micro to go through columns "SCOPE" and "TRADE NAME" to grab the unique entries and copy it into another sheet called "Code".
Sub First_COPY_STYLE_TO_REPORT()
'creating the Report sheet
Sheets("Report").Select
Cells.Select
Selection.Delete Shift:=xlUp
Sheets("Status Updates").Select
Cells.Select
Selection.Copy
Sheets("Report").Select
ActiveSheet.Paste
Rows("2:1048576").Select
Application.CutCopyMode = False
Selection.ClearContents
End Sub
Created a Micro to create a template for sheet "Report" which will eventually be filled with the results of next Micro.
Sub Second_COPY_UNIQUE_TO_CODE()
'add title to filter columns in the Code sheet
Sheets("Code").Select
Rows("1:1").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("A1").Select
ActiveCell.FormulaR1C1 = "Filter1"
Range("B1").Select
ActiveCell.FormulaR1C1 = "Filter2"
'creating the filter criteria also known as scope and trade name
'Finds Duplicates on SCOPE column and copies it to a new sheet called CODE
Sheets("Status Updates").Select
Dim s1 As Worksheet, s2 As Worksheet
Set s1 = Sheets("Status Updates")
Set s2 = Sheets("Code")
s1.Range(Range("B2"), Range("B2").End(xlDown)).Copy s2.Range("A2")
s2.Range("A:A").RemoveDuplicates Columns:=1, Header:=xlNo
'Finds Duplicates on NAME column and copies it to a new sheet called CODE
Dim s3 As Worksheet, s4 As Worksheet
Set s3 = Sheets("Status Updates")
Set s4 = Sheets("Code")
s1.Range(Range("C2"), Range("C2").End(xlDown)).Copy s2.Range("B2")
s4.Range("B:B").RemoveDuplicates Columns:=1, Header:=xlNo
'Clears formating and autofits column widths
Sheets("Code").Cells.ClearFormats
ThisWorkbook.Worksheets("Code").Cells.EntireColumn.AutoFit
End Sub
Created a Micro (Not Functioning) which includes two loops to filter two columns, sort the first column and copy and paste the second row of the sheet into the sheet "Report".
Sub Third_Generate_Latest_Status_Report()
Dim a1 As Long, a2 As Long, b1 As Long, b2 As Long
a1 = Cells.Find("Filter1").Offset(1, 0).Row
a2 = Cells.Find("Filter1").End(xlDown).Row
b1 = Cells.Find("Filter2").Offset(1, 0).Row
b2 = Cells.Find("Filter2").End(xlDown).Row
Dim g As Long, i As Long
For g = a1 To a2 'Look up for Filter1 column. Then loop through all criterias.
ActiveSheet.Range("$C$1:$J$300").AutoFilter Field:=2, Criteria1:=g
For i = b1 To b2 'Look up for Filter2 column. Then loop through all criterias.
ActiveSheet.Range("$C$1:$J$300").AutoFilter Field:=3, Criteria1:=i
'sort the NO column from largest to smallest (to get the latest/most recent update).
'I have copied this part of the code from the Micro I recorded.
ActiveWorkbook.Worksheets("Status Updates").AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Status Updates").AutoFilter.Sort.SortFields.Add2 _
Key:=Range("C1:C300"), SortOn:=xlSortOnValues, Order:=xlDescending, _
DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Status Updates").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
'I think I need to add code here to copy the row to sheet Report, and run the loop again
End With
Next i 'take next value in column Filter2
Next g 'take next value in column Filter1
End Sub
What I believe I need:
Sheet "Status Updates" - Filter "SCOPE" column and run through all criteria.Then,
Sheet "Status Updates" - Filter "TRADE NAME" column and run through all criteria.
Sort the "NO" column to get the most recent datapoint.
Copy the first row of data (meaning, the first row after the titles)
Paste it in another sheet called "Report".
Could you please take a look at my code and let me know what my mistakes are?
This is my first time coding/programming/using VBA.
Having an extra "code" sheet usually just makes things unnecessarily complicated. And because your "Status Updates" sheet is already sorted with Oldest updates to Newest updates, we know that for any given unique combo, you'll always want the bottom update. We can guarantee pulling that if we loop over your data backwards (from bottom row to first row, that's what the Step -1 does).
Then use a dictionary to check for unique combinations and pull the first encountered row (remember we're going backwards, so the first encountered row will be the latest update) for each unique combo and copy those rows over to your report sheet.
In the end, here's a fairly beginner friendly version of code for this task. I've commented it heavily for clarity so that you can follow along and understand what it does.
Sub tgr()
'Declare and set workbook and worksheet object variables
Dim wb As Workbook: Set wb = ActiveWorkbook
Dim wsUpdt As Worksheet: Set wsUpdt = wb.Worksheets("Status updates")
Dim wsRprt As Worksheet: Set wsRprt = wb.Worksheets("Report")
'Declare and set a range variable that contains your data
Dim rUpdateData As Range: Set rUpdateData = wsUpdt.Range("A2:G" & wsUpdt.Cells(wsUpdt.Rows.Count, "A").End(xlUp).Row)
'Verify data actually exists
If rUpdateData.Row < 2 Then Exit Sub 'If the beginning row is the header row, then no data actually exists
'Use a dictionary object to keep track of unique Scope and Trade Name combos
Dim hUnqScopeTrades As Object: Set hUnqScopeTrades = CreateObject("Scripting.Dictionary")
'Declare your resulting Copy Range variable. This will be used to gather only the range of rows that will be copied over to the Report worksheet
Dim rCopy As Range
'Declare a looping variable
Dim i As Long
'Loop through each row in your Status Updates data. Because your updates are already sorted Oldest to Newest, begin at the end and loop backwards to guarantee newest updates are found first
For i = rUpdateData.Rows.Count To 1 Step -1
'Verify this Scope/Trade combo hasn't been seen before
If Not hUnqScopeTrades.Exists(rUpdateData.Cells(i, 2).Value & "|" & rUpdateData.Cells(i, 3).Value) Then
'This is a newly encountered unique combo
'Add the combo to the dictionary
hUnqScopeTrades(rUpdateData.Cells(i, 2).Value & "|" & rUpdateData.Cells(i, 3).Value) = i
'If this is the first unique combo found, rCopy will be empty, check if that's the case
If rCopy Is Nothing Then
'rCopy is empty, add the first found unique combo to it
Set rCopy = rUpdateData.Cells(i, 1)
Else
'rCopy is not empty, add all additional unique combos with the Union method
Set rCopy = Union(rCopy, rUpdateData.Cells(i, 1))
End If
End If
Next i
'Clear previous results (if any)
wsRprt.Range("A1").CurrentRegion.Offset(1).Clear
'Verify rCopy isn't empty and then copy all rows over
If Not rCopy Is Nothing Then rCopy.EntireRow.Copy wsRprt.Range("A2")
End Sub
We are looking to automate this process using Excel VBA/macros because we process two to ten spreadsheets a week.
We want to extract a certain number of rows per a variable set of phone numbers.
For example: a spreadsheet with 200,000 rows has 20,000 rows assigned to ten phone numbers. We want to extract the first ten rows per phone number. Our resulting file will have 100 rows ordered by phone number.
Notes:
We need to extract a variable number of records per phone number.
The number of columns can vary.
The number of rows can vary.
We need the entire row of data.
The phone number column may be in a different place in each spreadsheet.
The number of phone numbers may vary.
Here's a code that works on one file, but cannot be duplicated to another worksheet because the "field", "criteria" and "rows" change per worksheet.
We thought IndexMatch might work, but it only returns one item, rather than duplicates.
We don't have a VBA solution, so we do this manually.
Any help would be appreciated!
Sub ExtractPh()
' Establish filter
' Choose first unique phone number
Cells.Select
Selection.AutoFilter
ActiveSheet.UsedRange.AutoFilter Field:=25, Criteria1:= _
"800-836-9207"
' Copy ten non-sequential rows from row 1 to row 82
Rows("1:82").Select
Selection.Copy
' Add rows to second sheet
Sheets.Add After:=Sheets(Sheets.Count)
Rows("1:1").Select
ActiveSheet.Paste
' Move second to sheet to first position to save as separate file
Sheets("Sheet1").Select
Application.CutCopyMode = False
Sheets("Sheet1").Move Before:=Sheets(1)
' Return to main data sheet
Sheets("Test LKY job").Select
' Choose second unique phone number in column
ActiveSheet.UsedRange.AutoFilter Field:=25, Criteria1:= _
"800-907-3803"
' Choose second set of ten non-sequential rows and paste to first sheet
Rows("6:26").Select
Selection.Copy
Sheets("Sheet1").Select
Rows("12:12").Select
ActiveSheet.Paste
' Return to main data sheet
Sheets("Test LKY job").Select
' Choose third unique phone number in column
ActiveSheet.UsedRange.AutoFilter Field:=25, Criteria1:= _
"800-538-1668"
' Choose third set of non-sequential rows and paste to first sheet
Rows("4:48").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Select
Rows("22:22").Select
ActiveSheet.Paste
End Sub
Here's some sample code showing how you can filter a sheet, grab a specific number of visible rows, then copy those rows to another sheet.
Sub Tester()
Dim rng As Range, rngDest As Range
Set rngDest = Sheet2.Range("A2")
Set rng = GetFirstVisibleRows(ActiveSheet, 1, "A", 10)
If Not rng Is Nothing Then
rng.EntireRow.Copy rngDest
Set rngDest = rngDest.Offset(rng.Cells.Count, 0)
End If
End Sub
'filter the data on a sheet by a given value in a given column, then
' return a range with the first x visible rows
Function GetFirstVisibleRows(sht As Worksheet, filterColumn As Long, _
filterValue, howManyRows As Long) As Range
Dim c As Range, rngVis As Range, rngCopy As Range
'filter the sheet and find the remaining visible rows (if any)
With sht.UsedRange
.AutoFilter
.AutoFilter Field:=filterColumn, Criteria1:=filterValue
On Error Resume Next '<< ignore error if no visible cells
'offset/resize is to ignore the header row...
Set rngVis = .Columns(1).Offset(1, 0).Resize(.Columns(1).Rows.Count - 1).SpecialCells(xlCellTypeVisible)
On Error GoTo 0 '<< stop ignoring errors
End With
If Not rngVis Is Nothing Then
'some visible (not filtered out) rows, so collect the first x of those...
For Each c In rngVis.Cells
If rngCopy Is Nothing Then
Set rngCopy = c
Else
Set rngCopy = Application.Union(c, rngCopy)
End If
'exit loop if we have enough rows
If rngCopy.Cells.Count >= howManyRows Then Exit For
Next c
End If
Set GetFirstVisibleRows = rngCopy
End Function