Loop a code to extract sequential column data to different sheets - vba

I apologise for what might be a messy code and/or simple question.
I have searched this site and web and tried various code pieces but my understanding and patience is too limited for the current task. I appreciate your more knowledgeable experience. Now the question..:
I would like to loop a piece of code so that it can be implemented for different ranges. I start with two sheets of data, the second of which contains the refined data with around 66 columns, the first two columns of which will be used for each new sheet. The code first filters the third column and copies the first two and third column, creates a new sheet and pastes the values. Then it returns to Sheet2 to remove the filter and do the same actions for the fourth column.
Since each iteration has repetition e.g. 3, 4, 5... I would like to create a variable that can be used to loop code and make it a lot neater as well as simple to limit the number of loops to the number of columns - 2 (the first two columns). So instead of me writing this code 64 times and changing it for another workbook with 100 columns, I would like to change just a few variables and ranges, if that is a possibility.
Sub CopyPaste()
Dim rg As Range
Set rg = ActiveSheet.Range("$A$1:$BN$5279")
rg.AutoFilter Field:=3, Criteria1:="<>"
Union(Columns(1), Columns(2), Columns(3)).Select
Selection.Copy
Sheets.Add After:=Sheets(Sheets.Count)
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Sheet2").Select
rg.AutoFilter Field:=3
rg.AutoFilter Field:=4, Criteria1:="<>"
Union(Columns(1), Columns(2), Columns(4)).Select
Selection.Copy
Sheets.Add After:=Sheets(Sheets.Count)
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Sheet2").Select
rg.AutoFilter Field:=4
rg.AutoFilter Field:=5, Criteria1:="<>"
Union(Columns(1), Columns(2), Columns(5)).Select
Selection.Copy
Sheets.Add After:=Sheets(Sheets.Count)
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Sheet2").Select
rg.AutoFilter Field:=5
End Sub
Thank you,
Ricky

Something like this should work for you. You can adjust the for loop as needed to loop through all the columns needed. This avoids the selection pieces, resets the filters when done with each iteration, and is easy to adjust for any changes in numbers of columns. It will also programmatically find the last row instead of the sheet range instead of hard coding it in.
Sub CopyPaste()
Dim rg As Range
Dim LastRow As Long
LastRow = Sheets("Sheet2").Range("A1").SpecialCells(xlCellTypeLastCell).Row
Set rg = Sheets("Sheet2").Range("A1:BN" & LastRow)
For i = 3 To 5
rg.AutoFilter Field:=i, Criteria1:="<>"
Union(Columns(1), Columns(2), Columns(i)).Copy
Sheets.Add After:=Sheets(Sheets.Count)
Sheets(Sheets.Count).Cells(1, 1).PasteSpecial Paste:=xlPasteValues
rg.AutoFilter
Next i
End Sub

There might be a better way to approach this but just to put it in a loop, try the below code:
Sub CopyPaste()
Dim rg As Range: Set rg = ActiveSheet.Range("$A$1:$BN$5279")
For iC = 3 To 64
rg.AutoFilter Field:=iC, Criteria1:="<>"
Union(Columns(1), Columns(2), Columns(3)).Select
Selection.Copy
Sheets.Add After:=Sheets(Sheets.Count)
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Sheet2").Select
rg.AutoFilter Field:=iC
Next
End Sub

Related

Excel VBA ClearContents error

