I am working on a new Excel macro through VBA.
The idea of the macro is to hide all the rows that doesn't contain an exact match of the string provided. By exact match, I mean it should only be that. In this macro's case, the cell should ONLY contain "HPS" or "HPS". No mix of other words with it.
My range will be all visible cells under columns C, D, E, F. Can loops jump from 1 column to another?
This is my attempt code.
'②
'HPS有りエンドユーザー
Dim userHPS As Range
Dim criteriaArray As Variant
Dim filteredRange As Range
Dim i, lCell As Long
Dim match As Boolean
lastRow = Cells(3, "G").End(xlDown).row
Set userHPS = Range("C3:F" & lastRow).SpecialCells(xlCellTypeVisible)
criteriaArray = Array("HPS", "HPS")
match = True
Dim i As Integer, icount As Integer
'Dim FoundCell As Range, rng As Range
'Dim myRange As Range, LastCell As Range
'Set myRange = Range("C3:F" & lastRow).SpecialCells(xlCellTypeVisible)
'Set LastCell = myRange.Cells(myRange.Cells.Count)
'Set FoundCell = myRange.Find(What:=criteriaArray)
For i = 3 To lastRow
If InStr(1, Range("C3:F" & i), criteriaArray) > 0 Then
icount = icount + 1
End If
Next i
'If icount > 1 Then
'We will hide it so we can leave all rows containing "HPS" on the sheet. (EntireRow.Hidden = True)
'End If
The following script checks whether the keyword exists (exact match as OP expected) in the target columns, and hides the row if the keyword is not found.
Sub Demo()
Dim userHPS As Range, c As Range
Dim lastRow As Long
Const COL_CNT = 4
' get the last row
lastRow = Cells(Rows.Count, "G").End(xlUp).Row
If lastRow < 3 Then Exit Sub
' get the visible cells in Column C
On Error Resume Next
Set userHPS = Range("C3:C" & lastRow).SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If userHPS Is Nothing Then Exit Sub ' exit if no visible rows
Application.ScreenUpdating = False
For Each c In userHPS
If Not CheckHPS(c.Resize(1, COL_CNT)) Then
c.EntireRow.Hidden = True ' hidden row if no keyword(s)
End If
Next
Application.ScreenUpdating = True
End Sub
' Return True if keyword(s) is found in "Target"
Function CheckHPS(Target As Range) As Boolean
Dim c As Range, k
CheckHPS = False
For Each c In Target.Cells
For Each k In Array("HPS", "HPS")
' If InStr(1, c, k, vbTextCompare) > 0 Then
If c = k Then ' case sensitive
CheckHPS = True
Exit Function
End If
Next
Next
End Function