How to use VBA to loop through cutting a range of cells and pasting into next row - excel

The purpose of this VBA is to make a single long row of values (tens of thousands) into something more readable by keeping each row limited to 22 values. I have a manual version of this which works for 200 rows, but am hoping to use looping to save myself time and hopefully improve performance.
Example:
I have values in A1:ZZ1 and am trying to cut W1:ZZ1 and paste into A2, then cut W2:ZD2 and paste into A3 until there are no values left to cut and paste.
I'm using Excel 2010.
Sub InsertScript22perLine()
'Turn off screen updating to speed up macro
Application.ScreenUpdating = False
Range("W1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Cut
Selection.End(xlToLeft).Select
Range("A2").Select
ActiveSheet.Paste
Range("W2").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Cut
Selection.End(xlToLeft).Select
Range("A3").Select
ActiveSheet.Paste
'Turn screen updating back on
Application.ScreenUpdating = True
End Sub

Sub InsertScript22perLine()
Application.ScreenUpdating = False
' Starting column for input data
Dim sStartCol As String
Dim lStartCol As Long
' Count of columns
Dim lColCount As Long
' Count of columns of data for output
Dim lRowLen As Long
lRowLen = 22
Dim lRow As Long
lRow = 2
sStartCol = "W"
lStartCol = Range(sStartCol & 1).Column
' Get the column count
lColCount = Cells(1, Columns.Count).End(xlToLeft).Column
For a = lStartCol To lColCount Step lRowLen
Range(Cells(lRow, 1), Cells(lRow, lRowLen)).Value = Range(Cells(1, a), Cells(1, a + lRowLen)).Value
lRow = lRow + 1
Next
Application.ScreenUpdating = True
End Sub

Related

Cut a table halfway in Excel

My sheet contains of cars that are placed at a certain location and need to be checked. This list is made twice a day and sometimes contains of 10 rows, sometimes 14, sometimes 12 etc. Now I would like to cut half of the rows and place it next to the other rows (in this case paste it in cell E). I would like to automate this process so in the VBA should be:
Count number of rows (X)
Cut the rows from X/2 to X
Paste the data in cell E1
I found this function which returns the middle cell. However, I would like to put this together in a sub.
Function Middle(r As Range) As Variant
Dim i As Long, j As Long
If r.Columns.Count > 1 Then
Middle = [#N/A]
Exit Function
End If
i = r.Row
j = r.Rows.Count
Middle = Cells(i + (j - 1) / 2, r.Column).Address
End Function
Sub cutting()
Range("Middle:C" & Range("A" & Rows.Count).End(xlUp).Row).Select
Selection.Cut
Range("E2").Select
ActiveSheet.Paste
Range("A1:C1").Select
Selection.Copy
Range("E1").Select
ActiveSheet.Paste
Cells.Select
Cells.EntireColumn.AutoFit
Range("E8").Select
End Sub
Before
After
You don't need to select the data to work with it.
Try:
Sub Test()
Dim lLastRow As Long
Dim lCutRow As Long
With ThisWorkbook.Worksheets("Sheet1") 'Change Sheet1 to the name of your sheet.
lLastRow = .Cells(.Rows.Count, 1).End(xlUp).Row 'Find last row in column A.
If lLastRow > 1 Then
lCutRow = (lLastRow / 2) + 1
.Range(.Cells(lCutRow, 1), .Cells(lLastRow, 3)).Cut Destination:=.Cells(1, 5) 'Paste to row 1, column 5 (E1).
End If
End With
End Sub

VBA Copy Data goes wrong

Sub CopyTMR()
Dim sheet_number As Integer
Dim counter As Integer
Dim last_row As Integer
Dim wb As Workbook
Dim tmr As Worksheet
Set wb = ActiveWorkbook
Set tmr = wb.Sheets("Team Member Rules")
' Counting the sheets number
sheet_number = Worksheets.Count
'MsgBox sheet_number
'MsgBox "Before you continue, make sure all sheets has the Header at the first row"
' Clearing existing TMR in the sheet4
tmr.Select
ActiveSheet.UsedRange.Offset(1, 0).Clear
' If there more than 4 sheets, then we copy from the 5th until the last tab to 4th (TMR)
If sheet_number > 4 Then
' Loop to copy any sheet after TMR tab to the TMR Tab
For counter = 5 To sheet_number
' Selecting the corresponding tab to copy
Worksheets(counter).Select ActiveSheet.Range("A1:A1").Select
ActiveSheet.Range(Selection, Selection.End(xlToRight)).Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
' The Header is not copy
Selection.Offset(1, 0).Copy
' Moving back to TMR Tab to paste data
tmr.Select
' Selecting the last row of TMR bab before pasting data after it
last_row = ActiveSheet.Cells(Rows.Count, 2).End(xlUp).Row
ActiveSheet.Range("A" & last_row + 1).Select
ActiveSheet.Paste
Next
End If
' Best fit
tmr.Select
ActiveSheet.UsedRange.Select
Selection.AutoFilter
Application.CutCopyMode = False
Selection.ColumnWidth = 100
Selection.Columns.AutoFit
Selection.Rows.AutoFit
ActiveSheet.Range("A2").Select
ActiveWindow.FreezePanes = True End Sub
Hi All!
I am having some issue with the code above.
For some reason it works fine for a while and then stop with "run-time error 1004".
What I am trying to do is to copy the content "without the header" of all the tab after the 4th and paste them into the 4th tab.
Any tip or idea could help.
Thanks,
Try using .CurrentRegion with .Offset. A variant array will assist in avoiding the clipboard altogether.
Sub CopyTMR()
di w as long, arr as variant
for w = 5 to worksheets.count
with worksheets(w)
arr = .cells(1,1).currentregion.offset(1,0).value
end with
with worksheets(4)
.cells(.rows.count,"B").end(xlup).offset(1, -1).resize(ubound(arr, 1), ubound(arr, 2)) = arr
end with
next w
end sub

excel vba showing incorrect data after certain manipulations

Sequence of events which I am trying to achieve:
1) I have data on Sheet1
2) I filter the data on Sheet1 according to a certain criteria and then copy the data to another Sheet say "Difference". The data has around 8 lines.
3) I then insert 11 lines between the data on sheet "Difference" after every 2 lines.
4) Next I insert 4 columns before the first column
5) I then insert the column header for the first 4 inserted column and row headers till the UsedRange.
6) After that I am doing certain less intensive calculations on the data such as comparing the values and looking up data from another workbook.
All this is in a macro on click of a button.
While clicking the button what happens is that sometimes I get the rows and columns in a sequence as expected and actually most of the times after the first 4 columns the rows come in a zig zag manner i.e. sometimes they would comes 5 - 6 columns after the first 4 columns and on other runs of a macro the rows would come after 50 lines or so.
I investigated my code but couldn't find any reason why this is happening. Also this happens intermittently. As I mentioned sometimes the result comes fine and most of the times the result (rows and columns) come in a zig zag manner.
Why is macro doing this? I am really having a hard time thinking about it? I have no answer. It seems so illogical.
I could post my code but it's too big. Please let me know which portion of the code should I post.
Please do suggest. Having a really hard time.
I am posting my code snippet below:
Private Sub CommandButton1_Click()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False
Dim wb As Workbook
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim sh3 As Worksheet
Dim ws As Worksheet
Dim i As Long
Set wb = GetObject(ActiveWorkbook.Path & "\ReconUtility_Enhanced.xlsm")
Set sh1 = wb.Sheets("Sheet1")
Set sh2 = wb.Sheets("Sheet2")
MsgBox sh2.UsedRange.Rows.count
For i = 1 To sh2.UsedRange.Rows.count
sh1.Activate
ActiveSheet.UsedRange.Select
Selection.AutoFilter
sh1.Range("E1").AutoFilter Field:=5, Criteria1:=sh2.Cells(i, 1).Value
Selection.Copy
With ThisWorkbook
Set ws = .Sheets.Add(After:=.Sheets(.Sheets.count))
ws.Name = sh2.Cells(i, 2).Value
End With
Sheets(sh2.Cells(i, 2).Value).Select
'Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
ActiveSheet.UsedRange.Columns.AutoFit
Next i
sh1.Activate
ActiveSheet.UsedRange.Select
Selection.AutoFilter
sh1.Range("E1").AutoFilter Field:=5, Criteria1:="Field Difference"
Selection.Copy
Sheets("Field Difference").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
ActiveSheet.UsedRange.Columns.AutoFit
MsgBox "Field Difference Copy completd"
' Step 2. Insert 11 lines and Insert 4 columns for analysis
Set sh3 = wb.Sheets("Field Difference")
Dim x As Long
Dim j As Long
Dim i1 As Long
Dim fieldRows As Long
j = 1
fieldRows = sh3.UsedRange.Rows.count
Dim rowsAfterInsertingLines As Long
rowsAfterInsertingLines = fieldRows / 2
Const count = 11
For i1 = 2 To fieldRows
If i1 Mod 2 = 1 Then
For x = 1 To count
sh3.Rows(i1 + j).Insert Shift:=xlDown
j = j + 1
Next
End If
Next i1
MsgBox "Inserted Lines Done"
' Inserting 4 columns before the first column
sh3.Range("A:D").EntireColumn.Insert Shift:=xlToRight
sh3.Range("A1").Value = "Data Source Name"
sh3.Range("B1").Value = "Final Status"
sh3.Range("C1").Value = "UserName"
sh3.Range("D1").Value = "Ownership"
MsgBox "Columns Inserted"
' Now a Loop to insert the values - (CMRS, DTCC-US, Difference, 2 Eye Check, 4 Eye Check)
Dim myModifiedArray() As Variant
myModifiedArray = Array("CMRS", "DTCC-US", "Difference", "Sapient Comments (History)", "Last Sapient Comment / 2 Eye Analysis", "4 Eye Analysis", "4 Eye Comments", "Last Comment made by (Sapient)", "Date of Last Comment (Sapient)", "NWM Comment (History)", "Last NWM Commnent", "Last Comment made by (NWM)", "Date of Last Comment (NWM)")
Dim rCount As Long
rCount = 2
Dim iCount As Long
Dim jCount As Long
For iCount = 1 To rowsAfterInsertingLines
For jCount = LBound(myModifiedArray) To UBound(myModifiedArray)
sh3.Cells(rCount, 1).Value = myModifiedArray(jCount)
rCount = rCount + 1
Next jCount
Next iCount
MsgBox "Row headers inserted"
End Sub

