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

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

Related

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

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() returns "object variable or with block variable not set"

This block of code was working fine but I deleted some lines above Find() that broke it. Any ideas?
Sub CopySheet()
Dim TotalRow As Integer
Set NurselineBook = ThisWorkbook
TotalRow = Range("$C:$C").Find(What:="Grand Total", LookIn:=xlValues, LookAt:=xlWhole).Row
Range("A1:L" & TotalRow).Select
Range("Ah1").Activate
Selection.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
MsgBox "Dashboard Copied"
End Sub
Sub CopyTable()
Const wsName As String = "Sheet1"
Const ColumnsAddress As String = "A:L"
Const FirstRow As Long = 1
Const CriteriaColumn As Long = 3
Const gtString As String = "Grand Total"
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
Dim srg As Range
With ws.Columns(ColumnsAddress)
Set srg = .Resize(ws.Rows.Count - FirstRow + 1).Offset(FirstRow - 1)
End With
Dim gtcell As Range: Set gtcell = srg.Columns(CriteriaColumn) _
.Find(gtString, , xlValues, xlWhole, , xlPrevious)
If gtcell Is Nothing Then
MsgBox "Could not find '" & gtString & "'.", vbCritical
Exit Sub
End If
Dim drg As Range
Set drg = srg.Resize(gtcell.Row - FirstRow + 1)
drg.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
MsgBox "Dashboard Copied", vbInformation
End Sub

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

Loop through multiple files in folder and copy/paste to master file

I need to copy from multiple files in a specific folder and paste into a Master file. All files have a sheet called "Analysis", variable rows, but constant columns. I need to copy from all files the sheet "Analysis" A4:AB and paste in workbook called "Evaluations" in Sheet called "Evaluations" G2:AH, one below the other. I have the below code, which worked but doesn't anymore and I don't know why. Can you please help?
Sub CopyRange()
Application.ScreenUpdating = False
Dim wkbDest As Workbook
Dim wkbSource As Workbook
Set wkbDest = ThisWorkbook
Dim lastRow As Long
Const strPath As String = "V:\Trade Marketing\Trade Finance\2021\Projects\Evaluation\Analysis\"
ChDir strPath
strExtension = Dir("*.xls*")
Do While strExtension <> ""
Set wkbSource = Workbooks.Open(strPath & strExtension)
With wkbSource
lastRow = .Sheets("Analysis").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
.Sheets("Analysis").Range("A4:AB" & lastRow).Copy wkbDest.Sheets("Evaluations").Cells(Rows.Count, "G").End(xlUp).Offset(1, 0)
.Close SaveChanges:=False
End With
strExtension = Dir
Loop
Application.ScreenUpdating = True
End Sub
Backup Data Columns
Option Explicit
Sub AnalysisBackup()
Const swbPath As String _
= "V:\Trade Marketing\Trade Finance\2021\Projects\Evaluation\Analysis\"
Const swbPattern As String = "*.xls*"
Const sName As String = "Analysis"
Const sCols As String = "A:AB"
Const sFirstRow As Long = 4
Const dName As String = "Evaluations"
Const dFirst As String = "G2"
Dim swbName As String: swbName = Dir(swbPath & swbPattern)
If swbName = "" Then Exit Sub ' no file found
Dim dwb As Workbook: Set dwb = ThisWorkbook
Dim dws As Worksheet: Set dws = dwb.Worksheets(dName)
Dim cCount As Long: cCount = dws.Columns(sCols).Columns.Count
Dim dirrg As Range: Set dirrg = dws.Range(dFirst).Resize(, cCount)
Dim drrg As Range ' Destination First Row Range
Dim dlCell As Range ' Destination Last Cell
Set dlCell = dirrg.Resize(dws.Rows.Count - dirrg.Row + 1) _
.Find("*", , xlFormulas, , xlByRows, xlPrevious)
If dlCell Is Nothing Then
Set drrg = dirrg
Else
Set drrg = dirrg.Offset(dlCell.Row - dirrg.Row + 1)
End If
Dim swb As Workbook ' Source Workbook
Dim sws As Worksheet ' Source Worksheet
Dim srg As Range ' Source Range
Dim slCell As Range ' Source Last Cell
Dim srCount As Long ' Source Range Rows Count
Dim drg As Range ' Destination Range
Application.ScreenUpdating = False
Do While swbName <> ""
Set swb = Workbooks.Open(swbPath & swbName)
Set sws = Nothing
On Error Resume Next
Set sws = swb.Worksheets(sName)
On Error GoTo 0
If Not sws Is Nothing Then
Set slCell = Nothing
With sws.Rows(sFirstRow).Columns(sCols)
Set slCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , xlByRows, xlPrevious)
If Not slCell Is Nothing Then
srCount = slCell.Row - .Row + 1
Set srg = .Resize(srCount)
Set drg = drrg.Resize(srCount)
drg.Value = srg.Value
Set drrg = drrg.Offset(srCount)
'Else ' empty source range
End If
End With
'Else ' source worksheet does not exist
End If
swb.Close SaveChanges:=False
swbName = Dir
Loop
'dwb.Save
Application.ScreenUpdating = True
MsgBox "Analysis backup created.", vbInformation, "Analysis Backup"
End Sub

Resources