Setting a dynamic paste range within a nested loop - excel

I have code that creates a bunch of new sheets, names them, and then loops through them searching a dataset for the name of the sheet and transposing data rows with a value matching the name of the sheet.
I've gotten it to work transposing each row to the next column to the right, but for printing purposes, I'd like it to move to the bottom of the last pasted cell, skip a row (or better yet, insert a page break), and then paste the next one.
Something about the way I've tried to tell it to count the rows, move down, and then start again, isn't working. It appears to be pasting multiple times over previously pasted data.
I've tried several different ways of counting the rows and adding a row, or inserting a page break, but I can't get it working. I thought maybe I needed to move the rowcount function out of the IF statement, but that didn't work either.
Sub Franchise_Data4()
'searches Raw Data sheet for the Franchise ID associated with each sheet name; then transposes each relevant row onto the associated sheet'
Dim Scol As Range, Cell As Object, rawdata As Worksheet, ws As Worksheet, lc As Long, rowcountA As Integer, startR As Integer, labels As Range
Set rawdata = ThisWorkbook.Worksheets("Raw Data")
Set Scol = rawdata.Range("$C$2:$C$2000") 'Franchise ID column on Raw Data sheet'
Set labels = ThisWorkbook.Worksheets("Raw Data").Range("A1:AZ1")
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Raw Data" And ws.Name <> "Pivot" Then
With ws 'cycles through all of the sheets with Franchise ID's as the name
startR = 0
For Each Cell In Scol 'should scan the C column on the Raw Data sheet'
If IsEmpty(Cell) Then Exit For
If Cell.Value = ws.Name Then 'checks for cells that contain the same Franchise ID as the current sheet in the cycle'
Cell.EntireRow.Copy
ws.Cells(startR + 1, 2).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=True
labels.Copy
ws.Cells(startR + 1, 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=True
End If
rowcountA = Cells(Cells.Rows.Count, "A").End(xlUp).Row
startR = rowcountA + 1
Next
End With
End If
Next ws
Application.CutCopyMode = False
End Sub
It appears to paste the first data set correctly, then move down 1 row (instead of the rowcount+1) and paste again. Then I guess it either stops, or it continues pasting the rest in the same spot.

You need to fully qualify the Worksheet that the Cells are on.
rowcountA = Cells(Cells.Rows.Count, "A").End(xlUp).Row
There's an implicit ActiveSheet here, not a reference to ws as you would want. You already have a With ws...End With so change this line to:
rowcountA = .Cells(.Rows.Count, "A").End(xlUp).Row
Note that there are other instances where you are "repeating" the ws instead of fully taking advantage of the With ws...End With.

Related

Paste to row based on row number value in cell

I am trying to write a macro that copies data from a form (Contractor Entry Form, range "U5:AT5") and pastes it to a database (CONTRACTOR DATABASE).
When a record is edited, it requests the Employee ID# and finds that row on the database, and pastes that row number reference temporarily into cell Contractor Entry Form "L1".
I need to then paste the copied data to the database on that row number (-1) that is referenced in cell "L1". If there is no value in "L1" that means it is a new entry and should then just paste to the last row -- as opposed to pasting over a previous record row.
Help, please. My code is here--
Sub ContractorEntry
Range("U5:AT5").Copy
Sheets("CONTRACTOR_DATABASE").Select
Dim R As Integer
R = Worksheets("CONTRACTOR ENTRY").Range("L1").value
'note-- if there is a value in CONTRACTOR ENTRY L1>0 then
' (it represents a row number --- paste value to that row -1 onto
' Contractor Database sheet.
If Worksheets("CONTRACTOR ENTRY").Range("L1") > 0 Then
Sheets("CONTRACTOR_DATABASE").Cells (R -1, 1)
Selection.PasteSpecial
End If
Else
'if there is no value in cell L1 then the following to just paste to the next blank row
lMaxRows = Cells(Rows.Count, "A").End(xlUpSelection.PasteSpecial.Row
Range("A" & lMaxRows + 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks :=False, Transpose:=False
'This returns to the contractor entry form and clears contents
Sheets("CONTRACTOR ENTRY").Select
Range("D3:M1").Select
Selection.ClearContents
'Should go back to Contractor Entry Form for Name and a new entry in cell D3
Range("D3").Select
End Sub
There's almost never any need to use Select/Activate see here for guidelines on how to improve your code: How to avoid using Select in Excel VBA
Something like this should work:
Sub ContractorEntry()
Dim rw, wsInput As Worksheet, wsDB As Worksheet
'use worksheet varaibles for easier maintenance
Set wsInput = ThisWorkbook.Worksheets("CONTRACTOR ENTRY")
Set wsDB = ThisWorkbook.Worksheets("CONTRACTOR_DATABASE")
rw = wsInput.Range("L1").Value - 1
'if row not present then get next empty row
If rw < 1 Then rw = wsDB.Cells(Rows.Count, "A").End(xlUp).Row + 1
'copy over values directly (no copy/paste)
With wsInput.Range("U5:AT5")
wsDB.Cells(rw, "A").Resize(.Rows.Count, .Columns.Count).Value = .Value
End With
With wsInput
.Activate
.Range("D3:M1").ClearContents
.Range("D3").Select
End With
End Sub

How can I run the same macro on every row until the end of a table?

I need your help. I'm trying to run a macro on every row of a table. I want to have the first and the last interaction date with all clients of the list. What I already did on a macro is to copy the first date from a sheet2 and paste it on sheet1 to get the first date, then with CTRL-Down do it again with the next date to get the last date. However, since it's not a loop, it only does it on the cells I did it. (Down is the code I have). I would like the code to do the same thing on every cell, until the end of the table.
I have attached screenshot of the two sheets. I hope I made myself clear and I hope someone can help you out.
sheet1 sheet2
Sheets("Total").Select
Range("D6923").Select
Selection.End(xlDown).Select
Selection.Copy
Sheets("Timeline").Select
ActiveSheet.Paste
Range("C189").Select
Sheets("Total").Select
Selection.End(xlDown).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Timeline").Select
ActiveSheet.Paste
Range("B190").Select
Sheets("Total").Select
Selection.End(xlDown).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Timeline").Select
ActiveSheet.Paste
Range("C190").Select
Sheets("Total").Select
Selection.End(xlDown).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Timeline").Select
ActiveSheet.Paste
I can see you are very new to this and that is fine, we all were once! Using recorded macros is a good way to see how excel views what you are doing at the time but it is extremely inefficient compared to what it could be. As Ron has mentioned, select really is not a friend of efficient code. For example, your first four lines could be rewritten into one line as:
Sheets("Total").Range("D6923").End(xlDown).copy
However even this isn't the best way. I'm going to assume that you are working from the top of your sheet to the bottom and answer your question based on what I think you are trying to do. I'm also assuming that your sheet called Timeline is sheet 1 and your sheet called Total is sheet 2. Within total I am assuming that any number of entries could be there rather than just the two shown in the three examples given.
Sub ExampleCode()
'Variables, you can create and store things in VBA to make life easier for you
Dim Wb as Workbook 'This is the workbook you are using
Dim wsTimeline as Worksheet 'This is your worksheet called Timeline
Dim wsTotal as Worksheet 'This is your worksheet called as Total
Const rMin as byte = 5 'This is where the loop will start, I'm assuming row 5. As _
this won't change throughout the code and we know it at the _
start it can be a constant
Dim rMax as long 'This will be the last row in your loop
Dim r as long 'This will be how your loop knows which row to use
Dim timelineRow as long 'This will be the row that the data is pasted in Timeline
Dim timelineLastRow as Long 'This is the last row of data in your timeline sheet
Set Wb = Thisworkbook 'Your whole workbook is now stored in the variable Wb
Set wsTimeline = Wb.Sheets("Timeline") 'As the workbook was stored in Wb we can use it as _
shorthand here. Now the sheet Timeline is in wsTimeline
Set wsTotal = Wb.Sheets("Total") 'Same as above, this sheet is now stored
rMax = wsTotal.Cells(Rows.Count, 1).End(xlUp).Row 'This is the equivalent of starting at the _
bottom row in column A and pressing _
Ctrl+Up. This takes you to the last _
row of data in column A. …(Rows.Count, 2)… _
would be column B etc.
timelineLastRow = wsTimeline.Cells(Rows.Count, 1).End(xlUp).Row
'This is the bit where you start to loop, the line below basically says "Do the code in this _
loop for every value between rMin and rMax, each time make 'r' that value (r for row!)
With wsTotal 'Means that anything below starting with '.' will _
be the same as 'wsTotal.'
For r = rMin To rMax
'Ensure working on a line with data
If .Cells(r, 1) = "" Then
r = .Cells(r, 1).end(xlDown).row
If r > rMax Then
End With 'Closes the With statement above as no longer needed.
Exit For 'Exits the loop as we have ended up beyond rMax
End if
End if
'This will look for the person in wsTimeline and if they aren't there then add them
If IsError(Application.Match(.Cells(r, 1), wsTimeline.Range("A3:A" & timelineLastRow), 0)) Then
wsTimeline.Cells(timelineLastRow + 1, 1) = wsTotal.Cells(r, 1)
timelineRow = timeLineLastRow + 1
timelineLastRow = timelineRow
Else
timelineRow = Application.Match(.Cells(r, 1), wsTimeline.Range("A3:A" & timelineLastRow), 0)
End If
'I'm assuming that all records in 'Total' are chronologically ascending with no gaps between _
each row for a single person.
wsTimeline.Cells(timelineRow, 3) = .Cells(r + 2, 4)
If .cells(r + 3, 4) <> "" then
wsTimeline.Cells(timelineRow, 4) = .Cells(r + 2, 4).End(xlDown)
Else
wsTimeline.Cells(timelineRow, 4) = .Cells(r + 2, 4).End(xlDown)
End If
'Now that the data has been brought across from Total to Timeline we can move on to _
the next row.
Next r 'This will add one to the value stored in r and start the code again where _
the loop started
End With
'The loop has now ended having gone through every row in your worksheet called Total.
End Sub

Excel VBA code to filter two columns and extract data

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

Loop in Excel 2013

I am having problems with getting a loop to run.
I have a Source1 spreadsheet with a list of values in Column A on the CC's tab. Each number is to be copied individually into Cell B1 on the Template tab of the Source2 spreadsheet.
Cell B1 triggers a consolidation of information (mainly indexed info) and displays it in a template - an aggregate picture of lots of background data. I then Copy A1:K71, and paste this into the Output tab of the Source1 spreadsheet.
I want to work down the list in Column A of the CC's tab, and append each output from the Source2 spreadsheet into the Output tab automatically.
I have the copy/paste working, but I am having problems with the loop.
Selection.Copy
Windows("Source2.xlsx").Activate
Range("B1").Select
ActiveSheet.Paste
Range("A1:K71").Select
Application.CutCopyMode = False
Selection.Copy
Windows("Source1.xlsm").Activate
Sheets("Ouput").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
ActiveWindow.SelectedSheets.HPageBreaks.Add Before:=ActiveCell
#Andrew, after reading and re-reading your question, I don't think a loop of any kind is necessary. The macro-recorder results you gave above provide information about how you can solve this. I tested this by creating a Source1 Workbook with values placed in column A on a sheet labeled CC's. I also added a sheet labeled Output. Then, I opened a second Workbook with a sheet labeled Template. Here is the sub-procedure I used to produce the result I think you are describing above:
Sub AndrewProject()
' COMMENT: Declare variables used throughout this procedure
Dim InitialVals As Range
Dim OutputVals As Range
Dim FinalResults As Range
Dim FinalOutput As Range
Dim cell As Variant
' COMMENT: Set the range objects so they are easier to manipulate
Set InitialVals = Workbooks("Source1").Worksheets("CC's").Range("A2:A72")
Set OutputVals = Workbooks("Source2").Worksheets("Template").Range("B2:B72")
Set FinalResults = Workbooks("Source2").Worksheets("Template").Range("A2:K72")
Set FinalOutput = Workbooks("Source1").Worksheets("Output").Range("A2:K72")
' COMMENT: This line copies the values in Source1 Workbook and pastes them into Source2 Workbook
InitialVals.Copy
OutputVals.PasteSpecial xlPasteValues
' COMMENT: Additional code goes here to create the desired output. To simplify things, I put a
' function in Source2, column K that concatenates the string "Output" with InitialVals copied
' from Source1. To emulate your Source2 Template, I placed random values between 1 and 1000 in
' Cells A2:A72 and C2:J72.
' COMMENT: Copy the FinalResults from Source2 "Template" tab into the Source1 "Output" tab
FinalResults.Copy
FinalOutput.PasteSpecial xlPasteAll
End Sub
OK #Andrew...this has got to be my last attempt. I believe this answers your question.
Sub AutomateIt()
' Declare your variables
Dim cell As Range
Dim Src1CC As Range
Dim Src2Template As Range
Dim Src2Calcs As Range
Dim Src1Output As Range
Dim NextRow As Long
Dim count As Integer
' Set the ranges so they can be manipulated
Set Src1CC = Workbooks("Source1").Worksheets("CC").Range("A1")
Set Src2Template = Workbooks("Source2").Worksheets("Template").Range("B1")
Set Src2Calcs = Workbooks("Source2").Worksheets("Template").Range("A1:K72")
Set Src1Output = Workbooks("Source1").Worksheets("Output").Range("A1:K72")
Src2Template.ClearContents
count = 0
' Loop through all the cells and calculate stuff
For Each cell In Src1CC.Range(Src1CC, Src1CC.End(xlDown))
'Determine the next empty row (plus a space for readability)
NextRow = Cells(Rows.count, 1).End(xlUp).Row + 2
'Send a copy of the Src1CC cell value to the Src2Template
cell.Copy Src2Template
'Re-calculate A1:K72 based on cell value
Src2Calcs.Calculate
'Copy Src2Calcs results and paste to Source1 Output
Src2Calcs.Copy
Src1Output.PasteSpecial xlPasteValues
count = count + 1
MsgBox "You have pasted " & count & " results."
'Change Src1Output Range so that the next paste is the next blank row
'plus one additional row for readability.
Set Src1Output = Workbooks("Source1").Worksheets("Output").Range(Cells(NextRow, 1), Cells(NextRow, 11))
Next cell
End Sub

Macro to delete contents of cells using their references

I have a list of references of cells to be deleted. The list of references is in sheet "test_url". The list of references point to cells to be deleted that are in another sheet "main_lists".
What I am after is a macro that takes all the references listed in "test_url" sheet, and select their cells in "main_lists" sheet and delete them.
The following macro is what I recorded for two references only in an attempt to demonstrate my problem that necessitated me to copy the reference from "test_url" sheet, then paste it in the NameBox of "main_urls" sheet to select the contents of the designated cell then delete its contents. This process was done manually one cell at a time for a list of 10-20 addresses/references. However, recently this list is over 2000 entries and it is growing:
Sub DeletePermittedCells()
'DeletePermittedCells Macro
Sheets("test_urls").Select
Range("B2").Select
Sheets("test_urls").Select
Selection.Copy
Sheets("main_lists").Select
Application.Goto Reference:="R200045C1"
Application.CutCopyMode = False
Selection.ClearContents
Sheets("test_urls").Select
Range("B3").Select
Selection.Copy
Sheets("main_lists").Select
Application.Goto Reference:="R247138C1"
Application.CutCopyMode = False
Selection.ClearContents
Sheets("test_urls").Select
End Sub
Can someone help with this issue please?
Try this one:
Sub DeletePermittedCells()
Dim rng As Range
Dim arr, c
With Sheets("test_urls")
'storing data in array makes your code much faster
arr = .Range("B2:B" & .Cells(.Rows.Count, "B").End(xlUp).Row).Value
End With
With Sheets("main_lists")
Set rng = .Range(arr(1, 1))
For Each c In arr
Set rng = Union(rng, .Range(c))
Next
End With
rng.ClearContents
End Sub
storing addresses in array (rather than reading each cell from worksheet directly) makes your code much faster.
Note, code assumed that your addresses stored in range B2:B & lastrow where lastrow - is row of last cell with data in column B
This assumes that the list of cells to be cleared in is column A:
Sub ClearCells()
Dim s1 As Worksheet, s2 As Worksheet
Dim N As Long, I As Long, addy As String
Set s1 = Sheets("test_url")
Set s2 = Sheets("main_lists")
N = s1.Cells(Rows.Count, "A").End(xlUp).Row
For I = 1 To N
addy = s1.Cells(I, 1).Value
s2.Range(addy).ClearContents
Next I
End Sub

Resources