Im trying to run macro which should clear contents from sheets AA, BB and CC and then move into sheet MENU but its highliting me an error on line 4. Please see the code below.
Sub clear_sheets()
Snames = Split(AA, BB, CC)
For Count = 0 To UBound(Snames)
Sheets(Snames(Count)).Range("A3:C3").End(xlDown).ClearContents
Next
Sheets("MENU").Select
Optimise (False)
End Sub
I got a little bit different approach posted on a different forum. Which would run more efficiently, I mean which one will will be putting less stress on a processing?
Sub clear_sheets()
Optimise (True)
Snames = Split("AA, BB, CC", ", ")
For count = 0 To UBound(Snames)
MyRange = Range("A3:C3", Range("A3:C3").End(xlDown)).Address
ThisWorkbook.Sheets(Snames(count)).Range(MyRange).ClearContents
Next
Sheets("MENU").Select
Optimise (False)
End Sub
Update
I understand this is not a code writing website but I would like to ask you if you could have a look at my code below.
Sub distribute_dsp_data_9()
Sheets("raw_data_1_9").Visible = True
Sheets("raw_data_1_9").Select
ActiveSheet.ListObjects("COMP_summ_9").Range.AutoFilter Field:=2, Criteria1 _
:="DTTD"
Range("C2").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Selection.Copy
Sheets("DTTD").Select
Range("A3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("raw_data_1_9").Select
ActiveSheet.ListObjects("COMP_summ_9").Range.AutoFilter Field:=2, Criteria1 _
:="FDTL"
Range("C2").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Selection.Copy
Sheets("FDTL").Select
Range("A3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("raw_data_1_9").Select
ActiveSheet.ListObjects("COMP_summ_9").Range.AutoFilter Field:=2, Criteria1 _
:="FULL"
Range("C2").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Selection.Copy
Sheets("FUL ON").Select
Range("A3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("raw_data_1_9").Select
ActiveSheet.ListObjects("COMP_summ_9").Range.AutoFilter Field:=2
Sheets("raw_data_1_9").Visible = False
End Sub
Try this. I've declared your variables properly and also assigned values to your array using Array() rather than Split() both are fine, but Array() is more flexible
Sub clear_sheets()
Dim sheetNames As Variant
Dim count As Integer
sheetNames = Array("AA", "BB", "CC")
For Count = 0 To UBound(Snames)
With Sheets(sheetNames(Count))
Range(.Range("A3"), .Range("C3").End(xlDown)).ClearContents
End With
Next
Sheets("MENU").Select
Optimise (False)
End Sub
Also, it's better to use ThisWorkbook.Sheets()rather than just Sheets() if your code refers to the same workbook you are writing your VBA in. If you don't do this then VBA will assume you are referring to the sheets in whichever workbook is active when you run the code - that's not usually a good thing.
Update
I've changed the code to delete what I think you might want deleted?
Use:
Snames = Split("AA", "BB", "CC")

Code Cleanup for Combining Sheets

I do not have much experience with VBA but I will start by explaining my situation.
I have a workbook with 341 sheets. Each sheet is identical in layout in that they occupy the space A1:J48. I need to combine all of these into one sheet called "COMBINATION". The information of relevance is from A10:J48. I also need to have the cells from A1:J9 as they are the title which is shared across all the sheets.
What I did was write a code that copies A1:J48 for Sheet1 (to get the title and info) and pastes it into "COMBINATION" with the paste special as text, then a code that goes to Sheet2 and copies from A10:J48 and pastes it in the first empty cell in column A of "COMBINATION".
This brings me to my problem. I have realized that there must be an easier way of doing this instead of copying the code 339 more times for each of the sheets.
See below the code. It does what I want correctly but as mentioned, I would like to find a way to not do this 339 more times...
Sheets("Sheet1").Select
Range("A1:J48").Select
Selection.Copy
Sheets("COMBINATION").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.Columns.AutoFit
Sheets("Sheet2").Select
Range("A10:J10").Select
Range("J10").Activate
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("COMBINATION").Select
NextFree = Range("A10:A" & Rows.Count).Cells.SpecialCells(xlCellTypeBlanks).Row
Range("A" & NextFree).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
I would use code like the following:
Dim ws As Worksheet
Dim r As Long
'Copy A1:J9 from the first sheet
Worksheets("Sheet1").Range("A1:J9").Copy
WorkSheets("COMBINATION").Range("A1").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, _
SkipBlanks:=False, _
Transpose:=False
'Now loop through every sheet (except "COMBINATION") copying cells A10:J48
r = 10 ' first sheet will be copied to row 10 in COMBINATION
For Each ws In Worksheets
If ws.Name <> "COMBINATION" Then
ws.Range("A10:J48").Copy
Worksheets("COMBINATION").Range("A" & r).PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, _
SkipBlanks:=False, _
Transpose:=False
'Set pointer ready for next sheet
r = r + 39
End If
Next
'Set column widths
Worksheets("COMBINATION").Columns.AutoFit
If your sheets don't always have data in all 39 rows (10 to 48), replace r = r + 39 with
r = Worksheets("COMBINATION").Range("A" & Worksheets("COMBINATION").Rows.Count).End(xlUp).Row + 1
Put the repeating code into a loop (untested):
Dim i as Integer
For i=2 to 341
Sheets(i).Select
Range("A10:J10").Select
Range("J10").Activate
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("COMBINATION").Select
NextFree = Range("A10:A" & Rows.Count).Cells.SpecialCells(xlCellTypeBlanks).Row
Range("A" & NextFree).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Next i
Range.PasteSpecial xlPasteValues is convenient but slow. It is much faster to define your 'Target' range to be the same size as your source range and do a direct assignment.
Sub CombineData()
Application.ScreenUpdating = False
Dim ws As Worksheet
Dim Target As Range
With Worksheets("COMBINATION")
.Range("A1:J9").Value = Worksheets("Sheet1").Range("A1:J49").Value
For Each ws In Worksheets
If ws.Name <> .Name Then
Set Target = .Range("A" & .Rows.Count).End(xlUp).Offset(1)
Target.Resize(39, 10).Value = ws.Range("A10:J48").Value
End If
Next
End With
Application.ScreenUpdating = True
End Sub

Copying Data from multiple sheets into a summary sheet within 1 workbook

I am new to Excel VBA and I am having trouble finding out how to create a macro that copies data from each sheet in a workbook and pastes the values into a summary sheet in the same workbook, appending the data below for each successive sheet.
I think my main problem is that the data to be copied does not start in A1. There are loads of answers where data does start in the first column but I can’t adapt it for data that doesn’t.
The data is in the same location and is the same size in each sheet, so I guess I can Dim a range for each and that I can probably manage.
I need to roll it out to multiple workbooks that have different numbers of sheets in each. Each sheet in each workbook is named in a generic sheet1, sheet2 etc way throughout.
I do have other sheets in the data that I won’t want copied but I have a piece of code that works by exception so as long as it loops through all sheets named generically that shouldn’t cause too much of a problem.
I’m really sorry if this has already been asked. I’ve been trying to search for a solution for weeks and have luckily learnt quite a few other useful bits along the way but I still can’t find a solution.
At the moment I am using this as a basis but obviously it’s very manual and I just can’t work out how to make it adaptable and not so clunky.
I will ultimately put in a loop but it’s just the basics of how to address the data that I am having the biggest problem with.
Thanks for reading!
Sheets("Sheet1").Select
Range("AD9").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("MASTER_QI_SUMMARY").Select
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Sheet2").Select
Range("AD9").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("MASTER_QI_SUMMARY").Select
Range("A288").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Sheet3").Select
Range("AD9").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("MASTER_QI_SUMMARY").Select
Range("A574").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Sheet4").Select
Range("AD9").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("MASTER_QI_SUMMARY").Select
Range("A860").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
I think this is what you're after.
Dim wsX As Worksheet, wsS As Worksheet
Dim strSheetsToExclude As String, strArr() As String
Set wsS = Worksheets("MASTER_QI_SUMMARY")
strSheetsToExclude = "Sheet4,Sheet5"
strArr = Split(strSheetsToExclude, ",")
For Each wsX In ActiveWorkbook.Worksheets
If Not wsX Is wsS _
And UBound(Filter(strArr, wsX.Name)) = -1 Then
wsX.Range("AD9").CurrentRegion.Copy
If IsEmpty(wsS.Range("A2")) Then
wsS.Range("A2").PasteSpecial xlPasteValues
Else
wsS.Range("A" & wsS.Range("A2").End(xlDown).Row + 1).PasteSpecial xlPasteValues
End If
End If
Next
Just add all sheets to be excluded to the comma separated string and may be change the range for pasting.
Here's something that might help you : you can concatenate strings.
Meaning Range("A" & 2+i*286)is a valid range for VBA. As well, Sheets("Sheet" & i)is a well-defined sheet.
If you loop on i, it should do what you want.
I would also advise you to search for posts adressing the use of Select and Copy if you feel the execution of the macro is too slow.

Calculate, Copy and Paste to a given value in VBA

I am fairly new to VBA. I am trying to automate iterations based on the no. of iterations specified in cell "E2". I want excel to Autofill down column A from cell "A4" to the value of cell "E2" e.g if E2 = 100, Excel will autofill series 1,2,3...down to 100.
I then want excel to continuosly calculate the value of cell "B2" then copy and paste each result down column B, starting at "B4" and stops at the value of iterations "E2"
I have the following code for the "Autofill"
Sub Monte3()
Dim srcRange As Range
Dim destRange As Range
Range("A5:A1000000").ClearContents
Set srcRange = ActiveSheet.Range("A4")
Set destRange = ActiveSheet.Range("A4:A103")
srcRange.AutoFill destRange, xlFillSeries
End Sub
I have recorded the following Macro for copy paste
Sub Macro10()
Application.CutCopyMode = False
Calculate
Range("B2").Select
Selection.Copy
Range("B4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Calculate
Range("B2").Select
Selection.Copy
Range("B5").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Calculate
Range("B2").Select
Selection.Copy
Range("B6").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Calculate
Range("B2").Select
Selection.Copy
Range("B7").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
What's the easiest way to do this?
A nice For Each Next Loop should work. See the code below. I took some guesses on some of the range references based on what you wrote above, but you should be able to modify it easily to suit your needs.
Sub Monte3()
Dim srcRange As Range, cel As Range
Dim wks As Worksheet
Set wks = Sheets("Sheet1") 'replace Sheet1 with your sheet name
With wks
.Range("B5:B1000000").ClearContents
Set srcRange = .Range("B4:B" & .Range("E2").Value + 4) 'will plug the number in from E2 as the row and adds 4 since you are starting at row 4
For Each cel In srcRange
With .Range("B2")
.Calculate
.Copy
End With
cel.PasteSpecial xlPasteValues
Next
End With
End Sub

Need to copy & paste from several different sheets into one sheet vertically

I'm attempting to write a macro that will copy a range of cells from a sheet, paste them into a sheet ("Bulksheet") that will contain all pasted data, then move on to the next tab after the first sheet. This needs to be done for 40+ tabs. Luckily, the data is in the same place in each tab, including the Bulksheet tab.
I can easily get this to apply to one tab, but returning to the first active tab and then moving on to the next is giving me no end of trouble.
Ex. code (shortened to the crucial bit). At the bottom where Next is would be where I need to move to the next sheet and do the same function, returning to "Bulksheet" and pasting in the next empty cell in column C.:
Sub
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
ws.Activate
Range("C100:F103").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Bulksheet").Select
Range("D1").End(xlDown).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Next
End Sub
Try looping through the sheets using an index value instead.
Sub
Dim i as integer
For i = 1 to worksheets.count
sheets(i).Activate
if activesheet.name <> "Bulksheet" then
Range("C100:F103").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Bulksheet").Select
Range("D1").End(xlDown).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
end if
Next
End Sub
Try this:
Sub CopyToBulksheet()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> "Bulksheet" Then
ws.Activate
Range("C1:F10").Copy
Sheets("Bulksheet").Select
Range("D" & Cells.Rows.Count).End(xlUp).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End If
Next
End Sub