Copy and paste to another sheet in the next empty row - excel

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

Related

Problems with pasting while shifting down cells

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

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

How can I make my copy and pasting work as intended

Hello all I did a macro in VBA that should check column D for the first empty cell then paste on that row but on column C, and when adding new info in the table it should take the first empty cell again, but it is replacing data, I don't check column C for first row because I have an filled cell midway, and if data were to replace that cell it should add a new row and avoid that.
`Sub CopyPasteToAnotherSheet()
Dim sourceRange As Range
Dim targetRange As Range
Dim lastRow As Long
Dim firstEmptyRow As Long
Set sourceRange = Selection
Set targetRange = Sheets("PARKING").Range("D18")
lastRow = targetRange.End(xlDown).Row
firstEmptyRow = Sheets("PARKING").Range("D" & lastRow).End(xlUp).Row + 1
If lastRow = targetRange.Row Then
targetRange.EntireRow.Insert
End If
If Sheets("PARKING").Range("C" & firstEmptyRow).Value <> "" Then
firstEmptyRow = firstEmptyRow + 1
End If
Set targetRange = Sheets("PARKING").Range("C" & firstEmptyRow)
sourceRange.Copy
targetRange.PasteSpecial xlPasteValues
End Sub
`
I have tried to work with different search ranges but it keeps overwriting data.
also if it would keep numbering the newly added rows when adding new data it would be great I am clueless on how I should do that
Append Values
Sub AppendValues()
Const PROC_TITLE As String = "Append Values"
Const DST_NAME As String = "PARKING"
Const DST_FIRST_CELL As String = "C18"
If Selection Is Nothing Then Exit Sub ' no visible workbooks open
If Not TypeOf Selection Is Range Then Exit Sub ' not a range
Dim srg As Range: Set srg = Selection
Dim sws As Worksheet: Set sws = srg.Worksheet
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
If Not sws.Parent Is wb Then Exit Sub ' not in this workbook
Dim dws As Worksheet: Set dws = wb.Sheets(DST_NAME)
If sws Is dws Then Exit Sub ' src. and dst. are the same worksheet
If dws.FilterMode Then dws.ShowAllData ' '.Find' will fail if 'dws' filtered
Dim dfCell As Range: Set dfCell = dws.Range(DST_FIRST_CELL)
Dim dlCell As Range
Set dlCell = dws.UsedRange.Find("*", , xlFormulas, , xlByRows, xlPrevious)
If Not dlCell Is Nothing Then
Set dfCell = dfCell.Offset(dlCell.Row - dfCell.Row + 1)
End If
Dim sarg As Range
For Each sarg In srg.Areas
dfCell.Resize(sarg.Rows.Count, sarg.Columns.Count).Value = sarg.Value
Set dfCell = dfCell.Offset(sarg.Rows.Count)
Next sarg
MsgBox "Values appended to worksheet """ & DST_NAME & """.", _
vbInformation, PROC_TITLE
End Sub

Find from InputBox, copy row of found cell without using .Select

I have a spreadsheet with over 10000 rows. I need to search it using InputBox (UPC field, input is from a barcode scanner).
I need to copy the row of the found cell, and paste it to another sheet.
This process should loop until the user cancels the InputBox.
I have done this, but it gives me an error on the SelectCells.Select line, but not every time.
Sub Scan()
Do Until IsEmpty(ActiveCell)
Dim Barcode As Double
Barcode = InputBox("Scan Barcode")
Dim ws As Worksheet
Dim SelectCells As Range
Dim xcell As Object
Set ws = Worksheets("Sheet1")
For Each xcell In ws.UsedRange.Cells
If xcell.Value = Barcode Then
If SelectCells Is Nothing Then
Set SelectCells = Range(xcell.Address)
Else
Set SelectCells = Union(SelectCells, Range(xcell.Address))
End If
End If
Next
SelectCells.Select
Set SelectCells = Nothing
ActiveCell.Rows("1:1").EntireRow.Select
Selection.Copy
Sheets("Sheet2").Select
ActiveSheet.Paste
Sheets("Sheet1").Select
Loop
End Sub
Copy Rows
Option Explicit
Sub Scan()
Const sName As String = "Sheet1"
Const Header As String = "Barcode"
Const dName As String = "Sheet2"
Const dFirstCellAddress As String = "A2"
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
Dim surg As Range: Set surg = sws.UsedRange
Dim slCell As Range
Set slCell = surg.Cells(surg.Rows.Count, surg.Columns.Count)
Dim shCell As Range
Set shCell = surg.Find(Header, slCell, xlFormulas, xlWhole, xlByRows)
If shCell Is Nothing Then
MsgBox "The cell containing the header '" & Header _
& "' was not found.", vbCritical
Exit Sub
End If
Dim sfCol As Long: sfCol = surg.Column
Dim srg As Range
Set srg = sws.Range(sws.Cells(shCell.Row + 1, sfCol), slCell)
Dim scColIndex As Long: scColIndex = shCell.Column - sfCol + 1
Dim scrg As Range: Set scrg = srg.Columns(scColIndex)
Dim SelectedRows As Range
Dim Barcode As Variant
Dim srIndex As Variant
Do
Barcode = InputBox("Scan Barcode")
If Len(CStr(Barcode)) = 0 Then Exit Do
If IsNumeric(Barcode) Then
srIndex = Application.Match(CDbl(Barcode), scrg, 0)
If IsNumeric(srIndex) Then
If SelectedRows Is Nothing Then
Set SelectedRows = srg.Rows(srIndex)
Else
Set SelectedRows = Union(SelectedRows, srg.Rows(srIndex))
End If
End If
End If
Loop
If SelectedRows Is Nothing Then
MsgBox "No scan results.", vbExclamation
Exit Sub
End If
Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
Dim dfCell As Range: Set dfCell = dws.Range(dFirstCellAddress)
Dim durg As Range: Set durg = dws.UsedRange
Dim dlRow As Long: dlRow = durg.Row + durg.Rows.Count - 1
Dim dlCell As Range
If dlRow < dfCell.Row Then
Set dlCell = dfCell
Else
Set dlCell = dws.Cells(dlRow + 1, dfCell.Column)
End If
SelectedRows.Copy dlCell
MsgBox "Rows copied.", vbInformation
End Sub
You can try something like this:
Sub Scan()
Dim Barcode As String, rngData As Range, m, rngDest As Range
'Column with barcodes
With Worksheets("Sheet1")
Set rngData = .Range("D1", .Cells(Rows.Count, "D").End(xlUp))
End With
'First paste postion
Set rngDest = Worksheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Offset(1)
Do
Barcode = InputBox("Scan Barcode")
If Len(Barcode) = 0 Then Exit Do
'm = Application.Match(Barcode, rngData, 0) 'Barcodes formatted as text
m = Application.Match(CDbl(Barcode), rngData, 0) 'Barcodes formatted as numbers
If Not IsError(m) Then
rngData.Rows(m).EntireRow.Copy rngDest 'copy to Sheet2
Set rngDest = rngDest.Offset(1)
Else
'if no match then what?
Debug.Print "no match"
End If
Loop
End Sub
Depending on how your barcodes are stored (as text, or a numeric values) you may need to use CDbl(Barcode) inside the call to Match()

Find Cell Based only on Format [duplicate]

This question already has answers here:
Excel VBA, getting range from an inactive sheet
(3 answers)
Closed last year.
I'm trying to iterate through worksheets and find cells that have a font size of 22. Here is what I have so far, however I keep returning the value of the first found term over and over again as it iterates through the sheets. I'm assuming I'll need to incorporate a FindNext in there somewhere?
Sub FindFormatCell()
Dim ws As Worksheet
Dim rngFound As Range
With Application.FindFormat.Font
.Size = 22
End With
For Each ws In Worksheets
If ws.Tab.ColorIndex = 20 And ws.Visible = xlSheetVisible Then
Set rngFound = Cells.Find(What:="", SearchFormat:=True)
Debug.Print rngFound
End If
Next ws
Application.FindFormat.Clear
End Sub
The Find Method - A SearchFormat Search
Option Explicit
Sub FindFormatCell()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Application.FindFormat.Font.Size = 22
Dim ws As Worksheet
Dim sCell As Range
Dim srg As Range
Dim urg As Range
Dim FirstAddress As String
For Each ws In wb.Worksheets
If ws.Visible = xlSheetVisible And ws.Tab.ColorIndex = 20 Then
Set srg = ws.UsedRange
' "" - empty cells, "*" - occupied cells
Set sCell = srg.Find(What:="", _
After:=srg.Cells(srg.Rows.Count, srg.Columns.Count), _
LookIn:=xlValues, SearchOrder:=xlByRows, SearchFormat:=True)
If Not sCell Is Nothing Then
FirstAddress = sCell.Address
Do
If urg Is Nothing Then
Set urg = sCell
Else
Set urg = Union(urg, sCell)
End If
Set sCell = srg.FindNext(sCell)
Loop Until sCell.Address = FirstAddress
End If
If Not urg Is Nothing Then
' Start doing stuff here.
Debug.Print ws.Name, urg.Address(0, 0)
' End doing stuff here.
Set urg = Nothing
End If
End If
Next ws
Application.FindFormat.Clear
End Sub

Resources