check every cell in a range for a specific string? - excel

I want a VBA code by which I can check every cell in a range with a specific text?
EG: for each cell in range (a:a)
if value of cell = "specific text"
do this
else
do that
*
How to do this in VBA Excel?

here you go, but please try to find on google first
Sub eachCell()
Dim c As Range
For Each c In Range("A1:D21")
If (c.Value = "mytext") Then 'if value of cell = "specific text"
c.Value = "other text" 'do this
Else
c.Value = "other text 2" 'do that
End If
Next c
End Sub

Using a Find loop will be quicker than looking at each cell
Sub Sample_Find()
Dim rng1 As Range
Dim rng2 As Range
Dim bCell As Range
Dim ws As Worksheet
Dim SearchString As String
Dim FoundAt As String
Set ws = Worksheets(1)
Set rng1 = ws.Columns(1)
SearchString = "specific text"
Set rng2 = rng1.Find(SearchString, , xlValues, xlWhole)
If Not rng2 Is Nothing Then
Set bCell = rng2
FoundAt = rng2.Address
MsgBox "do something here " & FoundAt
Do
Set rng2 = rng1.FindNext(After:=rng2)
If Not rng2 Is Nothing Then
If rng2.Address = bCell.Address Then Exit Do
FoundAt = FoundAt & ", " & rng2.Address
MsgBox "do something here " & rng2.Address
Else
Exit Do
End If
Loop
Else
MsgBox SearchString & " not Found"
Exit Sub
End If
MsgBox "The Search String has been found these locations: " & FoundAt
Exit Sub
End Sub

Another option to answer your post, using the AutoFilter.
Code
Option Explicit
Sub Test_AutoFilter()
Dim ws As Worksheet
Dim SearchString As String
Dim Rng As Range
Dim VisRng As Range
Dim c As Range
Set ws = Worksheets(1)
Set Rng = ws.Columns(1)
SearchString = "specific text"
Rng.AutoFilter
Rng.AutoFilter Field:=1, Criteria1:=SearchString
' set another range to only visible cells after the Filter was applied
Set VisRng = ws.Range(Cells(1, 1), Cells(1, 1).End(xlDown)).SpecialCells(xlCellTypeVisible)
If Not VisRng Is Nothing Then
' Option 1: show every cell that a SearchString was found
For Each c In VisRng
MsgBox "String match of " & SearchString & " found as cell " & c.Address
Next c
' Option 2: show all the cells that SearchString was found (in 1 message)
MsgBox "String match of " & SearchString & " found as cells " & VisRng.Address
End If
End Sub

Related

VBA - Excel insert row above for each cell containing certain text

How do you go through the specific worksheet and in a specific column for every row that contains word "firewall" - then insert an empty row above? The Row with "firewall" may be followed by rows that contain other values. The last line in the column is always "Grand Total". I supposed can be used as condition to stop the loop.
I found on Stack Overflow this example which is almost exactly what I need, but it does it only once, and I need through the entire column for all matches. The worksheet should be specified.
Sub NewRowInsert()
Dim SearchText As String
Dim GCell As Range
SearchText = "Original"
Set GCell = Worksheets("Sheet2").Cells.Find(SearchText).Offset(1)
GCell.EntireRow.Insert
End Sub
My data example:
firewall abc
policy x
policy y
firewall xyz
policy z
policy xxx
Grand Total
Insert Rows (Find feat. Union)
Option Explicit
Sub NewRowInsert()
Const sText As String = "FirEWaLL"
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet: Set ws = wb.Worksheets("Sheet1")
Dim LastRow As Long: LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
Dim rg As Range: Set rg = ws.Range("A2:A" & LastRow)
Dim sCell As Range: Set sCell = rg.Find(sText, , xlFormulas, xlPart)
Application.ScreenUpdating = False
Dim trg As Range
Dim sCount As Long
If Not sCell Is Nothing Then
Dim FirstAddress As String: FirstAddress = sCell.Address
Do
If trg Is Nothing Then
Set trg = sCell
Else
Set trg = Union(trg, sCell.Offset(, sCount Mod 2))
End If
sCount = sCount + 1
Set sCell = rg.FindNext(sCell)
Loop Until sCell.Address = FirstAddress
trg.EntireRow.Insert
End If
Application.ScreenUpdating = True
Select Case sCount
Case 0
MsgBox "'" & sText & "' not found.", vbExclamation, "Fail?"
Case 1
MsgBox "Found 1 occurrence of '" & sText & "'.", _
vbInformation, "Success"
Case Else
MsgBox "Found " & sCount & " occurrences of '" & sText & "'.", _
vbInformation, "Success"
End Select
End Sub

How to search for a string across all the sheets faster in VBA?

