This question already has an answer here:
Can the Excel VBA Range.Find method be used to find multiple values?
(1 answer)
Closed 1 year ago.
I have a find function that search through a column, and there might be more than one result. Which I would like to store in a range (instead of a separate array for example).
This is what I have:
Dim searchRange As Range
Set searchRange = ActiveWorkbook.Sheets(SHEET).Range(SEARCHFOLDERCOLUMN & SEARCHSTARTROW & ":" & SEARCHFOLDERCOLUMN & lastRow)
'search for value
Dim searchResult As Range
Dim firstAddress As String
Set searchResult = searchRange.Find(what:=sSearchFolder, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
If Not searchResult Is Nothing The
firstAddress = searchResult.Address
Do
'search for the next one
Debug.Print searchResult.Address
Set searchResult = searchRange.FindNext(searchResult)
'^^^^^ union instead of this ???
'avoid endless loop, when hitting back the first address
If firstAddress = searchResult.Address Then
'Set searchResult = tempSearchResult
Exit Do
End If
Loop While Not searchResult Is Nothing
End If
Debug.Print "out of loop"
My output:
$M$125
$M$148
$M$161
out of loop
How can I get a range like: "$M$125, $M$148, $M$161" ? Where the columns (or rows?) or 3 instead of 1 like I have now.
Thanks for your help.
Reference a 'FindNext Multi Range'
Option Explicit
Sub DebugPrintCCRGtest()
' Needs 'DebugPrintCCRG', 'RefColumn' and 'RefCriteriaColumnRange'.
DebugPrintCCRG ""
DebugPrintCCRG "Yes"
DebugPrintCCRG "No"
DebugPrintCCRG "2"
' Example Results:
' A4,A8:A9,A17
' A2:A3,A7,A12:A14,A21
' A6,A15:A16,A18:A19
' A5,A10:A11,A20
End Sub
Sub DebugPrintCCRG( _
ByVal Criteria As String)
' Needs 'RefColumn' and 'RefCriteriaColumnRange'.
Dim sFirst As String: sFirst = "A2"
Dim ws As Worksheet: Set ws = ActiveSheet ' be more specific
Dim crg As Range: Set crg = RefColumn(ws.Range(sFirst))
If crg Is Nothing Then Exit Sub
Dim ccrg As Range: Set ccrg = RefCriteriaColumnRange(crg, Criteria)
If ccrg Is Nothing Then Exit Sub
Debug.Print ccrg.Address(0, 0)
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Creates a reference to the one-column range from the first cell
' of a range ('FirstCell') to the bottom-most non-empty cell
' of the first cell's worksheet column.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefColumn( _
ByVal FirstCell As Range) _
As Range
If FirstCell Is Nothing Then Exit Function
With FirstCell.Cells(1)
Dim lCell As Range
Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , , xlPrevious)
If lCell Is Nothing Then Exit Function
Set RefColumn = .Resize(lCell.Row - .Row + 1)
End With
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Creates a reference to the range combined from all the cells
' of a one-column range ('crg'), whose values are equal
' to a string ('Criteria').
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefCriteriaColumnRange( _
ByVal crg As Range, _
ByVal Criteria As String) _
As Range
If crg Is Nothing Then Exit Function
Dim cCell As Range: Set cCell = crg.Find(Criteria, _
crg.Cells(crg.Cells.Count), xlFormulas, xlWhole)
If cCell Is Nothing Then Exit Function
Dim drg As Range: Set drg = cCell
Dim FirstAddress As String: FirstAddress = cCell.Address
Do
Set drg = Union(drg, cCell)
Set cCell = crg.FindNext(cCell)
Loop Until cCell.Address = FirstAddress
If drg Is Nothing Then Exit Function
Set RefCriteriaColumnRange = drg
End Function
Related
in my workbook Column I contains Dates.
I can get last Row easily by:
Dim LastRow As Long
LastRow = ActiveSheet.Cells(Rows.Count, "I").End(xlUp).Row
I need to put Row of that column in variable (Long) if first occurrence cell contains today.
actually , the expected code like this:
Set Rng = ActiveSheet.Range("I" & FirstRow & ":I" & LastRow)
Note: using VBA AutoFilter is not applicable on my workbook , Because it is protected and shared on the same time
Please, test the next simple code. All credit should go to #Simon, who clearly described what is to be done. I only put it in place, using a Variant (mtch) variable, able to be checked even if an error (in case of no any match) occurs:
Since your data in I:I does mean Time (something as 03.01.2022 21:27:37), the range must be corrected for the Date Long value to be matched. Please, test the code:
Sub firstCellTest()
Dim sh As Worksheet, firstCell As Long, lastCell As Long, rng As Range, mtch, arr
Set sh = ActiveSheet
lastCell = sh.Range("I" & sh.rows.Count).End(xlUp).row
Set rng = sh.Range("I1:I" & lastCell)
arr = Evaluate("INDEX(int(" & rng.Address & "),0)") 'place in an array only the Date part of existing time
mtch = Application.match(CLng(Date), arr, 0)
If IsNumeric(mtch) Then
firstCell = mtch
Set rng = sh.Range("I" & firstCell, "I" & lastCell)
Else
MsgBox "Today date could not be found..."
End If
If Not rng Is Nothing Then Debug.Print rng.Address
End Sub
Reference a Range Using the Find Method
This solution will find the first occurrence of today's date in a column and create a reference to the range from this cell to the bottom-most non-empty cell in the same column.
The RefTodaysRangeTEST procedure illustrates how to use the RefTodaysRange function (the way to go).
The TodaysRange procedure does the same thing without using a function yet cluttering your code.
The TodaysRangeDebugPrintStudy procedure prints the range addresses at the various stages to the Immediate window (Crtl+G).
Option Explicit
Sub RefTodaysRangeTEST()
Const fCellAddress = "A3"
Dim ws As Worksheet: Set ws = ActiveSheet
Dim fCell As Range: Set fCell = ws.Range(fCellAddress)
Dim trg As Range: Set trg = RefTodaysRange(fCell)
' Continue, e.g.:
If Not fCell Is Nothing Then
MsgBox "Today's Range Address: " & trg.Address(0, 0)
Else
MsgBox "Today's Range Address: not available."
End If
End Sub
Function RefTodaysRange( _
FirstCell As Range) _
As Range
If FirstCell Is Nothing Then Exit Function
Dim lCell As Range ' last (bottom-most) non-empty cell
Dim fCell As Range ' first (top-most) cell containing today's date
With FirstCell
Dim crg As Range
Set crg = .Resize(.Worksheet.Rows.Count - .Row + 1)
Set lCell = crg.Find("*", , xlFormulas, , , xlPrevious)
If lCell Is Nothing Then Exit Function ' no data
Set crg = .Resize(lCell.Row - .Row + 1)
Set fCell = crg.Find(Date, lCell, xlValues, xlWhole)
If fCell Is Nothing Then Exit Function ' today's date not found
End With
Set RefTodaysRange = fCell.Resize(lCell.Row - fCell.Row + 1)
End Function
Sub TodaysRange()
Const fCellAddress = "A3"
Dim ws As Worksheet: Set ws = ActiveSheet
Dim fCell As Range: Set fCell = ws.Range(fCellAddress)
Dim crg As Range: Set crg = fCell.Resize(ws.Rows.Count - fCell.Row + 1)
Dim lCell As Range: Set lCell = crg.Find("*", , xlFormulas, , , xlPrevious)
If lCell Is Nothing Then Exit Sub ' no data from 'fCell' to the bottom
Set crg = fCell.Resize(lCell.Row - fCell.Row + 1)
Set fCell = crg.Find(Date, lCell, xlValues, xlWhole)
If fCell Is Nothing Then Exit Sub ' today's date not found
Set crg = ws.Range(fCell, lCell)
End Sub
Sub TodaysRangeDebugPrintStudy()
Const fCellAddress = "A3"
Dim ws As Worksheet: Set ws = ActiveSheet
Debug.Print "Worksheet: " & ws.Name
Dim fCell As Range: Set fCell = ws.Range(fCellAddress)
Debug.Print "First Cell: " & fCell.Address(0, 0)
Dim crg As Range: Set crg = fCell.Resize(ws.Rows.Count - fCell.Row + 1)
Debug.Print "Column Range: " & crg.Address(0, 0)
Dim lCell As Range: Set lCell = crg.Find("*", , xlFormulas, , , xlPrevious)
If lCell Is Nothing Then Exit Sub ' no data from 'fCell' to the bottom
Debug.Print "Last Cell: " & lCell.Address(0, 0)
Set crg = fCell.Resize(lCell.Row - fCell.Row + 1)
Debug.Print "Column Range: " & crg.Address(0, 0)
Set fCell = crg.Find(Date, lCell, xlValues, xlWhole)
If fCell Is Nothing Then Exit Sub ' today's date not found
Debug.Print "First Cell: " & fCell.Address(0, 0)
Set crg = ws.Range(fCell, lCell)
Debug.Print "Column Range: " & crg.Address(0, 0)
End Sub
How can highlight in yellow a cell that have a specific word in it?
I have data in colum B and F with the word "No Game".
How can I have this in a vba in excel?
Thanks
Although this question has already been answered, I'd take my chance, showing how easy this is using conditional formatting (screenshots are minimised a bit):
Result looks like this:
Good luck
Highlight Matches (For Each...Next)
Copy the complete code into a standard module, e.g. Module1.
Adjust (play with) the values in the constants section.
Option Explicit
Sub HighlightColumns()
' Needs the 'RefColumn' and 'RefCombinedRange' functions.
Const ProcTitle As String = "Highlight Columns"
Const wsName As String = "Sheet1"
Const FirstCellsList As String = "B2,H2"
Const hCriteria As String = "No Game"
Const hColor As Long = vbYellow
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
' Write the list of the first cells' addresses to an array ('FirstCells').
Dim FirstCells() As String: FirstCells = Split(FirstCellsList, ",")
Dim scrg As Range ' Source Column Range
Dim sfCell As Range ' Source First Cell
Dim sCell As Range ' Source Cell
Dim hrg As Range ' Highlight Range
Dim n As Long ' Columns Counter
' Combine all matching cells into the Highlight Range.
For n = 0 To UBound(FirstCells)
Set sfCell = ws.Range(FirstCells(n))
Set scrg = RefColumn(sfCell)
If Not scrg Is Nothing Then ' found data in column range
For Each sCell In scrg.Cells
If StrComp(CStr(sCell.Value), hCriteria, vbTextCompare) = 0 Then
Set hrg = RefCombinedRange(hrg, sCell)
'Else ' not a match
End If
Next sCell
Set scrg = Nothing
'Else ' no data in current column range
End If
Next n
' Highlight and inform.
If Not hrg Is Nothing Then ' Highlight Criteria found
hrg.Interior.Color = hColor
MsgBox "Highlighted cells equal to '" & hCriteria & "'.", _
vbInformation, ProcTitle
Else ' no Highlight Criteria found
MsgBox "No occurrences of '" & hCriteria & "' found.", _
vbExclamation, ProcTitle
End If
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Creates a reference to the one-column range from the first cell
' of a range ('FirstCell') to the bottom-most non-empty cell
' of the first cell's worksheet column.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefColumn( _
ByVal FirstCell As Range) _
As Range
If FirstCell Is Nothing Then Exit Function
With FirstCell.Cells(1)
Dim lCell As Range
Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , , xlPrevious)
If lCell Is Nothing Then Exit Function
Set RefColumn = .Resize(lCell.Row - .Row + 1)
End With
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Creates a reference to a range combined from two ranges.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefCombinedRange( _
ByVal CombinedRange As Range, _
ByVal AddRange As Range) _
As Range
If CombinedRange Is Nothing Then
Set RefCombinedRange = AddRange
Else
Set RefCombinedRange = Union(CombinedRange, AddRange)
End If
End Function
I'd like to know how to write this range changing "G" to a string variable strColumn.
This is the code I want to change:
Dim lastRowElemento As Integer
lastRowElemento = Cells(Rows.Count, "G").End(xlUp).Row
Set rngElemento = ws.Range("G2:G" & lastRowElemento)
Applying OP's method, try this:
Sub TEST()
Dim ws As Worksheet, Rng As Range, sCol As String
sCol = "G"
Set ws = ThisWorkbook.Sheets("TEST") 'change as required
With ws.Columns(sCol)
Set Rng = Range(.Cells(2), .Cells(.Rows.Count).End(xlUp))
End With
End Sub
Reference a 'Non-Empty' Column Range
There are actually two requirements:
ColumnString = G (I prefer string since e.g. XFD are letters)
FirstRow = 2
If you put them together, you get G2 (think one, instead of two variables).
Since using the Find method is more reliable than using the End property in finding the bottom-most (last) non-empty cell in a column, I used it to write the RefColumn function which in your case can be utilized in the following way:
Set rngElemento = RefColumn(ws.Range("G2"))
I'll leave it up to you if you're going to test if there is data (usually you know there is), but I prefer to keep at least a 'simplified' test in the code:
If rngElemento is Nothing Then Exit Sub ' no data
' Continue...
The Code
Option Explicit
Sub RefColumnTEST()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet: Set ws = wb.Worksheets("Sheet1")
Dim rg As Range: Set rg = RefColumn(ws.Range("G2"))
If rg Is Nothing Then ' the range 'G2:G1048576' is empty
MsgBox "No data.", vbCritical
Else
MsgBox rg.Address(0, 0), vbInformation
End If
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Creates a reference to the one-column range from the first cell
' of a range ('FirstCell') to the bottom-most non-empty cell
' of the first cell's worksheet column.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefColumn( _
ByVal FirstCell As Range) _
As Range
If FirstCell Is Nothing Then Exit Function
With FirstCell.Cells(1)
Dim lCell As Range
Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , , xlPrevious)
If lCell Is Nothing Then Exit Function
Set RefColumn = .Resize(lCell.Row - .Row + 1)
End With
End Function
Meeting Your Requirements
Similarly to my preferred way, you could use the RefData function:
Function RefData( _
ByVal ws As Worksheet, _
ByVal ColumnIndex As Variant) _
As Range
On Error GoTo ClearError
With ws.Columns(ColumnIndex).Resize(ws.Rows.Count - 1).Offset(1)
Set RefData = _
.Resize(.Find("*", , xlFormulas, , , xlPrevious).Row - 1)
End With
ProcExit:
Exit Function
ClearError:
Resume ProcExit
End Function
which you can utilize in the following way:
Set rngElemento = RefData(ws, "G")
Set rngElemento = RefData(ws, 7)
' or:
Const strColumn As String = "G"
Set rngElemento = RefData(ws, strColumn)
I would like to delete a certain range (3 rows & 19 columns) in excel that contains specific string (lns) on the top left of the range, repeatedly. They appear in different rows and columns, but the range size is always the same.
I have written a following code but nothing happens:
For Each vCell In ActiveSheet.UsedRange
If InStr(vCell.Value, "*lns*") Then
Range(Cells(vCell.Row, vCell.Column), Cells(vCell.Row + 2, vCell.Column + 18)).Delete shift:=xlShiftUp
End If
Next
It might be faster to locate the cells with Find
Option Explicit
Sub MyMacro()
Const ROW_SIZE = 3
Const COL_SIZE = 19
Const SEARCH = "lns"
Dim rng As Range, cel As Range
Dim n As Integer, s As Long
Set rng = ActiveSheet.UsedRange
Set cel = rng.Find(SEARCH, LookIn:=xlValues, lookat:=xlPart, _
searchdirection:=xlPrevious)
Do While Not cel Is Nothing
cel.Resize(ROW_SIZE, COL_SIZE).Delete shift:=xlShiftUp
n = n + 1
Set cel = rng.FindPrevious
If n > 1000 Then MsgBox "Code Error in Do Loop", vbCritical: Exit Sub
Loop
MsgBox n & " blocks deleted", vbInformation
End Sub
Delete Range 'Blocks'
Option Explicit
Sub DeleteBlocks()
Const rCount As Long = 3
Const cCount As Long = 19
Const Criteria As String = "lns"
Dim ws As Worksheet: Set ws = ActiveSheet
Dim rg As Range: Set rg = ActiveSheet.UsedRange
Dim fCell As Range
Set fCell = rg.Find(Criteria, rg.Cells(rg.Rows.Count, rg.Columns.Count), _
xlFormulas, xlPart, xlByRows)
Dim drg As Range ' Delete Range
Dim brg As Range ' Block Range
Dim fCount As Long ' Found Count
Dim FirstAddress As String
If Not fCell Is Nothing Then
FirstAddress = fCell.Address
Do
Set brg = Nothing
On Error Resume Next ' if in last 2 rows or 18 last columns
Set brg = Intersect(rg, fCell.Resize(rCount, cCount))
On Error GoTo 0
If Not brg Is Nothing Then
fCount = fCount + 1
Set drg = GetCombinedRange(drg, brg)
Set fCell = rg.FindNext(fCell)
End If
Loop Until fCell.Address = FirstAddress
If Not drg Is Nothing Then
drg.Delete Shift:=xlShiftUp
End If
If fCount = 1 Then
MsgBox "1 block deleted.", vbInformation, "DeleteBlocks"
Else
MsgBox fCount & " blocks deleted", vbInformation, "DeleteBlocks"
End If
Else
MsgBox "No blocks found.", vbExclamation, "DeleteBlocks"
End If
End Sub
Function GetCombinedRange( _
ByVal BuiltRange As Range, _
ByVal AddRange As Range) _
As Range
If BuiltRange Is Nothing Then
Set GetCombinedRange = AddRange
Else
Set GetCombinedRange = Union(BuiltRange, AddRange)
End If
End Function
I want to find, and highlight cells that have a particular value.
In this example I'm searching for the number 2.
The code finds and highlights the cells with the number 2, but it also highlights cells with the number 22, and 23 because they contain the number 2.
'Find Search Values on Sheet and Highlight
Sub Find_And_Highlight()
Dim Searchfor As String
Dim FirstFound As String
Dim Lastcell As Range
Dim FoundCell As Range
Dim rng As Range
Dim myRange As Range
Set myRange = ActiveSheet.UsedRange
Set Lastcell = myRange.Cells(myRange.Cells.Count)
Searchfor = "2"
Set FoundCell = myRange.Find(what:=Searchfor, after:=Lastcell)
'Test to see if anything was found
If Not FoundCell Is Nothing Then
FirstFound = FoundCell.Address
Else
GoTo NothingFound
End If
Set rng = FoundCell
'Loop until cycled through all finds
Do Until FoundCell Is Nothing
'Find next cell with Searchfor value
Set FoundCell = myRange.FindNext(after:=FoundCell)
'Add found cell to rng range variable
Set rng = Union(rng, FoundCell)
'Test to see if cycled through to first found cell
If FoundCell.Address = FirstFound Then Exit Do
Loop
'Highlight cells that contain searchfor value
rng.Interior.ColorIndex = 34
Exit Sub
'Error Handler
NothingFound:
MsgBox "No values were found in this worksheet"
End Sub
Please look at the comment provided by #Craig which you need to implement. i.e. you need to modify the Foundcell line like below:
Set FoundCell = myRange.Find(what:=Searchfor, after:=Lastcell, lookat:=xlWhole)
Caution: This option modifies the user's search settings in Excel so in future make sure to uncheck below option in the Find box.
However, since you are changing the background color of the cells, you really do not need VBA for this purpose. You can use Conditional Formatting | Highlight Cells Rules | Equal To as shown below:
And then fill in the value as appropriate:
Outcome will appear like this:
Highlight Found Cells
Uncomment the Debug.Print lines in the FindAndHighlight procedure to better understand its behavior.
Option Explicit
Sub FindAndHighlight()
' You could use these constants ('ByVal') as arguments of this procedure,
' when you could call it with 'FindAndHighlight "2", 34' from yet another
' procedure.
Const SearchString As String = "2"
Const cIndex As Long = 34
If ActiveSheet Is Nothing Then Exit Sub ' if run from add-in
If TypeName(ActiveSheet) <> "Worksheet" Then Exit Sub ' if e.g. chart
'Debug.Print "Worksheet Name: " & ActiveSheet.Name
Dim srg As Range: Set srg = ActiveSheet.UsedRange
'Debug.Print "Source Range Address: " & srg.Address(0, 0)
Dim frg As Range: Set frg = refFindStringInRange(srg, SearchString)
If frg Is Nothing Then
MsgBox "No occurrence of '" & SearchString & "' found in range '" _
& srg.Address(0, 0) & "' of worksheet '" & srg.Worksheet.Name _
& "'.", vbCritical, "Nothing Found"
Exit Sub
End If
'Debug.Print "Found Range Address: " & frg.Address(0, 0)
HighLightRangeUsingColorIndex frg, cIndex
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Creates a reference to a range combined of all cells
' whose contents are equal to a string.
' Remarks: The search is case-insensitive ('MatchCase') and is performed
' by rows ('SearchOrder') ascending ('SearchDirection',
' ('FindNext')), starting with the first cell ('After')
' of each area of the range.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function refFindStringInRange( _
ByVal SearchRange As Range, _
ByVal SearchString As String) _
As Range
If SearchRange Is Nothing Then Exit Function
Dim frg As Range
Dim arg As Range
Dim lCell As Range
Dim fCell As Range
Dim FirstAddress As String
For Each arg In SearchRange.Areas
Set lCell = arg.Cells(arg.Rows.Count, arg.Columns.Count)
Set fCell = Nothing
' By modifying the parameters of the arguments of the 'Find' method
' you can change the behavior of the function in many ways.
Set fCell = arg.Find(SearchString, lCell, xlFormulas, xlWhole, xlByRows)
If Not fCell Is Nothing Then
FirstAddress = fCell.Address
Do
If frg Is Nothing Then
Set frg = fCell
Else
Set frg = Union(frg, fCell)
End If
Set fCell = arg.FindNext(After:=fCell)
Loop Until fCell.Address = FirstAddress
End If
Next arg
If Not frg Is Nothing Then
Set refFindStringInRange = frg
End If
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Highlights the cells of a range using a color index.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub HighLightRangeUsingColorIndex( _
ByVal rg As Range, _
ByVal cIndex As Long)
If rg Is Nothing Then Exit Sub
If cIndex < 1 Or cIndex > 56 Then Exit Sub
rg.Interior.ColorIndex = cIndex
End Sub