Copy paste Excel data between two sheets using a macro

I have 2 sheets, sheet1 and sheet2. From sheet1 data, I have to copy data and paste it into sheet2, then again from sheet1 I have to copy another different set of data and paste it into sheet2 last line, where I pasted data 1st time.
Sub Copy_chains_to_other_sheet()
ActiveSheet.Range("$A$1").AutoFilter Field:=8, Criteria1:="<>1", _
Operator:=xlAnd
ActiveSheet.Range("$A$1:$I$681").AutoFilter Field:=1, Criteria1:="=*antaris*" _
, Operator:=xlAnd
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
ActiveSheet.Next.Select
ActiveSheet.Paste
ActiveSheet.Range("$A$1").AutoFilter Field:=1
End Sub
This is the macro I wrote, but I don't know how to proceed. Because one time I have 5 rows of data that time I need to copy data from sheet1 and paste in sheet2 and with next set of data I need to paste it in 6th row, but another time I have 8 row of data that time I need to paste the next set of data from 9the row onwards, so how to deal with this.
If I understand correctly you want to copy the results of successive autofiltered data from Sheet1 to a continuous "list" in Sheet2. If this is so then perhaps try the following to get you going. You will need to alter the variables/names to suit your requirement, I have made some assumptions.
Option Explicit
Sub copyAFs()
Dim wsONE As Worksheet, wsTWO As Worksheet
Dim ONEstrow As Long, ONEendrow As Long, ONEstcol As Long, ONEendcol As Long
Dim TWOstrow As Long, TWOnextrow As Long, TWOstcol As Long
Dim crit1col As Long, crit2col As Long
Dim crit1 As String, crit2 As String
Set wsONE = Sheets("Sheet1")
Set wsTWO = Sheets("Sheet2")
ONEstrow = 1
ONEstcol = 1
ONEendcol = 10
TWOstrow = 1
TWOstcol = 1
crit1 = "antaris"
crit2 = "1"
crit1col = 1
crit2col = 8
With wsTWO
TWOnextrow = .Cells(.Rows.Count, TWOstcol).End(xlUp).Row + 1
End With
'clear autofilter
wsONE.AutoFilterMode = False
'apply autofilter
With wsONE
ONEendrow = Cells(Rows.Count, ONEstcol).End(xlUp).Row + 1
With .Range(.Cells(ONEstrow, ONEstcol), .Cells(ONEendrow, ONEendcol))
'set autofilter
.AutoFilter Field:=crit1col, Criteria1:=crit1
.AutoFilter Field:=crit2col, Criteria1:=crit2
End With
End With
'copy filtered range without header
With wsTWO
wsONE.AutoFilter.Range.Offset(1, 0).Copy Destination:=.Range(.Cells(TWOnextrow, TWOstcol), .Cells(TWOnextrow, TWOstcol))
End With
'clear autofilter
wsONE.AutoFilterMode = False
End Sub