I am tryng the search for a string across all sheets, the code below gets a string from each row in a column in one sheet and finds in another worksheet and then gets the formating of the corresponding cell for month.
The issue here is that it is very slow. How can I do this faster? is there a better way?
Sub colorstatus()
Application.ScreenUpdating = False
Range("H1").Activate
Dim c As Range
'//loop it
For Each c In Range(Range("H2"), Range("H2").End(xlDown))
est1 = Split(c, "_")(0) & "_" & Split(c, "_")(1)
ActiveWindow.ActivatePrevious
Dim ws As Worksheet
Dim ws1 As Worksheet
Dim est As Range
Dim strName As String
Dim status As Range
For Each ws1 In Worksheets
Columns.EntireColumn.Hidden = False
Rows.EntireRow.Hidden = False
Next
On Error Resume Next
strName = est1
For Each ws In Worksheets
With ws.UsedRange
Set est = .Find(What:="*" & strName & "*", After:=.Cells(1, 1), LookIn:=xlValues, LookAt:=xlWhole)
If Not est Is Nothing Then
ws.Activate
GoTo 0
End If
End With
Next ws
0
est.Activate
Set status = Cells.Find(What:="*May*", After:=Range("A1"), LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
, SearchFormat:=False)
Range(Split(status.Address, "$")(1) & est.row).Copy
ActiveWindow.ActivatePrevious
c.Offset(0, 11).PasteSpecial Paste:=xlPasteFormats
Next
End Sub
The below code loop all sheets and generate a message box with all sheets names have the value in. You can modify and try:
Sub Macro1()
Dim strSearch As String, strResults As String
Dim rngFound As Range
Dim ws As Worksheet
strSearch = "Test"
strResults = ""
For Each ws In ThisWorkbook.Worksheets
With ws
Set rngFound = .Cells.Find(strSearch, LookIn:=xlValues, Lookat:=xlWhole)
If Not rngFound Is Nothing Then
If strResults = "" Then
strResults = "Searching value, " & strSearch & ", appears in " & ws.Name
Else
strResults = strResults & ", " & ws.Name
End If
End If
End With
Next ws
If strResults <> "" Then
MsgBox strResults & "."
End If
End Sub
This piece of code will end either a message with the address for the cell which the word was found, or a message telling you that it didn't found the word:
Option Explicit
Sub colorstatus()
Application.ScreenUpdating = False
Dim ws As Worksheet
Dim cell As Range
Dim TheWord As String: TheWord = "dog_390"
For Each ws In ThisWorkbook.Sheets
Set cell = ws.Range("A:A").Find(TheWord, LookAt:=xlPart)
If Not cell Is Nothing Then
MsgBox "Word " & TheWord & "found in cell: " & cell.Address & " in worksheet: " & ws.Name
End
End If
Next ws
MsgBox "Word " & TheWord & " was not found on this workbook."
End Sub
Try the next code, please:
Sub colorstatus()
Dim sh As Worksheet, celFound As Range, strWord As String
Dim status As Range
strWord = "dog_390"
For Each sh In ActiveWorkbook.Sheets
Set celFound = sh.Range("A:A").Find(strWord, LookAt:=xlPart)
If Not celFound Is Nothing Then
Set status = sh.Rows(1).Find(What:="May", After:=sh.Range("A1"), LookAt:=xlPart)
If Not status Is Nothing Then
Debug.Print sh.Name, sh.cells(celFound.Row, status.Column).Interior.Color, sh.cells(celFound.Row, status.Column).Address
'do whatever you need with the found cell...
'....
Else
Debug.Print sh.Name, "No month found"
End If
Else
Debug.Print sh.Name, "No match found"
End If
Next sh
End Sub

Exit If and Next For

