Find Cell Based only on Format [duplicate] - excel

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

Related

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

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()

VBA to create sheets based on a list

I would like to automatically create sheets based on a list in sheet "Clients". This sheet has the names of clients (starting from cell A2) and the VBA code is reading this list and creates a sheet per cell value.
I found some code on this forum but it throws a 'Run-time error 450: Wrong number of arguments or invalid property assignment' on row 9 (Set MyRange2 = .Range(MyRange, .Rows.Count, "A").End(xlUp)). I'm not a VBA developer so searching for this error didn't really mean a lot to me. What could be wrong with this code?
Sub insertSheets()
Dim myCell As Range
Dim MyRange As Range
Dim MyRange2 As Range
With Sheets("Clients")
Set MyRange = .Range("A2")
Set MyRange2 = .Range(MyRange, .Rows.Count, "A").End(xlUp)
End With
For Each myCell In MyRange2
If Not myCell.Value = vbNullString Then
Sheets.Add After:=Sheets(Sheets.Count)
Sheets(Sheets.Count).Name = myCell.Value
End If
Next myCell
End Sub
Thanks for the help
Add Worksheets From a List
The Mistake
Set MyRange2 = .Range(MyRange, .Cells(.Rows.Count, "A").End(xlUp))
' or (no need for 'Set MyRange = .Range("A2")'):
'Set MyRange2 = .Range("A2", .Cells(.Rows.Count, "A").End(xlUp))
An Improvement
Option Explicit
Sub InsertSheets()
Dim sws As Worksheet: Set sws = ThisWorkbook.Worksheets("Clients")
Dim srg As Range
Set srg = sws.Range("A2", sws.Cells(sws.Rows.Count, "A").End(xlUp))
Dim sCell As Range
Dim sValue As Variant
Dim dws As Worksheet
Dim wsCount As Long
Dim ErrNum As Long
For Each sCell In srg.Cells
sValue = sCell.Value
If Not IsError(sValue) Then ' ignore error values
sValue = CStr(sValue)
If Len(sValue) > 0 Then ' ignore blanks
On Error Resume Next
Set dws = ThisWorkbook.Worksheets(sValue)
On Error GoTo 0
If dws Is Nothing Then
Set dws = ThisWorkbook.Worksheets.Add( _
After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
On Error Resume Next
dws.Name = sValue
ErrNum = Err.Number
On Error GoTo 0
If ErrNum = 0 Then ' valid name
wsCount = wsCount + 1
Else ' invalid name; delete the worksheet
Application.DisplayAlerts = False
dws.Delete
Application.DisplayAlerts = True
End If
' Else ' worksheet already exists; do nothing
End If
Set dws = Nothing
' Else ' is blank; do nothing
End If
' Else ' is error value; do nothing
End If
Next sCell
MsgBox "Worksheets created: " & wsCount
End Sub

Skipping worksheets without IF statements

I have some code here but I'd like it to skip worksheets names Aggregated, Collated Results, Template, End. I have tried to add an If statement in to skip these but it doesn't seem to like it.
Sub FillBlanks()
Dim ws As Worksheet
Dim rng1 As Range
Dim rng2 As Range
For Each ws In Worksheets
Set rng2 = ws.Range("L1:AB40")
On Error Resume Next
Set rng1 = rng2.SpecialCells(xlBlanks)
on error goto 0
if not rng1 is nothing then
Application.Iteration = True
rng1.FormulaR1C1 = "=AVERAGE(R[-1]C,R[1]C)"
Application.Iteration = False
rng2.Value = rng2.Value
end if
Next ws
End Sub
If you add the names of the sheets you want to skip to the line worksheetsToSkip = array("... (below), then the code below should skip said sheets.
Option Explicit
Sub FillBlanks()
Dim ws As Worksheet
Dim rng1 As Range
Dim rng2 As Range
Dim worksheetsToSkip As Variant
worksheetsToSkip = Array("Aggregated", "Collated Results", "Template", "End")
For Each ws In Worksheets
If IsError(Application.Match(ws.Name, worksheetsToSkip, 0)) Then
Set rng2 = ws.Range("L1:AB40")
On Error Resume Next
Set rng1 = rng2.SpecialCells(xlBlanks)
On Error GoTo 0
If Not rng1 Is Nothing Then
Application.Iteration = True
rng1.FormulaR1C1 = "=AVERAGE(R[-1]C,R[1]C)"
Application.Iteration = False
rng2.Value = rng2.Value
End If
End If
Next ws
End Sub

Resources