Im a beginner with Excel VBA
my question is if I have string in a cell like "MyNameIsHammadAndImFromIreland".
All cells have strings/sentences but there is no spaces.
How can I find if the cell includes the word "Ireland"?
The following VBA code will iterate through the used cells in a given worksheet and find any that match the given criteria. At the end, a message box is displayed showing a list of cells that contain the search term.
This functionality is equivalent to using the 'Find All' option you can choose when you use the normal find functionality available by pressing CTRL + F.
Option Explicit
Private Sub Find()
Dim rngResult As Range
Dim strToFind As String
'Set to your desired string to find
strToFind = "Ireland"
'If the string you are searching for is located in
'the worksheet somewhere, you can set the value
'like this: strToFind = Worksheets("Sheet1").Range("A1").Value
'This assumes your search term is in cell A1 of the
'Sheet1 worksheet.
'Look in the used range of a given worksheet
'Change Sheet1 to match your worksheet name
With Worksheets("Sheet1").UsedRange
'Find the first cell that contains the search term
Set rngResult = .Find(What:=strToFind, LookAt:=xlPart)
'If it is found, grab the cell address of where the
'search term can be found
If Not rngResult Is Nothing Then
Dim firstAddress As String, result As String
firstAddress = rngResult.Address
'Loop through the rest of the cells until returning
'to the first cell that we had a match in.
Do
'Record the cell address of the match
'to the result string
result = result & rngResult.Address & ","
'Go to next cell containing the search term
Set rngResult = .FindNext(rngResult)
'Exit the loop when we reach the starting point
Loop While rngResult.Address <> firstAddress
'Output the list of cells that contain the string to find
MsgBox "Found """ & strToFind & """ in cell(s): " & result
End If
End With
End Sub
Be sure to set strToFind to your desired string, and change Sheet1 to match the name of whichever sheet you want to search over.
You don't need VBA, just use a formula:
=IF(LEN(SUBSTITUTE(A1,"Ireland",""))<LEN(A1),"Word Found","Word NOT found")
If you really want VBA then:
hasWord = InStr(Range("A1").Value, "Ireland") > 0 '// returns TRUE or FALSE
Related
Trying to search for the cell location of a certain date.
I have a range of dates in dd-mm-yy form and need to be able to find the cell location of a date picked from a drop down menu. I was using a standard Range.Find function which works for searching for Non-dates but when searching for dates it returns error 91: Object variable or With block variable not set.
I have tried converting the dates to text format through both format cells and a =text function in excel prior to running the program but it still does not work.
I read somewhere about converting the date to match the internal format used by Excel (mm/dd/yy) but this didn't make a difference.
'Date to be searched
Set SDate = Sheets("Data").Range("F1")
'find function
Set oRange = Sheets("Planning").Range("A1:A50").Find(What:=Sdate, lookat:=xlWhole)
'Return Address
MsgBox oRange.Address
I expect to be able to search for a cell location and be given a cell location, in either A1 form or (1,1). Both will work.
You have merged cells, that's why it returns Nothing, try:
Sub finddate()
Set Sdate = Sheets("Data").Range("F1")
Set SearchRange = Sheets("Planning").Range("A1:A50")
If Not IsError(Application.Match(Sdate, SearchRange, 0)) Then
Set oRange = Cells(Application.Match(Sdate, SearchRange, 0), 1)
MsgBox oRange.Address
End If
End Sub
Another way to do it:
Sub findDate()
Dim sht As Worksheet
Set sht = ThisWorkbook.Worksheets("The name of your Worksheet")
Dim dateToFind As Date
dateToFind = sht.Range("F1").Value
Dim cell As Range
For Each cell In sht.Range("datesRng").Cells 'I am using a named range which contains the dates but you can use A1:A50 instead
If cell.Value = dateToFind Then
MsgBox cell.Address
End If
Next cell
End Sub
Combining .Find with date values is a tad tricky, as you found out yourself.
Try the following
Sub finddate()
'Date to be searched
Set SDate = Sheets("Data").Range("F1")
'find function
Set oRange = Sheets("Planning").Range("A1:A50").Find(What:=DateValue(Sdate), lookin:=xlFormulas)
'Return Address
MsgBox oRange.Address
End Sub
Im trying to make a VBA in excel that changes the content of a cell based on the text in the cells. All the cells I want to change contains a structure of "< (space) 0.005" the number however varies a lot and setting up all the different numbers would take too long.
I have a base for an older project but I can't seem to tweak it to the required needs.
Sub FillEmptyBlankCellWithValue()
Dim cell As Range
Dim InputValue As String
On Error Resume Next
InputValue = InputBox("Enter value that will fill empty cells in selection", _
"Fill Empty Cells")
For Each cell In Selection
If IsEmpty(cell) Then
cell.Value = InputValue
End If
Next
End Sub
You're on a right track. But in general I'd avoid using Selection or any other Select operations as they are prone to many errors.
Instead, I'd recommend using active (detected dynamic) range, or let the user define the range. eg.
Option Explicit
Private Sub fill_blanks
Dim ws as Worksheet: Set ws = Sheets("Sheet1") ' set yours
Dim firstcell as String, lastcell as String, fillvalue as String
Dim datarange as Range
firstcell = InputBox("Enter the starting cell of your data range")
lastcell = InputBox("Enter the last cell of your data range")
fillvalue = InputBox("Enter the value to fill blank cells with")
Set datarange = ws.Range(Trim(firstcell) & ":" & Trim(lastcell))
Dim cell as Range
For each cell in datarange
If IsEmpty(cell) Then
cell = fillvalue
End If
Next cell
End Sub
You could also let them define the range inside a pre-defined cells in
the worksheet, or detect the active range with .End(xlUp) for row
and .End(xlToLeft) for column. Up to you really..
Note: This will paste the result as a String (or "Text") as a Cell Format, you also need to change the Range.Format property.
I am working on a spreadsheet that will take a list of dates, and find those dates on a different sheet and populate some info in the cell below the matching date. The data to search through looks something like this:
ROW23: dates generated by formula (formatted: d-mmm)
ROW24: Mix of empty cells and cells with text and numbers.
ROW25: dates generated by formula (formatted: d-mmm)
ROW26: Mix of empty cells and cells with text and numbers.
and so on
This range is called "Calendar" and is Sheet9(B23:O74).
This list of dates to search are "List_Holidays" and is Sheet5(B9:B12,B16:B21). Once the date is located, the text to return in the cell below it is "List_HolAbbr" on Sheet5(A9:A12,A16:A21).
Currently I'm stuck on stage 1 of this code: Get it to run looking for only one date.
Stage 2 is to have it search for a list of dates.
Stage 3 is to have it only search through the rows that actually contain dates from the example above (skip the row of empty cells and cells with text/#s.
Stage 4: Have it populate the cell under the found date with some text.
My attempt so far:
Sub holidays()
Dim Cal As Range
Dim vholidays As Long
Dim cl As Range
Dim clgcaldate As Range
Set Cal = Sheets("2015_Consolidated").Range("Calendar")
'Find this
Set rgholidays = Worksheets("Holidays_EndPeriods").Range("F10") 'This is the date of the holiday to find in range Calendar
vholidays = DateValue(rgholidays)
MsgBox "vholidays is " & vholidays
'Search this range
MsgBox "g47 is: " & Sheets("2015_Consolidated").Cells(47, "G") 'G47 is the match to the cell in "rgholidays".
For Each cl In Cal
'With Range("List_Holidays)
Set rFound = Cells.Find(what:=vholidays, _
LookIn:=xlValues, _
lookat:=xlWhole, _
SearchOrder:=xlByRows) 'The cell in range Calendar that matches to vholidays
'Match found
If Not rFound Is Nothing Then
MsgBox "rFound is " & rFound
End If
'End With
Next cl
MsgBox "vholidays is " & vholidays & " and is located: " & rFound
End Sub`
The first 2 msgboxs are correct, but it does not find the match in G47.
I also tried this code, found at: Excel VBA - Using Find method on a range of dates
Second try, using the same variables as above.
`MsgBox "vhol is " & vholidays & " rghol is " & rgholidays
For Each cl In Cal
With rgholidays
Set rFound = .Find(vholidays, LookIn:=xlValues, lookat:=xlWhole)
If Not rFound Is Nothing Then
MsgBox cell
End If
End With
Next cl
End Sub`
Again, this does not return a match.
http://www.cpearson.com/excel/DateTimeVBA.htm recommends using DateValue() to convert the dates to a serial number, which seems reasonable to me and i tried it in the first example.
I've found some other references, but those are further removed from I'm trying to do.
Any suggestions to make this work?
Edit: I set a condition to test if the formats were the same for the search value and the value it should find. It said they were the same.
Testing the find/replace gui box on the spreadsheet, "find" does not locate the proper cell regardless of the find/replace settings.
Edit: I tried Application.Match. No match found. This loops through each column in the range looking for a match to the date, but doesn't find anything.
Sub holidays()
Dim Calendar As Range
Dim cl As Range
Dim rFound As Variant
Dim findthis As Double
Dim rng As Range
Dim Cal As Range
Set Cal = Sheets("2015_Consolidated").Range("Calendar")
findthis = CDate(CLng(Sheets("2015_Consolidated").Range("K17"))) '"1/13/2015"
Debug.Print "find this:" & findthis
Debug.Print "cell d23: " & ActiveSheet.Cells(23, 4)
For Each rng In Range("Calendar").Columns
Debug.Print rng.Address
rFound = Application.Match(findthis, rng.Address, 0)
If IsError(rFound) Then
Debug.Print "Not found"
Else
Debug.Print rFound
End If
Next rng
End Sub
Afer you set "Cal" and "rgholidays" variables in your code, try:
For each cell in Cal
if format(rgholidays,"m/d/yyyy")=format(cell,"m/d/yyyy") then
'Cell has the same date, do some code
endif
Next cell
When working with dates, another way to work with them is to format them yyyymmdd, then the larger numbers are always later then smaller ones, for example. This should get stage 1 of your question, to find the dates. Stage 2 and 4 should be some version of this code, combined with something you write. Stage 3 might be tricky, unless your line of non-dates is always constant.
When debugging or Quality Checking an Excel report at work I have found that the problem was because of text being hard coded inside a formula. I have heard this as being a Constant and Formula mixed cell.
Here are examples of what I see.
Constant =100
Constant =Facility
Formula cell =INDIRECT(ADDRESS(5,MATCH($A7&$B7&C$2,Data!$4:$4,0),,,$A$2))
Mixed cell =INDIRECT("Data!"&ADDRESS(5,MATCH($A7&$B7&C$2,Data!$4:$4,0)))
"Data!" is the Constant in the mixed cell, in this case the sheet name. If that sheet name ever changed, the formula would break. I have found and am using two conditional formats to highlight cells that are Constants and those that are formulas using this "Identify formulas using Conditional Formatting". I need to come up with a way to format those cells which contain these Constants inside of formulas.
I have found this question and tried using =IF(COUNT(SEARCH(CHAR(34),A1,1)),TRUE,FALSE) and FIND() to see if I could check if a cell had double quotes inside of it, but the SEARCH() returns FALSE since it is looking at the cells value and not it's contents. It returns TRUE if the cell contains "Constant" but if it is a formula it returns FALSE, such as if the cell contains ="Constant".
How can I find Constants inside formulas across a whole worksheet or workbook?
EDIT*
Thanks to Sidd's code below I have made a function in a module I can use in conditional formatting to at least highlight cells that contain quotes inside the cells.
Function FormulaHasQuotes(aCell)
If InStr(1, aCell.Formula, """") Then
FormulaHasQuotes = True
Else
FormulaHasQuotes = False
End If
End Function
Let's say your sheet looks like this.
Is this what you are trying?
Sub Sample()
Dim ws As Worksheet
Dim aCell As Range, FRange As Range
'~~> Set this to the relevant sheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
'~~> Find all the cells which have formula
On Error Resume Next
Set FRange = .Cells.SpecialCells(xlCellTypeFormulas)
On Error GoTo 0
If Not FRange Is Nothing Then
'~~> Check for " in the cell's formula
For Each aCell In FRange
If InStr(1, aCell.Formula, """") Then
Debug.Print "Cell " & aCell.Address; " has a constant"
End If
Next
End If
End With
End Sub
When you run the above code, you get this output
Cell $A$2 has a constant
Cell $A$5 has a constant
Note: I have shown you how to do it for a sheet, i am sure you can replicate it for all sheets in a workbook?
Only very lightly tested...
For example will not handle "string" constants which contain embedded "
Sub Tester()
'add reference to "Microsoft VBScript Regular Expressions 5.5"
Dim regxnum As New RegExp, regexpchar As New RegExp
Dim matches As MatchCollection, m As Match
Dim rngF As Range, c As Range
On Error Resume Next
Set rngF = ActiveSheet.UsedRange.SpecialCells(xlFormulas)
On Error GoTo 0
If Not rngF Is Nothing Then
regxnum.Pattern = "[^A-Z$](-?\d{1,}\.?\d{0,})"
regxnum.Global = True
regexpchar.Pattern = "(""[^""]{0,}"")"
regexpchar.Global = True
For Each c In rngF.Cells
Debug.Print c.Formula
Set matches = regxnum.Execute(c.Formula)
For Each m In matches
Debug.Print c.Parent.Name, c.Address(), m.SubMatches(0)
Next m
Set matches = regexpchar.Execute(c.Formula)
For Each m In matches
Debug.Print c.Parent.Name, c.Address(), m.SubMatches(0)
Next m
Next c
End If
End Sub
I have two worksheets, I want to use a value in sheet to_approve to lookup against column A in sheet submitted, then identify the cell reference so I can paste a value in the cell adjacent (column B).
I have used the following to identify the cell reference, but I don't know how to use it in VBA code.
=ADDRESS(MATCH(To_Approve!D19,Submitted!A:A,0),1,4,1,"submitted")
While many functions can be used in VBA using Application.WorksheetFunction.FunctionName ADDRESS is not one of these (MATCH is)
But even it it was available I would still use a Find method as below as it:
gives you the ability to match whole or part strings, case sensitive or not
returns a range object to work with if the value is found
readily handles a no match
you can control the point in the range being search as to where the search starts
multiple matches can be returned with FindNext
something like
Sub GetCell()
Dim ws As Worksheet
Dim rng1 As Range
Set ws = Sheets("submitted")
Set rng1 = ws.Columns("A").Find(Sheets("To_Approve").[d19], , xlValues, xlWhole)
If Not rng1 Is Nothing Then
MsgBox rng1.Address & " in sheet " & ws.Name
Else
MsgBox "not found", vbCritical
End If
End Sub
This example should give you an idea of how to find a corresponding value on another sheet and place a second value in the the column to the left. When using VBA, it is not necessary to select cells and then paste; you can directly enter a value into a range (cell) object.
Sub TransferValue()
Dim rngSearch As Range
Dim rngFind As Range
Dim dValue As Double
' initialization
Set rngSearch = Worksheets("to_approve").Range("D19")
dValue = Date
' find the match & insert value
Set rngFind = Worksheets("submitted").Columns(1).Find(What:=rngSearch.Value)
If Not rngFind Is Nothing Then
rngFind.Offset(ColumnOffset:=1).Value = dValue
End If
End Sub
(Note: dValue is a placeholder for whatever value you want to enter.)