I have a for next loop with an if statement. If the "If statement" is true then exit the if and next for. Here is the code: What I want is if Rng1 is not with in Range1 then goto the next rng1. I seems like a simple solution, but I cannot figure is out. Thank you in advance.
Sub me_test()
Dim Range1 As Range
Dim Rng1 As Range
Set Range1 = Application.Selection
Set Range1 = Application.InputBox("Please Select Your Range :", xtitledID, Range1.Address, Type:=8)
For Each Rng1 In Range1
If Intersect(Rng1, Range("B7:B15")) Is Nothing Then
MsgBox "Not within the perscribed range." & vbCr & "Please click OK to continue."
Else
Rng1.Value = "Good"
End If
Next
MsgBox "All Done"
End Sub
Sub me_test()
Dim Range1 As Range
Dim Rng1 As Range
Set Range1 = Application.Selection
Set Range1 = Application.InputBox("Please Select Your Range :", xtitledID, _
Range1.Address, Type:=8)
Set Range1 = Application.Intersect(Range1, ActiveSheet.Range("B7:B15"))
If Range1 is nothing then
MsgBox "No valid cells selected!"
else
Range1.Value = "Good"
end if
End Sub
This should work. It works on my end
Sub me_test()
Dim Range1 As Range
Dim Rng1 As Range
Dim rngIntr As Range
Set Range1 = Application.Selection
Set Range1 = Application.InputBox("Please Select Your Range :", xtitledID, Range1.Address, Type:=8)
For Each Rng1 In Range1
Set rngIntr = Intersect(Rng1.Cells, Range("B7:B15").Cells)
If rngIntr Is Nothing Then
MsgBox "Not within the perscribed range." & vbCr & "Please click OK to continue."
Else
Rng1.Value = "Good"
End If
Set rngInr = Nothing
Next
Set Range1 = Nothing
Set Rng1 = Nothing
MsgBox "All Done"
End Sub
How about this: Only show the "Not within..." Msgbox if none of the selected cells are within the desired range. Otherwise continue to iterate through the selection and write Good in every cell that is intersecting with the desired range.
Sub me_test2()
Dim Range1 As Range
Dim Rng1 As Range
Set Range1 = Application.Selection
Set Range1 = Application.InputBox("Please Select Your Range :", xtitledID, Range1.Address, Type:=8)
If Intersect(Range("B7:B15"), Range1) Is Nothing Then
MsgBox "Not within the perscribed range." & vbCr & "Please click OK to continue."
Else
For Each Rng1 In Range1
If Not Intersect(Rng1, Range("B7:B15")) Is Nothing Then
Rng1.Value = "Good"
End If
Next
MsgBox "All Done"
End If
End Sub
Maybe:
Sub me_test()
Dim rng1 As Range
Set rng1 = Application.InputBox("Please Select Your Range :", xtitledID, Selection.Address, Type:=8)
If Union(rng1, Range("B7:B15")).Address = Range("B7:B15").Address Then
rng1.Value = "Good"
Else
MsgBox "Not within the perscribed range." & vbCr & "Please click OK to continue."
End If
MsgBox "All Done"
End Sub
You may also want to check for a valid used range selection:
Sub me_test()
Dim rng1 As Range
Do
Set rng1 = Application.InputBox("Please Select Your Range :", xtitledID, Selection.Address, Type:=8)
Loop While rng1 Is Nothing
If Union(rng1, Range("B7:B15")).Address = Range("B7:B15").Address Then
rng1.Value = "Good"
Else
MsgBox "Not within the perscribed range." & vbCr & "Please click OK to continue."
End If
MsgBox "All Done"
End Sub

Show comments for each sheet of a workbook in a MsgBox

I am trying to display all comment text for each worksheet in the Activeworkbook in a MsgBox (for each comment).
My code isn't throwing an error, so I know I am close.
Sub ShowAllWorkbookcomments()
On Error Resume Next
Dim ws As Worksheet
Dim rng As Range
Dim cell As Variant
Dim cmt As String
Dim commentcount As Integer
Set ws = ActiveWorkbook.Worksheets(1)
Set rng = ActiveSheet.Cells.SpecialCells(xlCellTypeComments)
commentcount = rng.Count
'cmt = ws.rng.Comment.Text
Dim varComment As String
Dim c As Comment
For Each ws In ActiveWorkbook.Worksheets
Select Case commentcount
Case 0
MsgBox "No Comment", vbExclamation
Resume Next
Case Is > 0
For Each cell In rng
varComment = c.Text
MsgBox varComment, vbInformation
Next cell
End Select
Set rng = Nothing
Next ws
End Sub
You were close, just needed to get the Set rng = ActiveSheet.Cells.SpecialCells(xlCellTypeComments) inside the For Each ws In ActiveWorkbook.Worksheets loop.
Also, added another way to trap the possibility of a worksheet having no comments, and removed the unnecessary Select Case.
Try the code below:
Option Explicit
Sub ShowAllWorkbookcomments()
Dim ws As Worksheet
Dim rng As Range
Dim cell As Range
Dim cmt As String
Dim varComment As String
For Each ws In ActiveWorkbook.Worksheets
On Error Resume Next
Set rng = ws.Cells.SpecialCells(xlCellTypeComments)
On Error GoTo 0
If Not rng Is Nothing Then '<-- current worksheet has comments
For Each cell In rng.Cells
'varComment = cell.Comment.text
varComment = "worksheet " & ws.Name & " comment " & cell.Comment.text ' <-- added the worksheet name as reference
MsgBox varComment, vbInformation
Next cell
Else '<-- current worksheet has No comments >> rng is Nothing
'MsgBox "No Comment", vbExclamation
MsgBox "worksheet " & ws.Name & " has No Comments", vbExclamation ' <-- added the worksheet name as reference
End If
Set rng = Nothing
Next ws
End Sub
As mentioned in one of the comments above, the above logic will cause the MsgBox to be shown for each of the cells in a merged range. The following logic will loop-through the comments in a given sheet, it will work for merged rows/cols scenario as well.
For Each CommentedSheets In ActiveWorkbook.Worksheets
If CommentedSheets.Comments.Count = 0 Then
MsgBox "worksheet " & CommentedSheets.Name & " has No Comments", vbExclamation
Else
For Each Individual_Comment In CommentedSheets.Comments
varComment = "worksheet " & CommentedSheets.Name & " comment " & Individual_Comment.text
MsgBox varComment, vbInformation