How to select an entire range in a sheet, and in another sheet keep pasting two columns from the range with a gap of 2 columns

I have used the following code, but it is very specific:
Sub Macro 6 ()
Windows("Projects_Europe2014 work.xlsx").Activate
Range("B12:C16").Select
Selection.Copy
Windows("test1.xlsx").Activate
ActiveSheet.Paste
Windows("Projects_Europe2014 work.xlsx").Activate
Range("D12:E16").Select
Application.CutCopyMode = False
Selection.Copy
Windows("test1.xlsx").Activate
Range("F3").Select
ActiveSheet.Paste
Windows("Projects_Europe2014 work.xlsx").Activate
Range("F12:G16").Select
Application.CutCopyMode = False
Selection.Copy
Windows("test1.xlsx").Activate
Range("J3").Select
ActiveSheet.Paste
End Code
Is there a way, i can keep increasing the range, without manually entering the cde?
Does the worksheet you are copying to contains preexisting data? If not you could just copy your whole range and then insert empty columns where need be - after every two consecutive columns involving data
You can try the below and see if it fits - you need to fill in your references first where commented. "RANGE_REF" is the starting point cell where pasting of the original range should occur
Sub pasteandinsert()
Dim r As Range
Dim r2 As Range
'HERE
Set r = Workbooks("Projects_Europe2014 work.xlsx").Worksheets("YOUR_WS").Range("YOUR_RANGE")
r.Copy
'HERE
With Workbooks("test1.xlsx").Worksheets("YOUR_WS2")
.Activate
'HERE
.Range("RANGE_REF").Select
.Paste
End With
Application.CutCopyMode = False
'HERE
Set r2 = Range("RANGE_REF").Resize(r.Rows.count, r.Columns.count)
i = 3
colcount = r2.Columns.count
Do While i <= colcount
r2.Columns(i).Insert shift:=xlShiftToRight
r2.Columns(i).Insert shift:=xlShiftToRight
i = i + 4
colcount = colcount + 2
Loop
End Sub

Resources