Problems with pasting while shifting down cells - excel

Hi I am trying to copy info from a workbook into another workbook and paste while shifting cells down.
My problem is that is not pasting the information at all. The code does everything is supposed to except for pasting the rows.
Sub filter_copy_paste()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim whatToFind As String
Dim foundTwo As Range
Dim newSelectionRange As Range
Dim rowSelectionRange As Range
Dim Found_Row As Long
Dim num As Integer
'
Sheets("Sheet1").Select
whatToFind = "Mean"
Set foundTwo = Cells.Find(What:=whatToFind, After:=ActiveCell, LookIn:=xlFormulas2, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
'
Found_Row = foundTwo.row
With Sheets("Main").Range("A12:S12").CurrentRegion
.AutoFilter Field:=19, Criteria1:="Yes"
.SpecialCells(xlCellTypeVisible).EntireRow.Copy
'_
' Destination:=Sheets("Sheet1").Range("A1")
'
' I added the following line to insert selection and shift down in Cells above mean
'
Set rowSelectionRange = Rows(Found_Row - 1).Resize(1)
rowSelectionRange.Select
Selection.Insert Shift:=xlDown
End With
'
'Following is added to clean up my previous worksheet
'
Sheets("Main").Select
If ActiveSheet.FilterMode = True Then
ActiveSheet.ShowAllData
End If
Sheets("Main").Select
Rows("3:11").Select
Range("A11").Activate
Selection.EntireRow.Hidden = True
Application.CutCopyMode = False
Sheets("Sheet1").Select
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
I am expecting the copied rows to be inserted in the range above Mean

This should do what you need:
Sub filter_copy_paste()
Const FIND_THIS As String = "mean" 'use const for fixed values
Dim f As Range, numRows As Long, wsSrc As Worksheet, wsDest As Worksheet
Set wsSrc = ThisWorkbook.Worksheets("Main") 'source table
Set wsDest = ThisWorkbook.Worksheets("Sheet2") 'copy to here
Set f = wsDest.Cells.Find(What:=FIND_THIS, LookIn:=xlFormulas2, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If f Is Nothing Then
MsgBox "'" & FIND_THIS & "' not found on " & wsDest.Name, vbExclamation
Exit Sub
End If
With wsSrc.Range("A12:S12").CurrentRegion
Debug.Print "Data", .Address()
.AutoFilter Field:=19, Criteria1:="Yes"
'how many rows will be copied?
numRows = .Columns(1).SpecialCells(xlCellTypeVisible).Count
f.Resize(numRows).EntireRow.Insert shift:=xlDown 'insert the rows
'copy visible rows
.SpecialCells(xlCellTypeVisible).Copy wsDest.Cells(f.Row - numRows, "A")
End With
wsSrc.ShowAllData
End Sub

Insert Filtered Rows
Sub InsertFilteredRows()
Application.ScreenUpdating = False
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' Source
Dim sws As Worksheet: Set sws = wb.Sheets("Main")
If sws.FilterMode Then sws.ShowAllData
If sws.AutoFilterMode Then sws.AutoFilterMode = False
Dim srg As Range: Set srg = sws.Range("A12").CurrentRegion
srg.AutoFilter Field:=19, Criteria1:="Yes"
Dim svrg As Range: Set svrg = srg.SpecialCells(xlCellTypeVisible)
sws.AutoFilterMode = False
Dim sarg As Range, srCount As Long
For Each sarg In svrg.Areas: srCount = srCount + sarg.Rows.Count: Next sarg
'Debug.Print srg.Address, svrg.Address, srCount
' Destination
Dim dws As Worksheet: Set dws = wb.Sheets("Sheet1")
If dws.FilterMode Then dws.ShowAllData
Dim durg As Range: Set durg = dws.UsedRange
Dim dlCell As Range: Set dlCell = durg.Cells(durg.Cells.CountLarge)
' Starting with the first cell of the used range searching by rows,
' attempt to find the first cell that contains the search string.
' The search is by default case-insensitive ('A=a').
Dim dfCell As Range: Set dfCell = dws.Cells.Find( _
What:="Mean", After:=dlCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows) ' the rest are default parameters
If dfCell Is Nothing Then Exit Sub ' string not found
Dim dirg As Range: Set dirg = Intersect(durg, dfCell.EntireRow) _
.Resize(srCount) ' your code additionally suggests '.Offset(-1)' !?
'Debug.Print svrg.Address, dfCell.Address, dirg.Address
' Insert and copy.
dirg.Insert Shift:=xlShiftDown
' Cannot determine the 'CopyOrigin' parameter without seeing the data.
' Copy.
svrg.Copy dirg.Columns(1).Offset(-srCount)
' Clean up!?
sws.Rows("3:11").Hidden = True
If Not wb Is ActiveWorkbook Then wb.Activate
dws.Select
Application.ScreenUpdating = True
' Inform.
MsgBox "Filtered rows inserted.", vbInformation
End Sub

Related

How can I select only some specific Data when Using Last Row?

I would Like to only copy the information in Range A2:P13. This Data gets spit out In different rows from time to time, and some times additional data in some of the columns gets added. I wrote a script that allows me to Select and copy everything from the last row to an x number rows up. Problem is that this amount of rows can be variable And there is way more data above the shared image (its clutter). Is there a way to modify my script so it counts down to the last row and once it hits "n" or "Calibration" it selects 8 rows above it?
Thanks in advance :)
enter image description here
Option Explicit
Sub Import_File()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
Dim myValue As Variant
Dim Sht2 As Worksheet
Dim lastRow As Long
Dim Last24Rows As Range
Application.ScreenUpdating = False
Application.DisplayAlerts = False
myValue = InputBox("Please Input Run Number")
FileToOpen = Application.GetOpenFilename("Excel Files (*.xl*),*.xl*", , "Choose File", "Open", False)
If FileToOpen = False Then
Exit Sub
Else
Set OpenBook = Workbooks.Open(FileToOpen)
Set Sht2 = OpenBook.Sheets("Sheet1")
End If
lastRow = Sht2.Range("H" & Sht2.Rows.Count).End(xlUp).row
Set Last4Rows = Sht2.Range("A" & lastRow - 4 & ":AZ" & lastRow)
Last4Rows.Copy
ThisWorkbook.Worksheets(myValue).Range("A1").PasteSpecial xlPasteValues
OpenBook.Close False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
I tried Including this
' Dim wb As Workbook
' Dim ws As Worksheet
' Dim FoundCell As Range
' Set wb = ActiveWorkbook
' Set ws = ActiveSheet
'
' Const WHAT_TO_FIND As String = "Calibration"
'
' Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
' If Not FoundCell Is Nothing Then
' MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
' Else
' MsgBox (WHAT_TO_FIND & " not found")
' End If
But it did not work
This will select 8 rows above wherever it finds "calibration". The -8 makes it move up 8 rows, and then the resize(8) resizes it to include the 8 rows below. It will create an error if it can't find "calibration", it would be easy to change that to send a text box instead.
Sub Macro1()
'
' Macro1 Macro
'
'
Dim found As Range
Dim SelectionRange As Range
Dim what_to_find As String
Dim FoundRow As Long
what_to_find = "calibration"
Set found = Cells.Find(What:=what_to_find, After:=ActiveCell, LookIn:=xlFormulas2, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
FoundRow = found.row
Set SelectionRange = Rows(FoundRow - 8).Resize(8)
SelectionRange.Select
End Sub

How can i fix my loop, so that all matches are found?

My code does this. It search for the word: "KENNFELD" in my current sheet. Then it sets the variable label to the cell that is one to the right of "KENNFELD". Now i want to find matches of the variable label in my whole workbook, excluding the one i am currently on, because that is where i got them in the first place.
The problem is, that this works for the first label that is found, but not for the other ones, and i know for a fact that there has to be 6 more matches. I believe my problem is within the loops, but i can't locate it. Anybody has an idea?
Dim helpc As Range
Dim label As Range
Dim firstAddress As String
Dim foundCell As Range
With Sheets("C7BB2HD3IINA_NRM_X302")
Set helpc = .Cells.Find(what:="KENNFELD", MatchCase:=True)
Set label = helpc.Offset(0, 1) ' assign the value of the cell to label
If Not helpc Is Nothing Then
firstAddress = helpc.Address
Do
For Each ws In ThisWorkbook.Sheets
If ws.Name <> "C7BB2HD3IINA_NRM_X302" Then
Set foundCell = ws.Cells.Find(what:=label.Value, LookIn:=xlValues, LookAt:=xlWhole, _
MatchCase:=True)
If Not foundCell Is Nothing Then
MsgBox "Label " & label.Value & " found on sheet " & ws.Name
End If
End If
Next ws
Set helpc = .Cells.FindNext(helpc)
Loop While Not helpc Is Nothing And helpc.Address <> firstAddress
End If
End With
Find Found Values
Option Explicit
Sub FindLabels()
Const DST_NAME As String = "C7BB2HD3IINA_NRM_X302"
Const DST_SEARCH_STRING As String = "KENNFELD"
Const DST_COLUMN_OFFSET As Long = 1
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim dws As Worksheet: Set dws = wb.Sheets(DST_NAME)
If dws.AutoFilterMode Then dws.AutoFilterMode = False
Dim drg As Range: Set drg = dws.UsedRange
Dim dlCell As Range
Set dlCell = drg.Cells(drg.Rows.Count, drg.Columns.Count)
Dim dCell As Range: Set dCell = drg.Find( _
DST_SEARCH_STRING, dlCell, xlFormulas, xlWhole, xlByRows, , True)
If dCell Is Nothing Then
MsgBox "Could not find """ & DST_SEARCH_STRING & """ in worksheet """ _
& DST_NAME & """ of workbook """ & wb.Name & """.", vbCritical
Exit Sub
End If
Dim durg As Range: Set durg = dCell.Offset(, DST_COLUMN_OFFSET)
Dim dFirstAddress As String: dFirstAddress = dCell.Address
Do
Set durg = Union(durg, dCell.Offset(, DST_COLUMN_OFFSET))
Set dCell = drg.FindNext(dCell)
Loop Until dCell.Address = dFirstAddress
Dim sws As Worksheet, srg As Range, slCell As Range, sCell As Range
Dim sFirstAddress As String, Label
For Each sws In wb.Worksheets
If StrComp(sws.Name, DST_NAME, vbTextCompare) <> 0 Then
If sws.AutoFilterMode Then sws.AutoFilterMode = False
Set srg = sws.UsedRange
Set slCell = srg.Cells(srg.Rows.Count, srg.Columns.Count)
For Each dCell In durg.Cells
Label = dCell.Value
Set sCell = srg.Find( _
Label, slCell, xlFormulas, xlWhole, xlByRows, , True)
If Not sCell Is Nothing Then ' label found in current worksheet
sFirstAddress = sCell.Address
Do
MsgBox "Label """ & CStr(Label) & """ found in Cell " _
& """" & sCell.Address(0, 0) & """ of worksheet " _
& """" & sws.Name & """.", vbInformation
Set sCell = srg.FindNext(sCell)
Loop Until sCell.Address = sFirstAddress
'Else ' label not found in current worksheet; do nothing
End If
Next dCell
'Else ' it's the destination worksheet; do nothing
End If
Next sws
End Sub

Copy and paste to another sheet in the next empty row

I'm a newbie in VBA, so sorry for any stupid questions...
I have a huge number of data (about 15k rows) in which I need to find specific key word and if found, copy the row and 3 next rows.
This is what I have till now:
Sub Kopiowanie()
Dim Cell As Range
Worksheets("TEXT").Activate
ActiveSheet.Columns("A:A").Select
Set Cell = Selection.Find(What:="Teilschulderlass", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Cell Is Nothing Then
'do it something
MsgBox ("Nie ma!")
Else
'do it another thing
MsgBox ("Jest!")
Cell.Select
ActiveCell.Resize(4, 1).Copy
Sheets("WYNIK").Range("A1").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
End If
End Sub
The problem is, that is copying only one result and I need to have all of them.
I know that I'm lacking a loop macro, however I got stuck :(
Could someone help me with this task? Thanks in advance!
Copy Multiple Matches Using the Find Method
Sub Kopiowanie()
Const ROWS_COUNT As Long = 4
Const SEARCH_STRING As String = "Teilschulderlass"
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim sws As Worksheet: Set sws = wb.Sheets("TEXT")
Dim srg As Range
Set srg = sws.Range("A1", sws.Cells(sws.Rows.Count, "A").End(xlUp))
Dim dws As Worksheet: Set dws = wb.Sheets("WYNIK")
Dim dfCell As Range: Set dfCell = dws.Range("A1")
Dim dcrg As Range: Set dcrg = dfCell.Resize(ROWS_COUNT)
Dim sCell As Range: Set sCell = srg.Find(What:=SEARCH_STRING, _
After:=srg.Cells(srg.Cells.Count), LookIn:=xlFormulas, LookAt:=xlPart)
If sCell Is Nothing Then
MsgBox "The string '" & SEARCH_STRING & "' was not found in '" _
& srg.Address(0, 0) & "'.", vbExclamation
Exit Sub
End If
Dim FirstAddress As String: FirstAddress = sCell.Address
Dim scrg As Range
Do
Set scrg = sCell.Resize(ROWS_COUNT)
dcrg.Value = scrg.Value
Set dcrg = dcrg.Offset(ROWS_COUNT)
Set sCell = srg.FindNext(After:=sCell)
Loop Until sCell.Address = FirstAddress
MsgBox "Jest!", vbInformation
End Sub

Copy range of cells from one workbook to another

How can a range of cells be copied from one workbook to another? The code below does not work. I believe there is something wrong with how the range of cells are selected: sht1.Range("A1:D1").Select
Sub ImportData()
Dim wkb1 As Workbook
Dim sht1 As Worksheet
Dim wkb2 As Workbook
Dim sht2 As Worksheet
Application.ScreenUpdating = False
Set wkb1 = ThisWorkbook
Set wkb2 = Workbooks.Open("C:\Users\Temp\Desktop\MyExcelSheet.xlsm")
Set sht1 = wkb1.Sheets("Data")
Set sht2 = wkb2.Sheets("Summary")
'Function to clear the existing data. Doesn't work.
sht1.Range("A1:D1").Select
sht1.Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
' Copies data from the "Summary" sheet.
sht2.Range("O6:P102").Copy
sht2.Range("O6").Select
sht2.Range(Selection, Selection.End(xlToRight)).Select
sht2.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy ' Copies all of the highlighted cells.
sht1.Range("A1").PasteSpecial xlPasteValues
Application.CutCopyMode = False
wkb2.Close True
Application.ScreenUpdating = True
MsgBox "Complete"
End Sub
Replace:
sht1.Range("A1:D1").Select
sht1.Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
With
sht1.Range("A1:D" & Range("D1").End(xlDown).Row).Clear
Unless you specifically want to manually highlight the cells and then run the macro, this solution works.
This replacement code will now highlight every cell between "A1:D1" however, XlDown is only applied on the column "D".
Copy the Values of a Range
Option Explicit
Sub ImportData()
' Source (open, read from & close)
Const sFilePath As String = "C:\Users\Temp\Desktop\MyExcelSheet.xlsm"
Const sName As String = "Summary"
Const sFirstRowAddress As String = "O6:R6"
' Destination (write to & save)
Const dName As String = "Data"
Const dFirstCellAddress As String = "A1"
' Source
Dim swb As Workbook: Set swb = Workbooks.Open(sFilePath)
Dim sws As Worksheet: Set sws = swb.Worksheets(sName)
Dim srg As Range
With sws.Range(sFirstRowAddress)
Dim lCell As Range: Set lCell = .Resize(sws.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , xlByRows, xlPrevious)
If lCell Is Nothing Then
MsgBox "No data found.", vbCritical
Exit Sub
End If
Set srg = .Resize(lCell.Row - .Row + 1)
End With
' Destination
Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code
Dim dws As Worksheet: Set dws = dwb.Worksheets(dName)
' Clear & copy.
With dws.Range(dFirstCellAddress).Resize(, srg.Columns.Count)
' Clear previous data.
.Resize(dws.Rows.Count - .Row + 1).Clear
' Copy values by assignment.
.Resize(srg.Rows.Count).Value = srg.Value
End With
' Save & close.
swb.Close SaveChanges:=False
'dwb.Save
' Inform.
MsgBox "Values copied.", vbInformation
End Sub

VBA Excel - Delete - Cannot use that command on overlapping selections

I am trying to apply filter to the data and copy the filtered data to an other sheet and delete the filtered rows in base sheet.
I am facing error as 'cannot use the command on overlapping selection'
When I try to delete the filtered rows in base sheet using
specialcells(xlcelltypevisible).entirerow.delete
Sheets("analysis").select
Sourcecol=1
VCurrLength = cells(rows.count, sourcecol).end(clip).row
Activesheet.range("$A$1:$W$"& VCurrLength).autofilter field:=7, criteria1:= "ZP"
Range ("A1").select
Selection.end(xldown).select
If selection.row<1000000 then
Range("A2:w"& VCurrLength).specialcells(xlcelltypevisible).copy
Sheets("temp").select
Activesheet.paste
Sheets("analysis").select
Range("A2:w"& VCurrLength).specialcells(xlcelltypevisible).select
Selection.entirerow.delete
Endif
Backup Data
Option Explicit
Sub backupData()
Dim Success As Boolean
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim sws As Worksheet: Set sws = wb.Worksheets("analysis")
Dim sLR As Long: sLR = sws.Cells(sws.Rows.Count, "A").End(xlUp).Row
Dim srg As Range: Set srg = sws.Range("A1:W" & sLR)
Application.ScreenUpdating = False
If sws.AutoFilterMode Then
sws.AutoFilterMode = False
End If
srg.AutoFilter field:=7, Criteria1:="ZP"
If WorksheetFunction.Subtotal(103, srg.Cells.Resize(, 1)) > 1 Then
Dim dws As Worksheet: Set dws = wb.Worksheets("temp")
Dim dcell As Range
Set dcell = dws.Cells(dws.Rows.Count, "A").End(xlUp).Offset(1)
Dim frg As Range
Set frg = srg.Resize(srg.Rows.Count - 1).Offset(1) _
.SpecialCells(xlCellTypeVisible)
frg.Copy dcell
frg.EntireRow.Delete
If Not sws Is ActiveSheet Then
sws.Activate
End If
srg.Cells(1).Select
Success = True
End If
sws.AutoFilterMode = False
Application.ScreenUpdating = True
If Success Then
MsgBox "Data updated.", vbInformation, "Success"
Else
MsgBox "No updates available.", vbExclamation, "Nope"
End If
End Sub

Resources