VBA Calculate percentage

So i need some help. Im pretty new to VBA so im having some trouble.
Well i have multiple sheets in my work book (excel). what im trying to do is, calculate the percentage of how many cells have the word "IMCOMPLETE" in column D and putting the outcome in the main sheet on a certain cell. Example:
Sub Get_Percentage()
If Range("Jackson,_Mr._Vince_R.TrainingSt'!D2:D100").Value = "IMCOMPLETE" Then
put outcome in "TotalSummery%"!E2
If Range("Carter,_Mr._Oscar_R_(Oscar)Trai'!D2:D100").Value = "IMCOMPLETE" Then
put outcome in "TotalSummery%"!E4
If Range("Taravella,_Mr._Jim_(Jim)Trainin'!D2:D100") Value = "IMCOMPLETE" Then
put outcome in "TotalSummery%"!E5
End Sub
FYI: I have like 10 sheet tabs. Not sure if this would be a macro.
Sub FindAndCountWordInExcelWorkBook(Byval SearchString As String)
SearchString = "IMCOMPLETE"
Dim oRange As Range, aCell As Range, bCell As Range
Dim ws As Worksheet
Dim ExitLoop As Boolean
Dim FoundAt As String
On Error GoTo Err
Dim i As Integer
For i = 1 To Worksheets.Count
Set ws = Worksheets(i)
Set oRange = ws.UsedRange
Dim CountOfKeyWord As Integer
Set aCell = oRange.Find(What:=SearchString, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
Set bCell = aCell
FoundAt = aCell.Address
Do While ExitLoop = False
Set aCell = oRange.FindNext(After:=aCell)
If Not aCell Is Nothing Then
If aCell.Address = bCell.Address Then Exit Do
CountOfKeyWord = CountOfKeyWord + 1
FoundAt = FoundAt & ", " & aCell.Address
Else
ExitLoop = True
End If
Loop
Else
' MsgBox SearchString & " not Found"
End If
Next i
MsgBox "The Search String: " & SearchString & ", appeared " & CountOfKeyWord & " times at these locations: " & FoundAt
Exit Sub
Err:
MsgBox Err.Description
End Sub
Here is a simple way to do it. I am doing it for one sheet. You can use it in a loop
Sub Sample()
Dim ws As Worksheet
Dim SearchText As String
Dim WordCount As Long, ColDTotalWordCount As Long
Dim PercentageWord As Double
Set ws = ThisWorkbook.Sheets("Sheet1")
SearchText = "IMCOMPLETE"
With ws
'~~> Count the occurances of the word "IMCOMPLETE"
WordCount = Application.WorksheetFunction.CountIf(.Columns(4), SearchText)
'~~> Count the total words in Col D
ColDTotalWordCount = Application.WorksheetFunction.CountA(.Columns(4))
'~~> Calculate Percentage
PercentageWord = WordCount / ColDTotalWordCount
Debug.Print Format(PercentageWord, "00.00%")
End With
End Sub
The above code can be also converted to a function which can be very useful when you are looping through the sheets.
Option Explicit
Sub Sample()
Dim wSheet As Worksheet
Dim TextToSearch As String
Set wSheet = ThisWorkbook.Sheets("Sheet1")
TextToSearch = "IMCOMPLETE"
Debug.Print GetPercentage(wSheet, TextToSearch)
End Sub
Function GetPercentage(ws As Worksheet, SearchText As String) As String
Dim WordCount As Long, ColDTotalWordCount As Long
Dim PercentageWord As Double
With ws
'~~> Count the occurances of the word "IMCOMPLETE"
WordCount = Application.WorksheetFunction.CountIf(.Columns(4), SearchText)
'~~> Count the total words in Col D
ColDTotalWordCount = Application.WorksheetFunction.CountA(.Columns(4))
'~~> Calculate Percentage
PercentageWord = WordCount / ColDTotalWordCount
GetPercentage = Format(PercentageWord, "00.00%")
End With
End Function

Resources